Skip to content

Cheat Sheet English

KamiTzayig edited this page Oct 24, 2022 · 15 revisions

MM Python cheat sheet

Base

Output

Base Form

print()

Example

print("Hello World!") => Hello World!

Explanation

Send the desired output to the console.

Input

Base Form

input()

Example

input("Enter your name: ") => Enter your name: _ (Waiting for interactive input)

Explanation

Allows receiving input from the console user for all sorts of operations.

Casting

Base Form

int() / str() / float()

Example

int("1") => 1
str(1) => "1"
float(1) => 1.0

Explanation

Conversion from string to integer, integer/float to string or integer to float.

Strings

Slicing

Base Form

"string"[START:END:STEP]

Example

"ABCD"[1:3] => BC
"ABCDEFG"[1:-3] => BCD
"ABCDEFGHIJKLM"[:4:-1] => MLKJIHGF

Explanation

Some string slicing techniques. works for lists, tuples and sets aswell
[START::] Represents the pointer location to begin with, negative numbers are counted from the end.
[:END:] Represents the pointer location to end with, negative numbers are counted from the end.
[::STEP] Represents the number of places for a step, negative numbers are reversing the order.

String Length

Base Form

len()

Example

len("hello") => 5
len("Hello World") => 11

Explanation

counting the number of letters (including spaces) in the string and returning the length as int.

String casing manipulation

Base Form

"string".upper() / "string".lower()

Example

"Python Course".upper() => PYTHON COURSE
"Python Course".lower() => python course
"wEIRD Case"[0].upper() + "wEIRD Case"[1:].lower() => Weird case

Explanation

Changing the entire string into either UPPERCASE or lowercase depending on the respective function.

Counting inside string

Base Form

"string".count("")

Example

"Hello World!".count("!") => 1
"This is an example".count("is") => 2
"wEIrD CAse StrING".lower().count("s") => 2 #Function chaining to find an occurence inside mixed-case string

Explanation

Count occurences of substring inside another string.

other methods for strings

Medthods for strings

Conditions (if statements)

Boolean (bool) values

Base Form

False / True

Example

number1 > / < / >= / <= / == / != number2
item in list / string
item not in list / string
True and False == False
True and True == True
True or False == True

Explanation

Boolean values can have 2 states, either True or False. They can be used to create conditions.

Conditions

Base Form

if bool:
    option1
elif bool:
    option2
else:
    default_option

Example

# condition1/condition2 are Boolean

if condition1:
    this will run only if condition1 is True
elif condition2:
    this will run only if condition1 is False AND condition2 is True
else:
    this will run if only if condition1 AND condition2 are False

Explanation

Conditions allow running certain code under certain conditions.

Lists

Adding/Removing an object from a list

Base Form

list.append()
list.pop()

Example

ls = ["Tony", "Ana", "Dan", "Dvora"]
ls.append("Hanna")
print(ls)

["Tony", "Ana", "Dan", "Dvora", "Hanna"]

ls = ["Tony", "Ana", "Dan", "Dvora"]
index = ls.index("Ana")
ls.pop(index)
print(ls)

["Tony", "Dan", "Dvora"]

Explanation

.append(object) adds the object you put in it to the end of the list as is shown.
.pop(int) pops the item at the specified index, can be used with .index() to remove a specific item from the list

Sorting a list

Base Form

list.sort()
sorted(list)

Example

ls = [4,2,5,1,3]
ls.sort()
print(ls)

[5,4,3,2,1]

ls = [4,2,5,1,3]
ls2 = sorted(ls)
print(ls2)
print(ls)

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

Explanation

When the original list order is unneeded use sort(). If it's required, use sorted() and assign the sorted list to a new variable.

Sum/Min/Max values from a list

Base Form

sum(list)
min(list)
max(list)

Example

ls = [13,4,2,51,-1,3]
max_number = max(ls)
min_number = min(ls)
sum_of_list = sum(ls)
print(max_number)
print(min_number)
print(sum_of_list)

51
-1
72

Explanation

these are 3 useful functions you can use on a list

other methods for lists

Methods for lists

Loops

while loop

Base Form

while <boolean condition> :  
    <code>

Example

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

0
1
2
3
4

Explanation

while loops are used when we don't know the number of times it will repeat. for example the game "snake" is using a while loop and the condition for the game to be over is if you hit yourself

for loop

Base Form

for variable in iterable:  
    <code>

Example

ls = [1,2,"Tom", 5]
for i in ls:  
    print(i)

1
2
Tom
5

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

0
1
2
3
4

