Contents

Python Commands for Beginners

An Introduction to Essential Python Commands for New Programmers

Website Visitors:

List of basic python commands and data types:

Assignments and Expressions

In Python, an assignment is a statement that binds a value to a variable. An expression is a combination of values, variables, and operators that evaluates to a single value.

Assignments

An assignment statement has the following syntax:

1
variable = expression

The left-hand side of the assignment operator (=) is a variable name, and the right-hand side is an expression that evaluates to a value. The value of the expression is assigned to the variable.

For example, the following assignment statement assigns the value of 10 to the variable x:

1
x = 10

Expressions

An expression is a combination of values, variables, and operators that evaluates to a single value. Expressions can be used to perform calculations, make comparisons, and control the flow of execution. Expressions are a combination of numbers, symbols, or other values that produce a result when evaluated.

There are many different types of expressions in Python. Some of the most common types of expressions include:

  • Arithmetic expressions: These expressions perform mathematical operations, such as addition, subtraction, multiplication, and division.
  • Logical expressions: These expressions evaluate to a Boolean value, which can be either True or False. Logical expressions are used to make comparisons and control the flow of execution.
  • Comparison expressions: These expressions compare two values and evaluate to a Boolean value.
  • String expressions: These expressions consist of a sequence of characters. String expressions can be used to create strings, print text, and format data.
  • List expressions: These expressions consist of a sequence of values. List expressions can be used to create lists, store data, and perform operations on lists.
  • Dictionary expressions: These expressions consist of a set of key-value pairs. Dictionary expressions can be used to create dictionaries, store data, and perform operations on dictionaries.

Expressions can be used in a variety of ways in Python. They can be used to perform calculations, make comparisons, and control the flow of execution. Expressions can also be used to create variables, objects, and data structures.

Keyword

A keyword is a reserved word in a programming language that performs a specific purpose. In your first Python example, you briefly encountered the keywords for and in. Note that keywords will often appear in bold in this course.

Values: True, False, None

Conditions: if, elif, else

Logical operators: and, or, not

Loops: for, in, while, break, continue

Functions: def, return

Print

  • print(): used to display a message or value on the console.
1
2
3
name = "John"
print("Hello", name) # Output: Hello John. If you use comma, it will automatically add space after the word Hello, in this example.
print("Hello " + name) # output: Hello John

Return

The return statement in Python is used to exit a function and specify the value to be returned to the caller of the function. When a return statement is executed in a function, that particular function execution is stopped and the code that follows will not be executed.

Example:

1
2
3
4
5
6
7
8
9
def CheckEven(number):
    if number % 2 == 0:
        return True
    return False

print(CheckEven(10))

# Output: True
10/2 is 0. So, it returns True and exits out of the function without running the next return command.

Input/Output Commands

  • print() - used to print output to the console
  • input() - used to take input from the user

Example:

1
2
name = input("Enter your name: ")
print("Hello,", name)

Variables and Data Types

Variable: Variable is an instance of a data type class, represented by a unique name within the code, that stores changeable values of the specific data type.

  • variable_name = value: used to assign a value to a variable.

  • Variable types:

    • Numeric: int, float, complex
    • String: str
    • Boolean: bool
    • NoneType: None
  • int - used to define integers

  • float - used to define floating-point numbers

  • bool - used to define boolean values

  • str - used to define strings

  • list - used to define lists

  • tuple - used to define tuples

  • set - used to define sets

  • dict - used to define dictionaries

Example:

1
2
3
4
5
6
7
8
age = 25  # integer
height = 5.7  # float
is_male = True  # boolean
name = "John"  # string
fruits = ["apple", "banana", "orange"]  # list
point = (3, 4)  # tuple
my_set = {1, 2, 3}  # set
my_dict = {"name": "John", "age": 25}  # dictionary

