Show Menu

Python Cheat Sheet Cheat Sheet by

Vocabulary

Syntax
Gramma­r/S­tru­cture of language
Variable
Hold a value and can be change
Boolean
True/False
String
A list of character such as number, letter and symbols
Integer number
whole number­/co­unting number
Float number
The number in decimal
List
use [ ] square brackets
Comment
hashta­gs/­triple quotes
Character
Letters, numbers, spaces
Condit­ional
Like if/else
Modulo
Find the remain­der(ex. 33%10==3)
if/eli­f/else
condit­ional
Loop
Something that repeats
 
Parameter
Something you give to the function
Argument
Something you give to the function
Function call
When we call the function by its name, so that it shows the code
Constants
Data stored in memory that cannot be changed after declar­ation
Syntax error
Computer doesn't understand the instru­ction because it's typed incorr­ectly
Compile
Run the program
Statements
Instru­ctions that do not evaluate to any value
Length
The length of the string

Exam Review 1

1. Converting between different data types:
word = str(3) #converts 3 to a string "­3"
num = int("3.5­") #converts "­3.5­" to integer 3
num = float(­"­3") #converts "­3" to a float 3.0

2. Printing values:
print(­"­hel­lo",­"­the­re") #displays hello there
print(­"­hel­lo" + "­the­re") #displays hellothere

3. Combining strings (conca­ten­ation)
"­hi" + "­the­re" == "­hit­her­e"
"­hi" * 5 =="h­ihi­hih­ihi­"

4.Comments
# hashtag - everything after # is a comment no code
"­"­"
Double quote/­quo­tation marks - multi-line comment, everything in between three double quotes is a comment
"­"­"
5. Comparing Values:
when you compare two values, the result is a boolean (true or false) ex. 2==3 is false
== is equal to
!= is not equal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to
and
or
not
true or anything is always true
false and anything is always false
True and False must be in capital letter

Exam Review 2

1. Forever while loop:
while True: #forever
user_input = input('Enter a number:')
number = int(user_input)
print('The number squared is', number**2)

2. Conditional while loop:
count = 0 # start at zero
while count <10:#loop while count is less than 10
       print (count) #will print numbers 0-9
       count = count + 1 #must increase count

3. Decision making/ conditional statements:
if 3<2: #if statement must compare two booleans
   print('3 is less than 2')
elif 4<2: #can have 0 or more
    print('4 is less than 2')
elif 5<2:
    print(' 5 is less than 2')
else: #can have 0 or 1 else at the end
    print('none of the above are True')

4. Lists
mylist = [2,3,4,5] #create a list
#select an item from a list
print(mylist[0]) #selects first item and displays 2

#len() determines the length of the list
print(len(mylist)) #displays 4

mylist.append(5) #add an item to the end of the list
#it will print [2,3,4,5,5]

5. while loop with list:
thelist = [4,3,2,1,0]
index = #start at the first item
while index < len(thelist):
       print(thelist[index]) #prints each item
       index = index + 1

6. for loop with list
forlist = [3,4,5,2,1]
for item in forlist:
     print(item)

7.Range()
#creates a list of numbers from 0 to the specified number]
numberlist = range(5)
#is the same as creating the following list
numberlist2 = [0,1,2,3,4]

for num in range(100):
    print(num) #prints all numbers from 0-99
for num in range(5,50):
    print(num) #prints all numbers from 5-49

8. Functions
#function with no parameters/arguments
#and no return value
#return is optional if you do not return a value
def nameOfFunction():
     print('This function has no parameters')
     print('This function has no return value')
     return #no value, just exits the function
#function call
nameOfFunction()

#function with 1 parameter/argument
def testFunction(param):
     print('This function has 1 parameter')
     print(param)
#function call
testfunction('this is the parameter value')

#function with 2 parameters and a return value
def function3(param1, param2):
     print('This function has 2 parameters')
     return param1 + param2 #return value
#function call and store the result in a variable
returnValue = function3(2,3)
print(returnValue)

Condit­ionals

if else
If the statement is true then do command under then else do command under else.
elif
Similar to if else, but elif allows for more conditions (The keyword ‘elif‘ is short for ‘else if’)
for loop
For loop will loop though every element of the set of elements
while loop
Loop Contains 3 basic parts: 1. initial value 2. ending condition 3. update
while true
Loops forever
Boolean
True or anything = always True
Boolean
False and anything = always False
Boolean
True/False always write in capital letter