Explanation
for loops are used when the number of iterations is known before entering the loop. For example printing all the kids names from a list. Can be used with range(START, END, STEP)

range()

Base Form
range(START, END, STEP)

Example

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

5
6
7
8
9

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

5
4
3
2
1

Explanation
The range() function is typically used to create an iterable (similar to a list) of numbers.
START => what number to start the iterable.
END => what number to stop the iterable (stops one number before END, e.g range(1,5) stops at 4).
STEP => specifying the incrementation. Default is 1.

Dictionary

dict

Base Form

{"key":"value"}

Example

fruits = {"Apple": 5,
"Orange": 4}

print(fruits['Apple'])

Explanation
dict usually consists of some sort of key-value relation while the first part (left) represents
the key while the last part (right) represents the value, several items can be presented as long
as these are separated with a comma, for integer/float/double/boolean the quotes are not mandatory. Remember this is only a simplest form of list.

Nested dict

Base Form

{"key":
    {"key":"value"}
}

Examples

movies = {"Titanic": 
    {"Release Date": 1997,
    "Actors": ["Leonardo DiCaprio", "Kate Winslet"],
    "Watched": False},
"Forest Gump":
    {"Release Date": 1994,
    "Actors": ["Tom Hanks", "Robin Wright"],
    "Watched": True}}

print(movies["Forest Gump"]["Release Date"]) # Print the year Forest Gump was released
print(movies["Titanic"]["Actors"][1]) # Print the second actor (or actress) from the movie

1994
Kate Winslet

print(movies.keys())

dict_keys(['Titanic', 'Forest Gump'])

print(movies.values())

dict_values([{'Release Date': '1997', 'Actors': ['Leonardo DiCaprio', 'Kate Winslet']}, {'Release Date': '1994', 'Actors': ['Tom Hanks', 'Robin Wright']}])

print(movies.items())

dict_items([('Titanic', {'Release Date': '1997', 'Actors': ['Leonardo DiCaprio', 'Kate Winslet']}), ('Forest Gump', {'Release Date': '1994', 'Actors': ['Tom Hanks', 'Robin Wright']})])

for movie in movies:
    print(movie, "was released in", movies[movie]["Release Date"])

Titanic was released in 1997
Forest Gump was released in 1994

for key, value in movies.items():
    if value["Watched"]:
        print(f"You watched {key}")

You watched Forest Gump

removed = movies.pop("Titanic")
print(f"You removed the the object with these values: %s" % removed)
print(movies)

You removed the the object with these values: {'Release Date': '1997', 'Actors': ['Leonardo DiCaprio', 'Kate Winslet'], 'Watched': True}
{'Forest Gump': {'Release Date': '1994', 'Actors': ['Tom Hanks', 'Robin Wright'], 'Watched': True}}

Explanation
A nested dict allows nesting several items (mixed) as a value for a certain key, the following
example shows how to make a movie list with several details about each movie and the ability to
ask for specific value from the provided details.
keys() - Print a view object of the keys (names of the movies available).
values() - Print a view object of the values (all the details about the movie but not the name).
items() - Print a view object of all the dictionary items in tuples (key, value).
The last 2 examples before pop are about looping through a dictionary to display desired results, the first
loop will show the released date according to the data in the dictionary while parsing the dictionary itself,
while the second example treats the objects in the dictionary as a dual tuple that expands to 2 params.
pop() - Removes and returns an element from a dictionary having the given key.

Files

Read

Base Form

with open('somefile.txt') as f:
    lines = f.readlines()

Explanation
The lines read from the somefile.txt file will be added to the f parameter as list of strings,
the easiest way to approach this list would be by using some sort of loop (while/for).

Write

Base Form

lines = ['Hello', 'World']
with open('somefile.txt', 'w') as f:
    for line in lines:
        f.write(line)
        f.write('\n')

Example

lines = ['Titanic', 'Forest Gump']
with open('movies.txt', 'w') as f:
    for line in lines:
        f.write(line)
        f.write('\n')

Explanation
The lines from the lines parameter are written to the movies.txt file represented by the f
parameter so the .write() function is actually performed on f and \n is being added after every line.

Requests

Fetching data

Base Form

Warning Requests might not be part of the Python basic package and will require installing via pip

import requests

print(requests.get('https://w3schools.com/python/demopage.htm').text)

Example

import requests


def print_israel_uni(api):
     result=requests.get(url=api,verify=False)
     data=result.json()
     names=data
     for n in names:
          print(n['name']) 
 

api='http://universities.hipolabs.com/search?country=Israel'
print_israel_uni(api)

Explanation
The requests module allows fetching information from HTTP(S) services such as REST APIs and HTML pages.