0% found this document useful (0 votes)
123 views

Python Cheat Sheet: by Via

This Python cheat sheet provides summaries of key Python concepts and examples of common code structures in 3 sentences or less: It defines common Python vocabulary like strings, variables, booleans, and modulo. It also gives examples of good and bad variable names. Various Python data structures are demonstrated like lists, while and for loops, if/else statements, functions, and the Fibonacci sequence. Common string and list methods are shown along with examples of calculating areas of circles, guessing games, and basic calculators.

Uploaded by

pca_pca
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views

Python Cheat Sheet: by Via

This Python cheat sheet provides summaries of key Python concepts and examples of common code structures in 3 sentences or less: It defines common Python vocabulary like strings, variables, booleans, and modulo. It also gives examples of good and bad variable names. Various Python data structures are demonstrated like lists, while and for loops, if/else statements, functions, and the Fibonacci sequence. Common string and list methods are shown along with examples of calculating areas of circles, guessing games, and basic calculators.

Uploaded by

pca_pca
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Python Cheat Sheet

by sura1234 via cheatography.com/25868/cs/6990/

Vocabulary Upper Lower List (cont) Guessing Game (cont)

String A list of characters such as numbers, while item_n​umber < len(sh​opp​ing​list): chances = chances - 1
letters, symbols print ("list item:", shoppi​ngl​ist​[it​em_​num​ber]) print ("Ch​ances left: ", chances)
item_n​umber = item_n​umber + 1 if user_guess in mylist:
Variable Holds a value and can be changed
#for loop print ("That's incorr​ect​")
Syntax The set of rules that defines the
other = 0 else:
combin​ations of symbols
for cat in shoppi​nglist: print ("Sorry, that is not even in the list!")
Boolean Identified True or False (true is not other = other + 1 if chances == 0:
the same as True, false is not the # print ("List item:", cat) print ("The word was: ", random​_item)
same as False) print (other) print ("Final score =", scores)
Modulo Finds the remainder after division of print ("GAME OVER!!​!!!​!!!​")

one number by another Radius of a Circle


Calculator
while True:
Variable Name #Ask the user for a radius of a circle def calc(num1, num2, operat​ion):

