Resources and Posts

Python Cheatsheet


Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponent x**y
// Floor Division x/ y

Operator Name Example
== Equal x==y
!= Not equal x!=y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x>=y
<= Less than or equal to x<=y

Operator Name Result
and (x and y) is True if both x and y are true.
or (x or y) is True if either x or y is true.
not (x not y) If a condition is true then Logical not operator will make false.
in Evaluates to true if it finds a variable in the specified sequence and false otherwise. x in y, here in results in a 1 if x is a member of sequence y.
not in Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y.

For loop executes a sequence of stattements multiple times.

Let's create a shopping list:


        shopping_list = ["cheese", "bread","milk"]
        

Iterate through the shopping list and print item:


        for item in shopping_list:
            print("item is", item)
        


        item is cheese
        item is bread
        item is milk
        


A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.

Let's create a shopping list:


        shopping_list = ["milk", "bread","bananas","soda","oranges"]

Create a new variable number_of_items and measure(number of items) the length of shopping list:


        number_of_items = len(shopping_list)

Use while loop using condition number_of_items > 0: to remind to buy an item from shopping list, with a nested for loop, decrease number_of_items by 1, every time you run while loop:


        while number_of_items > 0:
            number_of_items -= 1
            for item in shopping_list:
                print ("Do not forget to buy:", item)

As we "buy" all items from the shopping list and condition number_of_items == 0, while loop stops iterating.


Conditional statements if, elif, else perform different actions based on different conditions.


        weather = input("pls enter weather:")

        if weather == "rainy":
            print("Please take an umbrella")

        elif weather == "sunny":
            print("Please take your sunglasses")

        else:
            print("Not a valid choice")

List slicing [start:stop:step]

Let's create a list:

lst = [1,2,3,4,5,6,7]

Let's select items from index 2 to index 4.

print(lst[2:5])

[3, 4, 5]

We want to select the first 4 elements. If we don't specify the starting index it automatically starts at the beginning.

print(lst[:4])

[1, 2, 3, 4]

We can also start at at certain index and select every item after that. We select every item starting at index

print(lst[2:])

[3, 4, 5, 6, 7]

We can also select all in another way. Since we leave the start and stop blank we are selecting all items.

print(lst[:])

[1, 2, 3, 4, 5, 6, 7]

We want to select every other item. The number after the seconf colon is the step. We go every two items.

print(lst[::2])

[1, 3, 5, 7]

Every two items starting at index 1.

print(lst[1::2])

[2, 4, 6]

What if we want to select the last item but we don't know how many items there are. For lst we can count 7 items and do print(lst[6]). But this is better way:

print(lst[-1])

7

We can combine what we have learned. Let's print the list backwards.

print(lst[::-1])

[7, 6, 5, 4, 3, 2, 1]

Printing the list backwards skipping every other item.

print(lst[::-2])

[7, 5, 3, 1]


Enumerate function

Let's create a list.

lst = ['a', 'b', 'c', 'd', 'e']

Let's print each item of the list:

for item in lst:
        print(item)

a

b

c

d

e

If we wanted to add the index while printing. 0: 'a' 1: 'b, etc...

for item in range(len(lst)):
        print(item, ':', lst[item])

0 : a

1 : b

2 : c

3 : d

4 : e

It is better to use enumerate.

for index, item in enumerate(lst):
        print(index, ':', item)

0 : a

1 : b

2 : c

3 : d

4 : e

Same result. Enumerate returns a tuple (index, item). We get the tuple when we assign only one iterator.

for _tuple in enumerate(lst):
        print(_tuple)

(0, 'a')

(1, 'b')

(2, 'c')

(3, 'd')

(4, 'e')


Function Result
len(list) Returns the length of the list.
list.append(obj) Appends object obj to list.
list.count(obj) Counts how many times obj occurs in list.
list.index(obj) Returns the lowest index in list that obj appears.
list.insert(indx, obj) Inserts object obj into list at offset index.
list.pop() Removes and returns last object or obj from list.
list.remove() Removes object obj from list.
list.reverse() Reverses objects of list in place.
list.sort() Sorts objects of list.

How to set the value of a variable

To set the value of a variable, type the character(s) you want followed by "=" and then the desired value.


        a = "hello"
        

        number = 7
        

        bananas = "Have a nice day!"
        

        shopping_list = ["milk","bread","bananas"]
        

        dic = {"AAPL":136}
        

        a,b = 1,2
        

Python variable names can contain any alphabetic characters (A-Z and a-z), digits (0-9), and the underscore character "_".

Uppercase and lowercase letters are distinct. Therefore, Number and number are two different variables.

A digit cannot start a variable name. Therefore, street123 is a valid variable, 123street is not.

Built-in keywords and function names shouldn't be used as a variable name. For example, list or len.


How to create a function


Function is a block of reusable code.

Function blocks begin with the keyword def followed by the function name and parentheses ( ) and colon :.

Functions can be invoked by name and parentheses ( ).


        def greetings():

        greetings()
        


        def math(a,b):
            
            total = a + b
            return total

        math(5,7)
        

help(obj)

Built-in function is a great way to find all answers if you are new to Python. Example: help(str) and a help page will be printed on the console. You could see all available functions and methods for this particular object.


range([start], stop, [step])

The range() built-in function returns a sequence of integer values.

start: Starting number of the sequence.

stop: Generate numbers up to, but not including this number.

step: Difference between each number in the sequence.

for i in range(1,5):
    print(i)
        

1

2

3

4


Python has many built-in data types. int (integer), float (floating-point number), str (string), list (list), and dict (dictionary).

If you are ever unsure of the type of the particular object, use the type() function, to check data type.

Converting Between Types


Function Result
int(obj) Returns an integer object constructed from a number or string.
str(obj) Returns a str version of an object.
bool(obj) Return a Boolean value, True or False.
bin(obj) Converts an integer number to a binary string.
list() Converts string, tuple, dictionary to a list.
tuple() Converts string, list to a tuple.
chr(i) Returns the string representing a character whose Unicode code point is the integer i.
ord(str) Given a string representing one Unicode character, return an integer representing the Unicode code point of that character.

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Prints objects to the text stream file, separated by sep and followed by end. sep, end and file are optional arguments.

for i in range(1,5):
    print(i, end=" ")
        

1 2 3 4


Function Data type Result
print("hello") a string hello
print(25) an int 25
print(7.5) a float 7.5
print(["E", "F", "F"]) a list of strings ['E', 'F', 'F']
print([2, 4, 6, 8]) a list of ints [2, 4, 6, 8]

Guides