Sample Exam 1

# Practice exam

# 1. Make the loop not to go forever
gameover = 0
while (gameover == 0):
    print("hello")
    gameover = 1 # or break

# 2. Make each number of the list mylist printed out on a seperate line
mylist = [1,2,3,4,5]
for number in mylist:
    print(number)

# 3. Make the program prints out the fifth character from the variable myword
myword = "hellothere"
print(myword[4])

# 4. Write a program that receives input from the user in a loop. Convert the input to an integer and print out that integer multiplied by 10.
while True:
    user_input = input("Please enter a number:")
    user_input1 = int(user_input)
    user_input2 = user_input1*10
    print(user_input2)

# 5. Write a program that uses a while loop to print out each item in the following list:
wlist = [2,4,5,6,7,8]
listnum = 0
while listnum < len(wlist):
    print(wlist[listnum])
    listnum = listnum + 1

# 6. Write a program that uses a for loop to print out each item in the following list:
forlist = ['hi', 'hello', 'goodbye']
for item in forlist:
    print(item)

Sample Exam 2

# Sample Exam 2

# 1. Receive input from the user as a float , and print out half of that number.
user_input = input("Please enter a number:")
print(float(user_input/2))
# 2. What is the putput of the following code:
y = True
print(not y or 2 < 3)
print(True)
# 3. Consider the following code:
message = "hello"
if (len(message)> 5):
    print ("Message is too long")
else:
    print("Message is good")
   # line 3 has an error because there is no indentation.
# 4. Program to receive a number from teh user and determine if that number is divisible by 3.
    # 9 is divisible by 3
    # 7 is not divisble by 3
user_input = input("Please enter a number;")
if user_input%3 == 0:
    print(user_input, "is divisible by 3")
else:
    print(user_input, "is not divisible by 3")
# 5. Print all the even numbers from 1 to 100 using a while loop
num = 2
while num <= 100:
    print(num)
    num = num + 2
# 6. What is the output of the following code:
condition = True
number = 5

if condition == False:
    number = number ** 2
elif number < 5:
    number = number * 2
elif condition == true:
    number = number % 2
else:
    number = number /2
    print(number)
# 7 . Given a list called mylist, print all the elements from the list using a loop
      #for loop solution
       mylist = [ 1,2,3,4,5]
       for number in mylist:
           print(number)
       #while loop solution
       mylist = [1,2,3,4,5]
       num = 0
       while num < len(mylist)
           print(mylist[num])
           num = num + 1
# 8. Use a for loop a print the following
     #0
     #01
     #012
     #0123
     #01234
mystring = ""
for number in range[5]: #[0,1,2,3,4,5]
     mystring = mystring +str(number)
     print(mystring)
# 9. Write a function called multiplicationTable that asks the user for a user for a number and computes its multiplication table. example: If the users enters 5, the output should be
     # Enter a number: 5
     # 5*1 = 5
     # 5*2 = 10
     def multiplicationTable():
         user_input = input("Enter a number:")
         num = int(user_input)
         count = 1
         while count <= 10:
             print(num, "", count, "=", numcount)
             count = count+1
        #function call
        multiplicationTable()

Sample Exam 3

# Sample Exam 3
#1. Write a program that receives input from the user, converts it to an integer, and prints the product of the integer and 5
user_input = input("Enter a number:")
user_input = int(user_input)
print(user_input*5)
#2. What is the output of the following code:
x = False
print(x and True or 1==1)
      #output is True
#3. no indentation
#4. Write a program that receives a number from the user and determines if that number is zero or positive
    #output of the program
    #4 is positive, 0 is zero, -8 is negative
user_input = int(input("enter a number:"))
if user_input>0:
    print(unser_input, "is positive")
elif user_input<0:
    print (user_input, "is negative")
else:
    print(user_input, "is zero")
#5. Write a program that prints all the even numbers from -100 to -1 using while loop
mynum = -100
while mynum <-1:
    print(mynum)
    mynum = mynum +2
#7. Given a list called mylist, write a program that prints all the items in the list using a loop
mylist = ['cokezero', 'bacon', 'pepsi']
for item in mylist:
    print(item)
#8. Complete the program below by filling in the blank:
        #Expected output of the program:
        #0
        #01
        #012
        #0123
        #01234
