PYTHON 3 BEGINNER’S CHEATSHEET
User input and output Arithmetic Operations
Printing to the screen Basic arithmetic Integer division Real division
print('Hello, World!') 5 + 2 - (4 * 3) 5 // 2 5/2
# result is -5 # result is 2 # result is 2.5
Printing a variable
Modulus Power
name = 'Karim'
print('Hello, ' + name + '!') 5%2 5 ** 2
# result is 1 # result is 25
Reading user input
country = input('where are you from?' )
age = int(input('what is your age?')) Lists
Creating a list Append to a list
Variables L = [1, 2, "abc", True] L.append(10)
Creating an integer variable Creating a list of lists Remove from a list
age = 25 L = [[1, 2], ["abc"], [True, 15.2, x, "item"]] L.remove("abc")
Creating a string variable
List contains item Get the index of an item
goal = 'Commit to CS mastery!'
L = [1, 2, "abc", True] L = [1, 2, "abc", True]
2 in L #True id x = L.in d ex("ab c")
Creating a float variable "xyz" in L #False # id x is 2
pi = 3.14
Reverse a list Sort a list
L.reverse() L.sort()
Strings
Conditional Statements
Creating strings with single or double quotes
If statements
greeting = "Hello"
name = ' World'
if x > 5:
print(greeting + name)
print("x is greater than 5")
# prints "Hello Worlds"
If else statements
Concatenation String contains another string
if age < 12:
msg = "Hello, " + "World!" "ap" in "apple" # True
print("child")
print(msg) "z" in "apple" # False
else:
print("adult")
String formatting
name = "Alice" If elif else statements
age = 20
msg = f"Hello my name is {name} and my age is {age}" if grade >= 85:
# only works with Python 3.6+ print ( 'Excellent' )
elif grade >= 75:
String to uppercase String to lowercase print ( 'very good')
elif grade >= 65:
my_string.upper() my_string.lower() print ( 'good')
elif grade >=50:
print ('pass')
else:
print ('failed')
For Loops
Repeating a block 5 times
While Loops
sum = 0
for i in range (5): Waiting for a condition Infinite loop
sum = sum + i
print(sum) i=0 while True:
# result = 10 while i < 5: print("this loop will never terminate")
print(i)
Iterating over a list i += 1
L = ["hello", "my", "name", "is", "Karim"]
Break from a loop
for item in L:
print(item)
x=0
while True:
Iterating over a string if (x == 20):
break
str = "afternerd" # do something
for ch in str: x += 1
print(ch) # you can also use break to break from for loops
Functions
Function with no parameters Function with multiple parameters
def print_msg(): def print_msg(msg, times):
print("Commit to CS mastery") for i in range(times):
print(msg)
Function with a return value Call a function
def power(x, y): x=5
return x ** y y=2
z = power(x, y)
# returns 25
w ww.afternerd.com