Show Menu
Cheatography

Python Cheat Sheet by

Vocabulary

Variable
something that can chage
String
a list of characters
Integer number
whole number­/co­unting number
Float number
the number in decimal
Syntax
gramma­r/s­tru­cture of lauguage
Modulo
find the remainder
Boolean
true/false
Parame­ter­/Ar­gument
variable next to name of function

Multip­lic­ation and Exponents

string­*number
Combine that string (repeat string)
string­*string
Crash
number­*number
Multiply (Math)
string­**s­tring
Crash
number­**n­umber
Exponent (Math)
string­**n­umber
Crash

Combining Strings

"hi" + "there" == "hithere"
"hi" * 5 == "hihihihihi"

Forever While Loop

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

Condit­ional 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

For‐Loop with List

forlist = [3, 4, 5, 2, 1]
for item in forlist:
 print(item)

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

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) # adds an item to the end of the list

Example of List

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) # adds an item to the end of the list

Note

- ถ้าหาร เลขอะไร ลงตัว หมายคว­ามว่า remainder ต้องเท­่ากับ 0
- str ตัวเลข = "­2" 3 = 222
- เลขคู่บวก2 เริ่มจาก0
- เลขคี่บวก2 เริ่มจาก 1

Different between [ ] and ( )

[ ] = uses for arrange (ลำดับ)
( ) = uses for print, condition, etc.
 

Math

==
equal to
!=
not equal to
<
less than
>
more than
<=
less than or equal to
>=
more than or equal to
%
modulo, find the remainder

Addition

string + string
Combine together
string + number
Crash
number + number
Addition (Math)

Create Function Calculate

def calc(num1, num2, operation):
    if operation == "sum":
        return sum(num1, num2)
    elif operation == "diff":
        return diff(num1, num2)
    elif operation == "div":
        return div(num1, num2)
    elif operation == "product":
        return product(num1, num2)
    
def sum(a, b):
    return a+b

def product(a, b):
    return a*b

def diff(a, b):
    return a-b

def div(a, b):
    if b != 0:
        return a//b
    else:
        print("Error")

print(calc(10, 0,"div"))
print(calc(1,2,"sum"))
print(calc (4, 2, "diff"))
print(calc (9, 3, "div"))
print(calc (2, 12, "product"))

Example for How to create Function

def areaOfTriangle(base,height):
    return 0.5baseheight

user_base = float(input("Enter the base of the triangle: "))
user_height = float(input("Enter the height of the triangle: "))


print("The area of the triangle is",areaOfTriangle(user_base,user_height))

def volumeOfPrism(b,h,prismheight):
    volume = areaOfTriangle(b,h)*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)

From Work Sheet

Write a program that repeatedly receives positive integers from the user. When the user enters a negative integer, exit the loop an print how many of the number entered were odd and even.
    
evencount = 0 
oddcount = 0
while True:
     num = int(input("Enter: "))
     if num<0:
        print("Even: ",evencount)
        print("Odd: ",oddcount)
        break
     else:
        if num%2 =0:
           evencount = evencount+1
        else:
           oddcount = oddcount + 1

Count Worksheet2

Complete the program below by filling in the blank:
Expected output of program:
0
01
012
0123
01234

mystring = ""
count = 0
while count < 5
   mystring = mystring + str(count)
   count = count +1

From worksheet 3

Use a for loop to print the following:
0
012
0123
01234

mystring = ""
for num in range(5)
     mystring = mystring + str(num)
     print (mystring)
 

Function

print()
displays inform­ation on the screen
int()
converts a value to an integer
str()
converts a value to a string
float()
converts a value to a floating point
input()
receives info from the user
len()
the length of the string
#
comment, no effect
def
create function
return
exit the function
break
exit the loop

Example for counting down number

while True:
    user_number = input("Please enter a number")

    number = int(user_number)

    countdown_string= ""

    while number > 0:
        countdown_string = countdown_string + str(number)
        number = number - 1

    print (countdown_string)

The result will be:

Please enter a number 5
54321

Number to binary

user_number = input("Enter number to convert to binary : ")

number = int(user_number)

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

print ("Binary string is",binary_string)

Example of how to random

import random

intlist = [1,2,3,4,5]
random_int = random.choice(intlist)
print(intlist, random_int)

fplist = [1.0,2.0,3.5,4.4,5.6]
random_fp = random.choice(fplist)
print(fplist, random_fp)

strlist = ['1','2','3','4','5']
random_str = random.choice(strlist)
print(strlist, random_str)

mylist = [1,1.0,'a']
random_item = random.choice(mylist)
print(mylist, random_item)

myvar1 = 1
myvar2 = 2
myvar3 = 3
varlist = [myvar1,myvar2,myvar3]
random_var = random.choice(varlist)
print(varlist, random_var)

Example for calculate in python

while True:
    #Ask the user for a radius of a circle
    user_radius = input("Please enter the radius of the circle")

    #Convert the given radius to a floating point
    radius = float(user_radius)

    #make a variable called pi
    pi = 3.1415

    #Calculate the area of the circle using exponent
    area = piradius*2

    #display the area of the circle to the use
    print ("The area of the circle is", area)

From worksheet 4

Create a program to receive a number from the user and determine if that number is divisible by3.
Example:
- 9 is divisible by 3.
- 7 is not divisible by 3.

user_num = input("Enter the number: ")
if user_num%3 == 0:
   print(user_num, "is divisible by 3")
else:
   print(user_num, " is not divisible by 3")
 

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.