You can also use string concatenation like print(“Hello " + SomeVariable). Checkout this post on data types for more information:

Global variables vs local variables

In Python, a variable’s scope determines where it can be accessed and modified. There are two types of variable scopes: global and local.

A global variable is a variable that is defined outside of any function and can be accessed and modified from anywhere in the code. Global variables are often used to store data that needs to be shared between functions or modules.

A local variable is a variable that is defined inside a function and can only be accessed and modified within that function. Once the function exits, the local variable is destroyed and cannot be accessed from outside the function.

Here’s an example to illustrate the difference between global and local variables:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Global variable
x = 5

def my_function():
    # Local variable
    y = 10
    print("x inside function:", x)  # Access global variable inside function
    print("y inside function:", y)  # Access local variable inside function

my_function()

print("x outside function:", x)  # Access global variable outside function
print("y outside function:", y)  # This will raise an error because y is a local variable and cannot be accessed outside the function

In this example, x is a global variable that can be accessed and modified from anywhere in the code. Inside the my_function function, x is accessed as a global variable, and y is a local variable that can only be accessed inside the function. When we try to access y outside the function, it raises a NameError because y is not defined in the global scope. If you’d like to declare y as global variable, in the function, use global keyword before y as shown below:

1
2
3
4
5
6
def my_function():
    # Global variable
    global y
    y = 10
    print("x inside function:", x)  # Access global variable inside function
    print("y inside function:", y)  # Access local variable inside function

To delete a variable use del variableName. This will delete that variable name.

Converting Data Types in Python

In Python, data types can be converted from one type to another using built-in functions. There are two types of data type conversion: implicit and explicit.

Implicit data type conversion is performed automatically by the Python interpreter. This type of conversion is used when the data type of an expression is not explicitly specified. For example, if you add an integer and a float together, the Python interpreter will automatically convert the integer to a float before performing the addition operation.

Implicit conversion is where the interpreter helps us out and automatically converts one data type into another, without having to explicitly tell it to do so.

Explicit data type conversion is performed by the programmer using built-in functions. This type of conversion is used when the data type of an expression needs to be explicitly specified. For example, if you want to convert a string to an integer, you would use the int() function.

By contrast, explicit conversion is where we manually convert from one data type to another by calling the relevant function for the data type we want to convert to.

Here are some examples of implicit and explicit data type conversion in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# Implicit data type conversion
x = 1 + 2.5
print(x)
# Output: 3.5

# Explicit data type conversion
y = int("123")
print(y)
# Output: 123

x = 200
y = 200
z = x*y
print (str(z))
# Output: 40000
Here the output is a number but the python considers it as a string. 
Run `print(type(str(z)))` in the same terminal to see the data type of the variable z. It will show as str.

Sorted type

In Python, the sorted() function is used to sort the elements of a list, tuple, or any iterable in ascending order by default. It returns a new sorted list without modifying the original iterable.

Here’s an example of how to use sorted():

1
2
3
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_list = sorted(my_list)
print(sorted_list)

Type() function

The type() function in Python is used to get the type of an object. It returns the type of the object as a string.

Here’s an example of how to use type():

1
2
my_variable = 42
print(type(my_variable))

This will output <class 'int'>, indicating that my_variable is of type integer.

Max and Min Functions

The max() function returns the largest numeric input passed into it. The min() function returns the smallest numeric input passed into it.

1
2
3
time_list = [12, 2, 32, 19, 57, 22, 14]
print(min(time_list))
print(max(time_list))

None data type

In Python, None is a special constant representing the absence of a value or a null value. It is often used to signify that a variable or a function does not return anything.

1
2
3
4
def greeting(name)
    print("welcome" + name)
result = greeting("john") # Prints Welcome john
print(result) # output is none because there is nothing in result variable.

Comments

  • #: used to add comments in your code.

Arithmetic Operators

  • +: addition
  • -: subtraction
  • *: multiplication
  • /: division
  • //: integer division
  • %: modulus (remainder)
  • **: exponentiation

Comparison Operators

  • ==: equal to
  • !=: not equal to
  • >: greater than
  • <: less than
  • >=: greater than or equal to
  • <=: less than or equal to
  • = : assignment

Python comparison operators return Boolean results (True or False) with strings:

Expression Description
“a” == “a” If string “a” is identical to string “a”, returns True. Else, returns False. If the words are the same, return True. Else, return False.
“a” != “b” If string “a” is not identical to string “b”
“a” > “b” If string “a” has a larger Unicode value than string “b”
“a” >= “b” If the Unicode value for string “a” is greater than or equal to the Unicode value of string “b”
“a” < “b” If string “a”  has a smaller Unicode value than string “b”
“a” <= “b” If the Unicode value for string “a” is smaller than or equal to the Unicode value of string “b”

print("Wednesday" > "Friday") In Python, when comparing strings using the > (greater than) or < (less than) operators, it compares the strings lexicographically based on the Unicode values of their characters. Unicode values: A to Z, are from numbers 65 to 90. A is 65, B is 66, C is 67 and so on.. similarly, for values a to z, unicode value is from 97 to 122. a is 97, b is 98, c is 99 and so on…

In the case of “Wednesday” > “Friday”, the comparison evaluates to True. This is because in the Unicode character set, the letter “W” has a greater Unicode value than the letter “F”. Therefore, when comparing the two strings lexicographically, “Wednesday” is considered greater than “Friday”.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
print("Brown" < "brown")
True

print(5*2==10)
True

print(33!=10*3)
True

print(44 == 40+4)
True

print("a string" == "a string")
True

print("4 + 5" == 4 + 5)
False

print("rabbit" != "frog")
True

print("rabbit" = "frog")
False 
In Python, when using the == operator to compare two strings, it checks if the content of the strings is exactly the same character by character. As rabbit and frog doesn't have same characters, it is false.

event_city = "Shanghai"
print(event_city != "Shanghai")
False

print("three" == 3)
False

x = 2*3 > 6
print("The value of x is:")
print(x)

print("")  # Prints a blank line

print("The inverse value of x is:")
print(not x)

Logical Operators

  • and: logical and
  • or: logical or
  • not: logical not # can also be used as: print(not 55 = 'yellow')

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
x = 10
y = 5
print(x + y)  # 15
print(x - y)  # 5
print(x * y)  # 50
print(x / y)  # 2.0
print(x // y)  # 2
print(x % y)  # 0
print(x ** y)  # 100000
print(x == y)  # False
print(x != y)  # True
print(x > y)  # True
print(x < y)  # False
print(x >= y)  # True
print(x <= y)  # False
print(x > y and x > 0)  # True
print((6*3 >= 18) and (9+9 <= 36/2)) # True
print(x > y or x < 0)  # True
print(not(x > y))  # False

Check out more about operators in the Python Operators article here

Conditional Statements

  • if statement: used to check a condition and execute a block of code if the condition is true.
  • if-else statement: used to execute a block of code if the condition is true, and another block of code if the condition is false.
  • if-elif-else statement: used to execute a block of code if the first condition is true, another block of code if the second condition is true, and a final block of code if none of the conditions are true.

Example:

1
2
3
4
5
6
7
8
age = 25

if age < 18:
    print("You are not an adult.")
elif age >= 18 and age <= 65:
    print("You are an adult.")
else:
    print("You are a senior citizen.")

You can also specify if and else statements in a single liner like shown below:

1
2
result = "x is less than y" if x < y else "x is greater than y"
print (result)

We can also use return command for conditions like:

1
2
3
4
5
6
def checkXvalue(x):
    return x==10

print(checkXvalue(10))

# Output: True when value 10 is passed. Output will be false when any other value other than 10 is passed.
1
2
3
4
def is_even(number):
    if number % 2 == 0:
        return True
    return False

In the above example, if number % 2 ==0, then the program returns true and exits the function immediately. return false statement will only execute when number % 2 is not equal to 0. We can also specify conditions like this, instead of using else condition.

Loops

In Python, both the while loop and the for loop are used to execute a block of code repeatedly, but they differ in their approach and usage.

  1. while loop: The while loop is used when you don’t know the exact number of iterations in advance. A while loop executes the body of the loop while a specified condition remains True. They are commonly used when there’s an unknown number of operations to be performed, and a condition needs to be checked at each iteration. The loop continues to execute as long as the condition specified in the while statement is True. The condition is evaluated before each iteration of the loop. The loop will continue to execute until the condition becomes False.

    • Example:

      1
      2
      3
      4
      
      i = 0
      while i < 5:
          print(i)
          i += 1
      
  2. for loop:

    • The for loop is used when you know the exact number of iterations in advance.

    • The loop iterates over a sequence (such as a list, tuple, string, or range) and executes the block of code for each element in the sequence.

    • The loop variable takes on the value of each element in the sequence during each iteration.

    • Example:

      1
      2
      3
      4
      5
      6
      7
      8
      
      fruits = ['apple', 'banana', 'cherry']
      for fruit in fruits:
          print(fruit)
      
      # Example2:
      numbers = [1,2,3,4,5]
      sq_numbers = [x**2 for x in numbers]
      print(sq_numbers)
      

The main differences between while and for loops are:

  1. Iteration control:

    • while loop: The loop continues as long as the condition is True.
    • for loop: The loop iterates over a sequence, with the loop variable taking on the value of each element in the sequence.
  2. Readability and purpose:

    • while loop: Typically used when the number of iterations is not known in advance or when the loop needs to be controlled by a specific condition.
    • for loop: Typically used when the number of iterations is known in advance or when you want to iterate over a sequence of elements.
  3. Initialization and increment:

    • while loop: You need to initialize and increment the loop variable manually.
    • for loop: The loop variable is automatically assigned the next value from the sequence.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# for loop
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

# while loop
i = 0
while i < 5:
    print(i)
    i += 1

Use for loops when there’s a sequence of elements that you want to iterate. Use while loops when you want to repeat an action until a condition changes.

Range

In Python, the range function is used to generate a sequence of numbers. It’s often used in for loops to iterate over a sequence of numbers.

The basic syntax of the range function is:

1
range(start, stop, step)

Where:

  • start is the starting number of the sequence (inclusive). If omitted, it defaults to 0.
  • stop is the ending number of the sequence (exclusive).
  • step is the increment between numbers in the sequence. If omitted, it defaults to 1.

Note that with range function, the result would be one less than the stop number. If you want to print numbers from 10 to 30, then in your range function, you should specify as range(10,31) so that the last number 31 is omitted and numbers till 30 are printed.

Here are some examples of each type of range function in Python:

range(stop)

  • range(5) generates the sequence 0, 1, 2, 3, 4
  • range(10) generates the sequence 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
  • range(x+3, y, z) starts from a defined variable x, and adds 3 to it. if x is 2, then range starts from 5. range(5,y,z)

range(start, stop)

  • range(1, 6) generates the sequence 1, 2, 3, 4, 5
  • range(5, 10) generates the sequence 5, 6, 7, 8, 9
  • range(10, 15) generates the sequence 10, 11, 12, 13, 14

range(start, stop, step)

  • range(0, 10, 2) generates the sequence 0, 2, 4, 6, 8
  • range(1, 10, 3) generates the sequence 1, 4, 7
  • range(5, 20, 5) generates the sequence 5, 10, 15

Negative step

  • range(10, 0, -1) generates the sequence 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
  • range(10, 0, -2) generates the sequence 10, 8, 6, 4, 2

Large ranges

  • range(100) generates the sequence 0, 1, 2, ..., 99
  • range(1000, 2000) generates the sequence 1000, 1001, 1002, ..., 1999

Note that range returns an iterator, not a list. This means it’s memory-efficient and can be used with large ranges without consuming too much memory. If you need to convert a range object to a list, you can use the list function:

1
2
my_list = list(range(5))
print(my_list)  # [0, 1, 2, 3, 4]

Break

A break statement in Python provides a way to exit out of a loop before the loop’s condition is false. Once a break statement is encountered, the program’s control flow jumps out of the loop and continues executing the code after the loop.

1
2
3
4
while True:
    do_something_cool()
    if user_requested_to_stop():
        break

Inorder to stop the infinite loop, use the break command to exit out of the loop.

Pass

A pass statement in Python is a placeholder statement which is used when the syntax requires a statement, but you don’t want to execute any code or command.

Lists and Tuples

Lists

  • list_name = [value1, value2, ...]: used to create a list of values.
  • list.append(value): used to add a value to the end of a list.
  • list.insert(index, value): used to insert a value at a specific index in a list.
  • list.remove(value): used to remove the first occurrence of a value from a list.
  • list.pop(index): used to remove the value at a specific index from a list.
  • list.index(value): used to find the index of the first occurrence of a value in a list.
  • len(list): used to find the length of a list.
  • list[0]: starting value in the list

Complete details about lists are given here: Lists Explained

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
mylist = [0, 1, "two", 4.5,True, "false", "yes", "no"]
# To refer to a specific value in the list, you should use []
print (mylist[2])
print (mytuple[1])

#list values start from 0 when you refer them using []

# Display values from 1 to 5th place in mylist list. 
print (mylist[1:5]) #[1, 'two', 4.5, True]

# Display values from 1 to 8th place skipping second value.
print (mylist[1:8:2]) #[1, 4.5, 'false', 'no']

#Reverse values in list
print (mylist[::-1])

Tuples

  • tuple_name = (value1, value2, ...): used to create a tuple of values.
  • Tuples are immutable, which means their values cannot be changed once they are created.
  • len() - used to get the number of elements in a tuple
  • [] - used to access individual elements in a tuple

Complete details about tuples are given here:Tuples Explained

Example:

1
2
3
numbers = (1, 2, 3, 4, 5)
print(len(numbers))  # 5
print(numbers[2])  # 3

Set Operations

  • len() - used to get the number of elements in a set
  • add() - used to add an element to a set
  • remove() - used to remove an element from a set
  • union() - used to get the union of two sets (i.e., all unique elements from both sets)
  • intersection() - used to get the intersection of two sets (i.e., all elements that are common to both sets)
  • difference() - used to get the difference between two sets (i.e., all elements in the first set that are not in the second set)

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
s1 = {1, 2, 3, 4, 5}
s2 = {3, 4, 5, 6, 7}
print(len(s1))  # 5
s1.add(6)
print(s1)  # {1, 2, 3, 4, 5, 6}
s1.remove(2)
print(s1)  # {1, 3, 4, 5, 6}
print(s1.union(s2))  # {1, 3, 4, 5, 6, 7}
print(s1.intersection(s2))  # {3, 4, 5}
print(s1.difference(s2))  # {1, 6}

{ } are called sets in Python.

Dictionaries

In Python, a dictionary is a built-in data type that stores a unordered and random collection of key-value pairs. Dictionaries are mutable, meaning they can be modified after creation.

Here are some key features of dictionaries in Python:

  • Each key is unique and maps to a specific value.
  • Keys can be strings, integers, or any other immutable type.
  • Values can be any type, including strings, integers, lists, and even other dictionaries.
  • Dictionaries are unordered, meaning the order of the key-value pairs is not preserved and are used with {} brackets
  • You can access a value by its key using the square bracket notation, e.g., my_dict['key'].
  • You can add or update a key-value pair using the assignment operator, e.g., my_dict['new_key'] = 'new_value'.
  • You can remove a key-value pair using the del statement, e.g., del my_dict['key'].

Here are some ways to add and remove values from dictionaries in Python:

Adding values to a dictionary:

  1. Assignment: You can add a new key-value pair to a dictionary using the assignment operator (=).

    1
    2
    3
    
    my_dict = {'name': 'John', 'age': 30}
    my_dict['city'] = 'New York'
    print(my_dict)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
    
  2. Update method: You can use the update() method to add multiple key-value pairs to a dictionary at once.

    1
    2
    3
    
    my_dict = {'name': 'John', 'age': 30}
    my_dict.update({'city': 'New York', 'country': 'USA'})
    print(my_dict)  # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
    
  3. Dictionary comprehension: You can use dictionary comprehension to create a new dictionary with additional key-value pairs.

    1
    2
    3
    
    my_dict = {'name': 'John', 'age': 30}
    new_dict = {**my_dict, 'city': 'New York', 'country': 'USA'}
    print(new_dict)  # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
    

    Removing values from a dictionary:

  4. Del statement: You can use the del statement to remove a key-value pair from a dictionary.

    1
    2
    3
    
    my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
    del my_dict['age']
    print(my_dict)  # Output: {'name': 'John', 'city': 'New York'}
    
  5. Pop method: You can use the pop() method to remove a key-value pair from a dictionary and return the value.

    1
    2
    3
    4
    
    my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
    age = my_dict.pop('age')
    print(my_dict)  # Output: {'name': 'John', 'city': 'New York'}
    print(age)  # Output: 30
    
  6. Clear method: You can use the clear() method to remove all key-value pairs from a dictionary.

    1
    2
    3
    
    my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
    my_dict.clear()
    print(my_dict)  # Output: {}
    

    Note that if you try to remove a key that doesn’t exist in the dictionary, you’ll get a KeyError. You can use the in operator to check if a key exists in the dictionary before trying to remove it.

Examples:

  • dictionary_name = {key1: value1, key2: value2, ...}: used to create a dictionary of key-value pairs.
  • dictionary[key]: used to access the value associated with a key in a dictionary.
  • dictionary[key] = value: used to add or modify a key-value pair in a dictionary.
  • dictionary.keys(): used to get a list of keys in a dictionary.
  • dictionary.values(): used to get a list of values in a dictionary.
  • len() - used to get the number of key-value pairs in a dictionary
  • [] - used to access the value associated with a key in a dictionary

Example:

1
2
3
4
5
6
7
person = {"name": "John", "age": 25, "is_male": True}
print(len(person))  # 3
print(person["name"])  # John
print(person.keys())  # dict_keys(['name', 'age', 'is_male'])
print(person.values())  # dict_values(['John', 25, True])
print(person.items())  # dict_items([('name', 'John'), ('age', 25), ('is_male', True)])
print (person["name"]) # displays value John in output.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# Example1
file_counts = {"jpg":10, "txt":14, "csv":2, "py":23}
for ext, amount in file_counts.items():
  print("There are {} files with the .{} extension".format(amount, ext))

# Example2
file_counts = {"jpg":10, "txt":14, "csv":2, "py":23}
file_counts.keys()
file_counts.values()

#Example3
def email_list(domains):
    emails = []
    for domainname,users in domains.items():
      for user in users:
        emails.append(user+ "@" +domainname)

    return(emails)

print(email_list({"gmail.com": ["clark.kent", "diana.prince", "peter.parker"], "yahoo.com": ["barbara.gordon", "jean.grey"], "hotmail.com": ["bruce.wayne"]}))

Quick differences between set,list,string,tuple and dictionary:

Feature by Data Structure Dictionary Set List String Tuple
Definition Stores key:value pairs An unordered collection of unique elements A sequential, mutable collection of any data type A sequential, immutable collection of textual data A sequential, immutable collection of any data type
Representation { ‘a’:[42], ‘b’:[23,6,1] } {’^2’, ‘mc’, ’ equal’, ‘E’} [ ‘a’,‘b’, 3, 4 ] “call me ishmael” ( ‘commander’,’lambda’)
How to create? x = {}, x = dict() x = set() x = [], x = list() x = (), x = str() x = (‘a’,’b’,), x=tuple()
Is structure mutable and allow duplicate elements? immutable keys but mutable and duplicate values mutable but unique elements only mutable and allows duplicate elements immutable but allows duplicate elements immutable but allows duplicate elements
Is the structure iterable? no, it is unordered and random no, it is unordered and unique yes, and with numeric index assignment yes, but with a sequence of textual data yes, and with numeric index assignment

Dictionaries versus Lists

Dictionaries are similar to lists, but there are a few differences:

Both dictionaries and lists:

  • are used to organize elements into collections;

  • are used to initialize a new dictionary or list, use empty brackets;

  • can iterate through the items or elements in the collection; and

  • can use a variety of methods and operations to create and change the collections, like removing and inserting items or elements.

Dictionaries only:

  • are unordered sets;

  • have keys that can be a variety of data types, including strings, integers, floats, tuples;.

  • can access dictionary values by keys;

  • use square brackets inside curly brackets { };

  • use colons between the key and the value(s);

  • use commas to separate each key group and each value within a key group;

  • make it quicker and easier for a Python interpreter to find specific elements, as compared to a list.

Lists only:

  • are ordered sets;

  • access list elements by index positions;

  • require that these indices be integers;

  • use square brackets ;

  • use commas to separate each list element.

String Operations

  • len() - used to get the length of a string
  • + - used to concatenate strings
  • * - used to repeat a string
  • [] - used to access individual characters in a string

Checkout more about strings here: Strings Explained

Example:

1
2
3
4
5
6
message = "Hello, world!"
print(len(message))  # 13
print(message + " My name is John.")  # Hello, world! My name is John.
print(message * 3)  # Hello, world!Hello, world!Hello, world!
print(message[0])  # H
print(message[7:12])  # world

Slicing and Joining Strings

In Python, you can slice and join strings using various methods. Here are some examples:

Slicing Strings

You can slice a string using the [] operator, specifying the start and end indices. The syntax is string[start:stop:step].

  • start: The starting index of the slice (inclusive). Defaults to 0 if omitted.
  • stop: The ending index of the slice (exclusive). Defaults to the end of the string if omitted.
  • step: The increment between indices. Defaults to 1 if omitted.

Examples:

  • my_string = "hello"; print(my_string[1:4]) # Output: "ell"
  • my_string = "hello"; print(my_string[:4]) # Output: "hell"
  • my_string = "hello"; print(my_string[1:]) # Output: "ello"
1
2
3
4
5
6
7
8
string1 = "Greetings, Earthlings"
print(string1[0])   # Prints "G"
print(string1[4:8]) # Prints "ting"
print(string1[11:]) # Prints "Earthlings"
print(string1[:5])  # Prints "Greet"
print(string1[-10:])# Prints "Earthlings" again
print(string1[55:])# Prints empty string as the index is beyond end of string  
print(string1[::-1])# Prints "sgnilhtraE ,sgniteerG" ie., prints backwards.

Joining Strings

You can join multiple strings using the + operator or the join() method.

Using the + operator

Example: print("Hello, " + "world!") # Output: "Hello, world!"

Using the join() method

The join() method takes an iterable of strings as an argument and concatenates them with a separator.

Example: print(", ".join(["apple", "banana", "cherry"])) # Output: "apple, banana, cherry"

You can also use the join() method with a generator expression:

Example: print(" ".join(str(i) for i in range(5))) # Output: "0 1 2 3 4"

Combining slicing and joining strings

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
phonenum = '2025551212'
# The first 3 digits are the area code:
  area_code = "(" + phonenum[:3] + ")"

# The next 3 digits are called the “exchange”:
  exchange = phonenum[3:6]

# The next 3 digits are the line number:
  line = phonenum[-4:]

def format_phone(phonenum):
    area_code = "(" + phonenum[:3] + ")"
    exchange = phonenum[3:6]
    line = phonenum[-4:]
    return area_code + " " + exchange + "-" + line

List Operations

  • len() - used to get the length of a list
  • + - used to concatenate lists
  • * - used to repeat a list
  • [] - used to access individual elements in a list
  • append() - used to add an element to the end of a list
  • insert() - used to insert an element at a specific index in a list
  • remove() - used to remove an element from a list
  • pop() - used to remove and return the last element from a list
  • sort() - used to sort a list in ascending order
  • reverse() - used to reverse the order of elements in a list

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
fruits = ["apple", "banana", "orange"]
print(len(fruits))  # 3
print(fruits + ["grape"])  # ['apple', 'banana', 'orange', 'grape']
print(fruits * 2)  # ['apple', 'banana', 'orange', 'apple', 'banana', 'orange']
print(fruits[1])  # banana
fruits.append("pear")
print(fruits)  # ['apple', 'banana', 'orange', 'pear']
fruits.insert(2, "pineapple")
print(fruits)  # ['apple', 'banana', 'pineapple', 'orange', 'pear']
fruits.remove("banana")
print(fruits)  # ['apple', 'pineapple', 'orange', 'pear']
last_fruit = fruits.pop()
print(last_fruit)  # pear
print(fruits)  # ['apple', 'pineapple', 'orange']
fruits.sort()
print(fruits)  # ['apple', 'orange', 'pineapple']
fruits.reverse()
print(fruits)  # ['pineapple', 'orange', 'apple']

Branching

Branching in Python refers to the use of conditional statements to control the flow of a program. The most common branching statements in Python are if, elif (short for “else if”), and else.

Here’s a basic example of branching in Python using if, elif, and else:

1
2
3
4
5
6
7
8
x = 10

if x > 10:
    print("x is greater than 10")
elif x < 10:
    print("x is less than 10")
else:
    print("x is equal to 10")

In this example:

  • The if statement checks if x is greater than 10.
  • The elif statement checks if x is less than 10.
  • The else statement is executed if none of the above conditions are met.

You can have multiple elif statements to check for additional conditions. The code inside the block associated with the first true condition encountered will be executed, and the rest of the blocks will be skipped.

Functions

Block of code which is executed only when it is called. Repeated code is placed in this function block and it is called when needed in the script.

Defining Functions

  • def function_name(parameter1, parameter2, ...): : used to define a function with parameters.
  • return value: used to return a value from a function.

Example:

1
2
3
4
5
def add_numbers(x, y):
    return x + y

result = add_numbers(2, 3)
print(result)  # 5

Calling Functions

  • function_name(argument1, argument2, ...): used to call a function with arguments.

When you want to call the function, you should use function name and brackets (). In your function if you have a print statement, and you call that function using a print command outside that function, it will not result in anything because your function already has a print statement. When you use print again, it looks for a return value from the function. As there is no return value (you are printing a value not returning anything), it will not pick anything to print. So output will be none.

1
2
3
4
def myfunction():
    print ("This is function")

print (myfunction())

If you directly call myfunction(), it will print the output as “This is function”. But if you use print (myfunction()) it displays none in the output because there is no return value from the function. If you want to use print() for sure outside the function, then you should change the print command to return command as shown below:

1
2
3
4
def myfunction():
    return ("This is function")

print (myfunction())

Variable Annotation

In Python, annotation refers to the ability to add metadata to variables, functions, and other objects. This metadata is not used by the Python interpreter itself, but it can be accessed and used by other tools, such as type checkers, IDEs, and documentation generators.

Variable annotations (or type annotations), in particular, are a way to add a type hint or a description to a variable. They were introduced in Python 3.5 as part of the typing module.

Here’s an example:

1
2
name: str = "John"
age: int = 30

In this example, name and age are variables with annotations. The : str and : int parts specify the expected type of the variable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import typing
# Define a variable of type str
z: str = "Hello, world!"
# Define a variable of type int
x: int = 10
# Define a variable of type float
y: float = 1.23
# Define a variable of type list
list_of_numbers: typing.List[int] = [1, 2, 3]
# Define a variable of type tuple
tuple_of_numbers: typing.Tuple[int, int, int] = (1, 2, 3)
# Define a variable of type dict
dictionary: typing.Dict[str, int] = {"key1": 1, "key2": 2}
# Define a variable of type set
set_of_numbers: typing.Set[int] = {1, 2, 3}

Annotations can be used for several purposes:

  1. Type hinting: As shown above, annotations can be used to specify the expected type of a variable. This can help with code readability and can be used by type checkers to catch type-related errors.
  2. Documentation: Annotations can be used to add a brief description of a variable, making it easier for others (and yourself) to understand the code.
  3. IDE integration: Many Integrated Development Environments (IDEs) can use annotations to provide features like code completion, type checking, and code refactoring.

It’s worth noting that annotations are not enforced by the Python interpreter, so you can still assign a value of a different type to a variable with an annotation. However, using annotations can help you write more maintainable and self-documenting code.

File Handling

Opening and Closing Files

  • file = open(filename, mode): used to open a file.
  • file.close(): used to close a file.
  • read() - used to read the contents of a file
  • write() - used to write data to a file

Modes in Python for file handling:

  • r - Read mode which is the default mode. Opens file for reading, error if the file does not exist.

  • w - Write mode which opens file for writing. Creates a new file if does not exist or truncates the existing file.

  • a - Append mode opens file for writing at the end of the file without truncating it. Creates a new file if does not exist.

  • r+ - Open file for both reading and writing. The file must exist.

  • w+ - Open file for both reading and writing. Creates a new file if does not exist or truncates the existing file.

  • a+ - Open file for both reading and appending. The file must exist.

  • x - Open file for exclusive creation, failing if the file already exists.

  • b - Binary mode which is used for binary files. Added to any of the above modes like rb, wb, etc.

  • t - Text mode (default). Open file for updating (reading and writing), failing if file does not exist.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# writing to a file
file = open("example.txt", "w")
file.write("Hello, world!")
file.close()

# reading from a file
file = open("example.txt", "r")
contents = file.read()
print(contents)
file.close()

Reading from Files

  • file_object = open(file_path, mode): used to open a file with a specified file path and mode.
  • file_object.read(): used to read the contents of a file.
  • file_object.readline(): used to read a single line from a file.
  • file_object.readlines(): used to read all lines from a file and return them as a list.

Writing to Files

  • file_object = open(file_path, mode): used to open a file with a specified file path and mode.
  • file_object.write(string): used to write a string to a file.
  • file_object.writelines(iterable): used to write an iterable to a file.

Appending to Files

  • file = open(filename, 'a'): used to open a file in append mode.
  • file.write(string): used to append a string to a file.

Closing Files

  • file_object.close(): used to close a file that has been opened with the open() function.

Exception Handling

try-except Block

  • try - used to wrap code that may raise an exception
  • except - used to handle exceptions that are raised in a try block
  • finally - used to execute code regardless of whether an exception is raised

try-except-else Block

  • try:
    • # code that might raise an exception
  • except exception_type:
    • # code to handle the exception
  • else:
    • # code to execute if no exceptions are raised

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
try:
   print("Trying to open and read file")
   file = open("file.txt")
   content = file.read()
   print(content)
except IOError:
   print("Error opening/reading file") 
else:
   print("File read without any errors")
   file.close()

Some key points:

  • The except block runs only if the exception mentioned occurs. Otherwise program flow moves to else.

  • Multiple except blocks can be used to handle different exceptions.

  • else block runs even if the exception was handled in except and program didn’t crash.

  • Code in else is guaranteed to run only when try succeeds without any exception.

try-except-finally Block

  • try:

    • # code that might raise an exception
  • except exception_type:

    • # code to handle the exception
  • finally:

    • # code to execute regardless of whether an exception was raised or not

    Here is an example of using the try, except and finally blocks in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
try:
   print("Dividing numbers")
   num1 = int(input("Enter first number: "))
   num2 = int(input("Enter second number: "))
   result = num1/num2
   print("Result is:", result)

except ZeroDivisionError:
   print("Cannot divide by zero")

finally:
   print("Finally block executed")

The key points about try, except and finally:

  • try block contains the code that may raise an exception.

  • except block handles the specific exception. Here it handles ZeroDivisionError.

  • finally block contains the cleanup code that must be executed whether exception occurred or not.

  • Code in finally block is executed after try and except blocks.

  • If no exception occurs, finally runs after try block.

  • If exception occurs and is handled in except, finally runs after except.

  • finally block is useful to close files, database connections etc. to avoid resource leaks.

  • Code in finally ensures resources are cleaned even if program crashes in try or except.

So in summary, finally allows executing important cleanup code regardless of normal or exceptional program flow through try and except blocks.

Modules

Checkout Python Modules post for more information.

  • import - used to import modules or packages
  • from - used to import specific functions or classes from a module

Example:

1
2
3
4
5
6
7
# importing entire module
import math
print(math.sqrt(16))  # 4.0

# importing specific function from module
from random import randint
print(randint(1, 10))  # generates a random integer between 1 and 10 

Refactoring: When a code is updated to be more self-documenting and clarify the intent

Suggested Article

If you’d like to continue reading, checkout our other articles on python here or browse all other topics here.

Conclusion

This is not an exhaustive list of all Python commands and libraries, but it covers many of the most commonly used ones. As you continue to learn and use Python, you will likely encounter many more commands and libraries that are not listed here. Please let us know your feedback about this article in the comments section below.

Your inbox needs more DevOps articles.

Subscribe to get our latest content by email.