Good Variable Name user_r​adius = input(​"What is the radius of the if operation == "​sum​":

my_string = "​123​" circle ") return sum(num1, num2)


_hello = "​1" #Convert the given radius to a floating point elif operation == "​pro​duc​t":

mystring = 1 radius = (float​(us​er_​rad​ius)) return produc​t(num1, num2)

value1 = 1 #Make a variable called pi elif operation == "​dif​f":

#can have integers, lowerc​ase​/up​per​case, pi = 3.1415 return diff(num1, num2)

unders​cores #Calculate the area of the circle using elif operation == "​div​":

#the first character must be a exponents return div(num1, num2)

lowerc​ase​/up​percase or an underscore area = (pi (radius * 2)) else:


Bad Variable Name #Display the area of the circle to the user print ("Un​known Operat​ion​")

email@ = 2 print(​"The area of the circle is", area) def sum(a, b):

1value = 2 return a + b
Guessing Game def product(a, b):
return a * b
Upper Lower List #PWTK 1002
def diff(a, b):
mystr = "​hello THERE" scores = 0
return a - b
print (mystr.up​per()) #Upper case all the letter in chances = 3 def div(a, b):
a word while chances > 0: if b == 0:
print (mystr.lo​wer()) #Lower case all the letter in print ("-=​-=-​=-=​-=-​=-=​-=-​=-=​-Gu​essing Game-
return ("Error: Undefined value")
a word =​-=-​=-=​-=-​=-=​-=-​-=-​=-=​-")
else:
print (mystr.ca​pit​ali​ze()) #Capital only first letter import random
return a // b
of first word mylist = ['apple', 'banana', 'papaya', 'melon', print(​cal​c(12, 12, "​sum​"))
print (mystr.ti​tle()) #Capital first letter of every 'orange', 'grape', 'mango'] print(​calc(9, 18, "​dif​f"))
word. print (mylist)
print(​cal​c(20, 10, "​pro​duc​t"))
#List in python random​_item = random.ch​oic​e(m​ylist)
print(​cal​c(12, 4, "​div​"))
shoppi​nglist = ['Dogs', 'Cats', 'Mouses', 'Giraffe'] user_guess = input(​"​Guess a word: ")

print(​sho​ppi​ngl​ist[2]) #Will print 'Mouses' if user_guess == random​_item:

#while loop print ("That's correc​t")

item_n​umber = 0 scores = scores + 100


print ("Scores =", scores)
else:

By sura1234 Published 12th February, 2016. Sponsored by ApolloPad.com


cheatography.com/sura1234/ Last updated 17th March, 2016. Everyone has a novel in them. Finish Yours!
Page 1 of 4. https://apollopad.com
Python Cheat Sheet
by sura1234 via cheatography.com/25868/cs/6990/

Fibonacci Command Loop Range

num1 = 0 # Add # CAN WRITE #Creating List


num2 = 1 Hashtag comment ANYTHING HEREEE mylist = [1,2,3​,4,5,6]
fibonacci = num1 + num2 mylist2 = ['hi', 'hello', 'anyth​ing']
''' (3 Long ''' ALSO HEREEEEE
output = "​0,1​" mylist3 = [1, 'hello', 2.5]
Apostr​op comment '''
while fibonacci < 50: print (mylist)
he)
output = output + "​," + str(fi​bon​acci) print (mylist2)
print To display print (var)
num1 = num2 print (mylist3)
something
num2 = fibonacci #How to make a list with all numbers from 0-10
fibonacci = num1 + num2 '' '' Assign mystr = ("Ge​org​e") mynumbers = range(11) #0-10 (Number starts
print (output) something with 0)
in a for num in mynumbers:
Fibonacci variable print (num)

int() Set the integer = int(20) #with mylist​2.a​ppe​nd(​'an​other item') #Adding item in
num1 = 0 a list
number to no decimal
num2 = 1
interger print (mylist2)
fibonacci = num1 + num2
output = "​0,1​" str() Convert a String = str(in​teger)
Binary
while fibonacci < 50: variable to
output = output + "​," + str(fi​bon​acci) string while True:
num1 = num2 input() Gain Name = input(​" Put user_n​umber = input(​"Put the number: ")
num2 = fibonacci inform​ation your name here: " number = int(us​er_​number)
fibonacci = num1 + num2 from the binary​_string = ''
print (output) user while (number > 0):
remainder = (number % 2)
float() Convert the Num = float(2) #the
Loop Positive Integer binary​_string = str(re​mai​nder) + binary​_string
number answer will be 2.0
number = (number // 2)
even = 0 with
print ("binary string is", binary​_st​ring)
odd = 0 decimal
while True: len() Find the num1 = ("Ge​org​e"),,
Basic Info
user_input = int(in​put​("Enter a number :")) length of num2 = len(num1)
user = user_input % 2 the string #Answer will be 6 Basic Python Progra​mming Language
if user_input > 0: :(colon) = syntax
if user == 0: Reverse Syntax (=) Grammar
even = even + 1 Variable = Something that cahnge​s(n​umbers,
elif user != 0: word = input(​"​Input a word: ") words)
odd = odd + 1 reverse = "​" Number vs Strings: my var = 1 + 2
print(​use​r_i​nput) letter_num = 0 print my var = 3
else: ''' my var 2 = "​1" + "​2"
print ("Even number = ", even) while letter_num < len(word): print my var "​12"
print ("Odd number = ", odd) reverse = word[l​ett​er_num] + reverse hello= "​hel​lo" + "It's me"
break letter_num = letter_num + 1 print hello = "​hel​loI​t's​me"
''' If 1==2:
for item in word: When you do division in progra​mming the
reverse = item + reverse program will add decimal even if it doesn't
print ("Re​verse: "​,re​verse) have the decimal EX: 10.0

By sura1234 Published 12th February, 2016. Sponsored by ApolloPad.com


cheatography.com/sura1234/ Last updated 17th March, 2016. Everyone has a novel in them. Finish Yours!
Page 2 of 4. https://apollopad.com
Python Cheat Sheet
by sura1234 via cheatography.com/25868/cs/6990/

Basic Info (cont) Palindrome Number and String

my var = "​you​rna​me"[0] (the first letter in def isPali​ndr​ome​(word): "​Str​ing​" + Put both string together
progra​mming is 0 not 1) reverse = "​" "​Str​ing​"
== equal to for item in user_word:
Number + CRASH!
!= not equal to reverse = item + reverse
"​Str​ing​"
> Greater than revers​e_item = reverse
Number + Additi​on(​Math)
>= Greater than or equal to if revers​e_item == user_word:
Number
<= Less than or equal to return True#(​rev​ers​e_item, ("is a palind​rom​e"))
< Less than else: "​Str​ing​" * CRASH!
print (len(f​ull​name)) return False#​(re​ver​se_​item, ("is not a "​Str​ing​"
if 1 == 2: palind​rom​e")) "​Str​ing​" * Print that string that number
print ("tr​ue") while True: Number times
else: user_word = input(​"​Enter a word: ")
Number * Multip​lic​ati​on(​Math)
print ("fa​lse​") length = len(us​er_​word)
Number
if 2 == 2: if user_word == 'quit':
print ("tr​ue") break String ** String CRASH!
else: else: String ** CRASH!
print ("fl​ase​") print (length) Number
print ("fa​lse​2") numlen = 0
Number ** Expone​nt(​Math)
while numlen < length / 2 + 1:
Number
Return Max Number if user_w​ord​[nu​mlen] != user_w​ord​[-n​uml​en-1]:
print (user_​wor​d,"is not a palind​rom​")
def max2(num1, num2): Hexade​cimal
break
maxvalue = num1 numlen += 1 while True:
if num2 > maxvalue: else: user_n​umber = input(​"Put the number: ")
masvalue = num2 print (user_​wor​d,"is a palind​rom​e") number = int(us​er_​number)
return maxvalue
#Loop the command
def max3(num1, num2, num3):
Mathem​atics hex_string = ''
maxvalue = num1
while (number > 0):
if num2 > maxvalue: + Addition
remainder = number % 16
maxvalue = num2
- Subtra​ction if remainder == 10:
if num3 > maxvalue:
* Multip​lic​ation remainder = 'A'
maxvalue = num3
elif remainder == 11:
return maxvalue / Division (Result with floating point)
remainder = 'B'
def maxlis​t(l​ist): // Division elif remainder == 12:
maxvalue = list[0]
** Exponent remainder = 'C'
for num in list:
elif remainder == 13:
if num > maxvalue: % Modulo (Find remainder)
remainder = 'D'
maxvalue = num == Equal to
elif remainder == 14:
return maxvalue
>= Greater than or equal to remainder = 'E'
print (maxli​st(​[1,​2,3​,4,5]))
<= Less than or equal to elif remainder == 15:
remainder = 'F'
!= Not equal to
hex_string = str(re​mai​nder) + hex_string
< Less than number = number // 16
> More than print ("he​xad​ecimal string is 0x"+ hex_st​ring)

By sura1234 Published 12th February, 2016. Sponsored by ApolloPad.com


cheatography.com/sura1234/ Last updated 17th March, 2016. Everyone has a novel in them. Finish Yours!
Page 3 of 4. https://apollopad.com
Python Cheat Sheet
by sura1234 via cheatography.com/25868/cs/6990/

Countdown Area of Triangle (cont) List Practice (cont)

user_n​umber = input(​"​Please enter a number: print ("The area of the triangle is", random_var = random.ch​oic​e(v​arlist)
") areaof​Tri​ang​le(​use​r_base, user_h​eight)) print (varlist, random​_var)
number = int(us​er_​number) area = areaof​Tri​ang​le(​use​r_base,
countd​own​_string = "​" user_h​eight) Multip​lic​ation Table
while number > 0: def volume​ofP​ris​m(area, height):
def multip​lic​ati​onT​able():
countd​own​_string = countd​own​_string + return area * height
innum = int(in​put​("Enter a number: "))
str(nu​mber) user_h​eight2 = float(​inp​ut(​"​Enter the second
for i in range(​1,11):
number = number - 1 height of the triangle: "))
output = innum*i
#add the number to the string print ("The volume of the triangular prism is",
print (str(i​nnum) + "​*" + str(i) + "​=" +
#subtract 1 from the number volume​ofP​ris​m(area, user_h​eig​ht2))
str(ou​tput))
print (count​dow​n_s​tring)
multip​lic​ati​onT​able()
Loop Review
List Random​Choice
#While loop
import random mylist = [1,2,3]
intlist = [1, 2, 3, 4, 5] index = 0 #set to 0 because that is the first item
random_int = random.ch​oic​e(i​ntlist) in the list
print (intlist, random​_int) while index < len(my​list):
fplist = [2.2, 3.5, 4.8, 6.2, 7.9] print (mylis​t[i​ndex])
random_fp = random.ch​oic​e(f​plist) index = index + 1
print (fplist, random_fp) #For loop
strlist = ['burger', 'cheese', 'ham', 'bacon', for item in mylist:
'sandw​ich', 'pizza'] print(​item)
random_str = random.ch​oic​e(s​trlist)
print (strlist, random​_str) List Practice
mylist = [4, 6, 8, 11.4, 12.8, 17.6,'​coco', 'latte',
import random
'mocha']
intlist = [1, 2, 3, 4, 5]
random​_item = random.ch​oic​e(m​ylist)
random_int = random.ch​oic​e(i​ntlist)
print (mylist, random​_item)
print (intlist, random​_int)
myvar1 = 1
myvar2 = 2 fplist = [2.2, 3.5, 4.8, 6.2, 7.9]

myvar3 = 3 random_fp = random.ch​oic​e(f​plist)

varlist = [myvar1, myvar2, myvar3] print (fplist, random_fp)

random_var = random.ch​oic​e(v​arlist) strlist = ['burger', 'cheese', 'ham', 'bacon',

print (varlist, random​_var) 'sandw​ich', 'pizza']


random_str = random.ch​oic​e(s​trlist)
print (strlist, random​_str)
Area of Triangle
mylist = [4, 6, 8, 11.4, 12.8, 17.6,'​coco', 'latte',
# Pom Wintakorn 1002 'mocha']
def areaof​Tri​ang​le(​base, height): random​_item = random.ch​oic​e(m​ylist)
return 0.5 base height print (mylist, random​_item)
user_base = float(​inp​ut(​"​Enter the base of the myvar1 = 1
triangle: ")) myvar2 = 2
user_h​eight = float(​inp​ut(​"​Enter the height of myvar3 = 3
the triangle: ")) varlist = [myvar1, myvar2, myvar3]

By sura1234 Published 12th February, 2016. Sponsored by ApolloPad.com


cheatography.com/sura1234/ Last updated 17th March, 2016. Everyone has a novel in them. Finish Yours!
Page 4 of 4. https://apollopad.com

You might also like