mystring =""
count = 0
while count < 5:
       mystring = mystring + str(count)
       print(mystring)
       count = count + 1
#9. Write a unction called areaOfEllipse() that computes the area of an ellipse using the equation: pirr
    #The function should be given two parameterss( radius 1 and radius2) and should return the area
def areaOfEllipse(radius1, radius2):
        pi = 3.1415
        area = piradius1radius2
        return area
    #function call
    area1 = areaOfEllipse(2,3)
    print(area1)
#11.Wrie a program that repeatly receives positive integers from the user. When the user enters a negative integer, exit the loop and orint how many of the numbers entered were even and odd.
evenCount = 0
oddCount = 0
while True:
       num = int(input("Enter a positive integer:"))
       if num < 0 :
         print("Even numbers:", evenCount)
         print("Odd numbers:", oddCount)
         break
       else:
            if(num%2) == 0
                evenCount = evenCount + 1
            else:
                oddCount = oddCount + 1
 

Basic Math Operation

==
Equal to
!=
No equal to
<
Less than
>
More than
<=
Less than or equal to
>=
More than or equal to
+
Add
-
Subtract
*
Multiply
**
Exponent
/
Divide and quotient is float
//
Divide and quotient is integer
%
Modulo, Find the remain­der­(33­%10==3)

Addition

string + string
Combine togehter
string + number
CRASH!
number + number
Addition (Math)

Multip­lic­ation and Exponents

string * number
Combine that string
string * string
CRASH!
number * number
Multiply (Math)
string ** string
CRASH!
number ** number
Exponent (Math)
string ** number
CRASH!

Function

print()
Show inform­ation that you want on the screen
int()
Change number to be number integer
float()
Change number to be decimal number
input()
Gain inform­ation from user
str()
A list of number, letter and symbols
len()
The length of the string
#
Comment, no effect

Example

Print (2) - integer
Print (2.5) - floating point
Print ("Hello) - string
Print (mystr) - variable
Print (mystr­,"Hi­"­2,1,0) - - commas

mystr = "­Hi"
mystr - name
"­Hi" - value can change

print (int(1.5)) - 1
print (int("2')) - 2

Naming Convention

Rule for giving name
- letter
- number (number cannot be the first letter)
- underscore_
- can start with letters or underscores ONLY
- no spaces

Valid name
- myStr
- my3
- Hello_there

Invalid name
- 3my = "hi" (cannot start with number)
- first name = "hi" (no spaces allowed)
- first-name (dashes are not accepted)
 

Area of circle Python

#Ask the user for a radius of a circle

while True:
    user_radius = input("Please enter the radius of the circle:")
    radius = float(user_radius)
    pi = 3.1415
    area = (piradius*2)
    print("The area of the circle is", area)

Area of triangle & Volume of prism Python

#write a function

#name : areaOfTriangle
#parameters : base height
#return : area

user_base = float(input('Enter the base of the triangle:'))
user_height = float(input('Enter the height of the triangle:'))
def areaOfTriangle (base, height):
    return 1/2 user_base user_height

#function call
print('The area of the triangle is',areaOfTriangle (user_base, user_height))


#write function compute volume of prism

#name : volumeOfPrism
# parameters : b,h,prism_height
# return volume

def volumeOfPrism(base, height, prism_height):
    # area* prism_height
    volume = areaOfTriangle(base,height) * prism_height

    return volume

user_prism_height = float(input('Enter the prism height:'))
print ('The volume of the prism is', volumeOfPrism(user_base, user_height, user_prism_height))

Convert to binary Python

user_number = ' '

while user_number != '0' :
   user_number = input ("Enter a number to convert to binary")
   number = int(user_number)
   binary_string = ' '

while (number > 0):
   remainder = number%2
   binary_string = str(remainder) + binary_string
   number = number // 2

   print ("Binary string is", binary_ string)

Countdown String Python

user_number = input("What number do you want to count down?")
number = int(user_number)
countdown_string = ' '

while number > 0:
   countdown_number = countdown_string + str(number) + " "
   number = number - 1
   #print (number)

   print (countdown_string)

Define Python

def calc(num1, num2, operation):
    #use if/elif/else to check what operation to do
    #call the correct function and return the answer
    if operation == "sum":
        return sum(num1, num2)
    elif operation == "product":
        return product(num1, num2)
    elif operation == "diff":
        return diff(num1, num2)
    elif operation == "div":
        return div(num1, num2)
        
    
def sum(a,b):
    #calculate the sum of a and b
    #return the answer
    return a+b

def product(a,b):
    #calculate the product of a and b
    #return the answer
    return a*b

def diff(a,b):
    #calculate the difference between a and b
    #return the answer
    return a-b

def div(a,b):
    if b != 0:
        return a//b
    else:
        print("Error")
    #calculate the division of a and b
    #return the answer
    

print(calc(10,0,"div")) #division by zero
print(calc(1,2,"sum")) #output should be 3
print(calc(4,2,"diff"))#output should be 2
print(calc(9,3,"div"))#output should be 3
print(calc(2,12,"product"))#output should be 24

Define Python

_var1 = 1
_var1 = 3
_var1 + 100
print(_var1)

def bacon():
    print("hello")
    return
bacon()

#anything after return will not be printed
def bacon():
    print("hello")
    print("line1")
    return
    print("bye")
bacon()

def myprint(text):#
    print("" + str(text) + "")
    return #return exits the function
myprint(1)
myprint(2.5)
myprint("hello")

def myprint2 (text, decoration): #text and decoration are arguments(parameter) to the function (something you're giving to the function)
    print(decoration + text + decoration)
    return
myprint2("hello", "+++")
myprint2("hello", "-=-=-=-=-=-")
myprint2("hello", ">>>>>>>")

def doubleIt(number):
    return number*2 #return value
print (doubleIt(2))
myvar = doubleIt(doubleIt(3)) #same as doubleIt(6) because doubleIt(3) ==6)
print (myvar) #it will display 12

def areaOfCircle (r):
    if r <= 0:
            return "Error: invalid radius"
    pi = 3.1415
    area = pir*2
    return area
user_radius = input("Enter the radius:")
radius = float(user_radius)
print("The area of the circle is", areaOfCircle(radius))

Max value + For loops Python

# write a function that returns the largest of two values
# name: max2
# arguments: num1, num2
# return: the largest value

def max2(num1, num2):
    if num1 > num2:
        maxvalue = num1
    elif num2 > num1:
        maxvalue = num2
    return maxvalue

print(max2(2656,3))

def max2(num1, num2):
    maxvalue = num1
    if num2 > maxvalue:
        maxvalue = num2
    return maxvalue
print(max2(2,3))


# write a function that returns the largest of three values
# name: max3
# arguments: num1, num2, num3
# return: the largest value

def max3(num1, num2, num3):
    maxvalue = num1
    if num2 > maxvalue:
        maxvalue = num2

    if num3 > maxvalue:
        maxvalue = num3
    return maxvalue
print(max3(2,3,4))

# write a function that returns the largest number in a list
# name: maxlist
# arguments: list
# returns the largest value in the list

def maxlist(list):
    maxvalue = list[0]
    for item in list:
        if item > maxvalue:
            maxvalue = item
    return maxvalue
        
mylist = [23,4342,468,56,7873]
print(maxlist(mylist))

Name Python

firstname = input("What is your first name?")
lastname = input("what is your last name?")

fullname = firstname + " " + lastname
print (fullname)

letternumber = int(input("What is the letter number?"))

if letternumber >= len(fullname):
    print("Invalid letter number,try again.")
else:
    print(fullname[letternumber])
    #letter number is a string
    times = int(input("How many times to print the letter"))
    if times > 100:
        print ("Too many letters to print!")
    else:
        print (fullname[letternumber]*times)
    #square brackets select a letter inside a string

Return function Python

#how to create a function
def nameOfFunction (myvar1, myvar2):
    print("hello")
    return myvar1 + myvar2

#function call
nameOfFunction (2,3)
myanswer = nameOfFunction (4,1)
print(myanswer)
print(nameOfFunction(nameOfFunction(2,1),4))
# it will print(nameOfFunction(3,4))

Reverse Word Python

while True:
   word = input('Please enter a word')
   index = 0
   reverse = ''

   while int(index) < len(word):
         reverse = word[index] + (reverse)
         index = int(index) + 1

   print ("Reverse: ", reverse)

Download the Python Cheat Sheet Cheat Sheet

7 Pages
//media.cheatography.com/storage/thumb/pizzajza_python-cheat-sheet.750.jpg

PDF (recommended)

Alternative Downloads

Share This Cheat Sheet!

 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.