python Cheat Sheet
by noeyarp via [Link]/25806/cs/6980/
Functions Functions (cont) Python Identifier
print() displays information on the screen. complex are of the form a + bJ, where a Defi is a name used to identify a variable,
input() receives information from the user. (complex and b are floats and J (or j) niti function, class, module or other object.
numbers) represents the square root of -1 on An identifier starts with a letter A to Z or
int() converts a value to an integer.
(which is an imaginary number). a to z or an underscore (_) followed by
float() change number to be decimal The real part of the number is a, zero or more letters, underscores and
number. and the imaginary part is b. digits (0 to 9).
str() a list of number,letter and symbols. Complex numbers are not used
much in Python programming. Python Assignment Operators
len() the length of the string.
# Comment or no effect Operator Description **E
Code
long Also called longs, they are integers
(long of unlimited size, written like integers Python Assignment Operators
name = "noey RAWIDA"
integers and followed by an uppercase or
print (name.upper())
) lowercase L. Operator Description Example
print (name.lower())
print (name.capitalize()) = Assigns values from c=a+b
print (name.title()) right side operands to assigns
left side operand value of a
Conditional + b into c
+=Add It adds right operand c += a is
if A statement that the writer given a
AND to the left operand equivalent
condition
and assign the result to c = c +
else A statement that can be combined with
to left operand a
an if statement.
- It subtracts right c -= a is
elif A statement that allows you to check
=Subtract operand from the left equivalent
multiple expressions for TRUE and AND operand and assign to c = c -
execute a block of code as soon as the result to left a
one of the conditions evaluates to
operand
TRUE.
while A statement that acting resembles like
a loop.
By noeyarp Published 15th February, 2016. Sponsored by [Link]
[Link]/noeyarp/ Last updated 8th March, 2016. Learn to solve cryptic crosswords!
Page 1 of 7. [Link]
python Cheat Sheet
by noeyarp via [Link]/25806/cs/6980/
Python Assignment Operators (cont) Random Code Number to Binary Code
*=Multiply It multiplies right c = a is import random mystring = "hello"
AND operand with the equivalent mylist = ['Dog','Fish', 'Cat', print (mystring)
left operand and to c = c a
'Bear'] firstname = input( "what is your
assign the result
counter = 0 first name?")
to left operand
while counter < 10: lastname = input( "what is your
/=Divide It divides left c /= a is
random_item = [Link] last name?")
AND operand with the equivalent
(mylist) fullname = firstname + " " +
right operand and to c = c / ac
assign the result /= a is print (random_item) lastname
to left operand equivalent counter = counter + 1 print (fullname)
to c = c / a letternumber = int(input( " what
%=Modulus It takes modulus c %= a is Number to Binary Code is letter number? " ))
AND using two equivalent if letternumber >len(fullname):
mystring = "hello"
operands and to c = c % print ( " invalid letter
print (mystring)
assign the result a
number, try again! " )
to left operand firstname = input( "what is your
else:
first name?")
**=Exponent Performs c = a is
letter = (
AND exponential lastname = input( "what is your
equivalent
fullname[letternumber] )
(power) to c = c a last name?")
print (letter)
calculation on fullname = firstname + " " +
operators and numberletter = int(input( "how
lastname
assign value to the many times to print letter " ))
print (fullname)
left operand if numberletter >100:
letternumber = int(input( " what
//=Floor It performs floor c //= a is print ( " too many letters
is letter number? " ))
Division division on equivalent to print! " )
if letternumber >len(fullname):
operators and to c = c // a else:
assign value to the print ( " invalid letter
print (letter *
left operand number, try again! " )
numberletter )
else:
letter = (
Addition
fullname[letternumber] )
print (letter) string + string combine together
numberletter = int(input( "how string + number crash
many times to print letter " ))
number + number math - addition
if numberletter >100:
print ( " too many letters
to print! " )
else:
print (letter *
numberletter )
By noeyarp Published 15th February, 2016. Sponsored by [Link]
[Link]/noeyarp/ Last updated 8th March, 2016. Learn to solve cryptic crosswords!
Page 2 of 7. [Link]
python Cheat Sheet
by noeyarp via [Link]/25806/cs/6980/
Multiplication and Exponents Python Variables Types Data Type Conversion (cont)
string * number combine that string multiple Number dict(d) Creates a dictionary, d must be a
times. String sequence of (key,value) tuples.
string * string crash List frozenset Converts to a frozen set.
number * math - multiply (s)
Tuple
number chr(x) Converts an integer to a character.
Dictionary
string ** string crash unichr(x) Converts an integer to a Unicode
character.
number ** math - exponents Data Type Conversion
number ord(x) Converts a single character to its
Function Description
string ** crash interger value.
number int(x Converts x to an integer. base hex(x) Converts an integer to a
[,base]) specifies the base if x is a string. hexadecimal string.
Loop float(x) Converts x to a floating-point oct(x) Converts an interger to an octal
number. string.
While Repeats a statement or group of
Loop statements while a given condition is long(x Converts x to a long integer. base
TRUE. It tests the condition before [,base] ) specifies the base if x is a string. Data Types
executing the loop body. str(x) Converts object x to a string Integer -256, 15
For Executes a sequence of statements representation.
Float -253.23, 1.253e-10
Loop multiple times and abbreviates the repr(x) Converts object x to an
String " Hel lo", 'Goodbye', " " " Mul til ine
code that manages the loop variable. expression string.
"""
Nested You can use one or more loop inside complex(r Create a complex number.
Boolean True,False
Loop any another while, for or do..while eal
loop. [,imag]) List [ value, ... ]
eval(str) Evaluates a string and returns an Tuple ( value, ... )1
object. Dictionary { key: value, ... }
tuple(s) Converts s to a tuple. Set { value, value, ... }2
list(s) Converts s to a list
set(s) Converts s to a set.
By noeyarp Published 15th February, 2016. Sponsored by [Link]
[Link]/noeyarp/ Last updated 8th March, 2016. Learn to solve cryptic crosswords!
Page 3 of 7. [Link]
python Cheat Sheet
by noeyarp via [Link]/25806/cs/6980/
Python Shop Code Python Shop Code (cont) Random Choice Code
print ("welcone to our shop") price = price+80 import random
price=0 print( "the price now mylist =
size=('s','m','l','xl') is",price) ['beagle','pomeranian','pug','golde
colour=('red','black','white') elif shirtcolour ==('white'): n','chihuahua']
sock=('want','not want') price = price+90 score = 0
print (size) print( "the price now chances = 3
shirt = (input('what shirt size do is",price) start_over = 0
you want?')) else: random_item =
if shirt == ('s'): print("our shop don't have [Link]oice(mylist)
price = price+70 this colour") while chances > 0:
print( "the price now print (size) start_over = 0
is",price) pant = (input('what pant size do random_item =
elif shirt ==('m'): you want?')) [Link]oice(mylist)
price = price+80 if pant == ('s'):
print( "the price now price = price+70 while start_over < 1:
is",price) print( "the price now print ("-=-=-=-=-=-=-=-
elif shirt ==('l'): is",price) =-=-=-=-=-=-=-=-=-")
price = price+90 elif pant ==('m'): print ("Guessing Game")
print( "the price now price = price+80 print ("-=-=-=-=-=-=-=-
is",price) print( "the price now =-=-=-=-=-=-=-=-=-")
elif shirt ==('xl'): is",price) print("words:", mylist)
price = price+100 elif pant ==('l'): guess = input("Guess a
print( "the price now price = price+90 word: ")
is",price) print( "the price now if (guess in mylist):
else: is",price)
print("our shop doesn't elif pant ==('xl'): if(guess ==
have this size.") price = price+100 random_item ):
print (colour) print( "the price now print("That's
shirtcolour= (input('what colour of is",price) correct!")
shirt do you want?')) else: score = score +
if shirtcolour == ('red'): print("our shop doesn't 100
price = price+70 have this size.choose again") print("Score:",
print( "the price now score)
is",price) start_over = 2
elif shirtcolour ==('black'): else:
print("Sorry, wrong
choice! ")
chances =
int(chances) -1
else:
print("Sorry, that is
not even in the list")
chances = int(chances)
-1
By noeyarp Published 15th February, 2016. Sponsored by [Link]
[Link]/noeyarp/ Last updated 8th March, 2016. Learn to solve cryptic crosswords!
Page 4 of 7. [Link]
python Cheat Sheet
by noeyarp via [Link]/25806/cs/6980/
Random Choice Code (cont) Loop list Code (cont) Vocabulary (cont)
if(chances > 0): print(userlist) integer whole number or counting number.
print("Chances number
remaining:",chances) float the number in decimal.
else: number
start_over = 2 Math syntax grammar structure of language.
print("Game Over! The value the number or the string can be
!= unequal or not equal to
word was ", random_item) store in valuable.
== equal to example;(a == b)
print("Chance loop
is not true.
remaining:", chances) module the text for storing for python
< less than example;(a < b)
print("Final score:", code.
is true.
score)
> more than example;(a > b) blank
is not true. comment
Loop list Code
<= less than or equal example;(a <= b) input receives information from the user.
def creatlist(quitword) : is true.
code
print ('Keep entering words to >= more than or equal example;(a >= b)
print to show information.
add to the list') is not true.
syntax make possible to the parse
print ('Quit when word =', % modulo or find the remainder
error
quitword)
<> If values of two example;(a <> b)
boolean true/false
mylist = [] operands are not is true. This is
while True: equal, then condition similar to !=
Python Arithmetic Operators
user_word = input('Enter a becomes true. operator.
word to add to the list:') Operat Description Exam
if user_word == quitword Vocabulary or ple
return mylist variable holds a value and can be changed. + Adds values on either side a+b
duplicateword = False Addition of the operator. = 30
string a list of characters such as numbers,
for item in mylist: letters, symbols.
if item == user_word:
duplicateword =
True
for item == user_word:
duplicateword =
True
if duplicateword == True:
print ('Duplicate
Word')
else:
myl[Link]pend(user_word
)
userlist = createList("stop")
By noeyarp Published 15th February, 2016. Sponsored by [Link]
[Link]/noeyarp/ Last updated 8th March, 2016. Learn to solve cryptic crosswords!
Page 5 of 7. [Link]
python Cheat Sheet
by noeyarp via [Link]/25806/cs/6980/
Python Arithmetic Operators (cont) Statements Code
- Subtracts right hand a-b= If Statement mystring = "hello"
Subtractio operand from left hand 30 if expression: print (mystring)
n operand. statements firstname = input( "what is your
* Multiplies values on either a*b= elif expression:
first name?")
Multiplica side of the operator. 200 statements
lastname = input( "what is your
tion else:
last name?")
statements
/ Division Divides left hand operand b/a=
While Loop fullname = firstname + " " +
by right hand operand. 2
while expression: lastname
% Divides left hand operand b%a statements print (fullname)
Modulus by right hand operand =0 For Loop letternumber = int(input( " what
and returns remainder.
for var in collection:
is letter number? " ))
** Performs exponential a ** b statements
if letternumber >len(fullname):
Exponent (power) calculation on = 10 Counting For Loop
print ( " invalid letter
operators. to the for i in range(s t art, end [, step]):
power number, try again! " )
statements
20 (start is included; end is not) else:
// Floor Division - The 9//2 = letter = (
division of operands 4 and Area of circle Code fullname[letternumber] )
where the result is the 9.0/2.0 print (letter)
while True:
quotient in which the = 4.0 numberletter = int(input( "how
digits after the decimal
many times to print letter " ))
point are removed. user_radius = input("What is
if numberletter >100:
the radius?")
print ( " too many letters
radius = float(user_radius)
to print! " )
pi = 3.1415
else:
area= pi radius * 2
print (letter *
print ("The area of the circle
numberletter )
is", area)
Print Code
name = "noey RAWIDA"
print (name.upper())
print (name.lower())
print (name.capitalize())
print (name.title())
By noeyarp Published 15th February, 2016. Sponsored by [Link]
[Link]/noeyarp/ Last updated 8th March, 2016. Learn to solve cryptic crosswords!
Page 6 of 7. [Link]
python Cheat Sheet
by noeyarp via [Link]/25806/cs/6980/
List Code Random Code 2
shoppinglist = ['tshirt' , 'pants' , import random
'socks'] intlist = [1,2,3,4]
for myvariable in shoppinlist: random_int =
print (myvariable) [Link]oice(intlist)
print (shoppinglist[1]) print(intlist,random_int)
for number in range(5): fplist = [1.0, 2.0, 3.0, 4.0]
print (number) random_fp = [Link]oice(fplist)
print(fplist,random_fp)
Count Down Code strlist =
['book','pen','bag','pencil']
#create a program that receives a
random_str =
number from the user and count down
[Link]oice(strlist)
from that number on the same line
print (strlist,random_str)
#recive the number from the user as a
mylist = [1, 1.0, 'beagle' ]
string
random_item =
user_number= input("enter number")
[Link]oice(mylist)
#convert the user number to an integer
print(mylist,random_item)
number = int(user_number)
myvar1 = 1
#setup the countdown string
myvar2 = 2
countdown_string = ""
myvar3 = 3
while number > 0:
varlist =[myvar1, myvar2, myvar3]
#add the number to the string
random_var =
#subtract 1 from the number
[Link]oice(varlist)
countdown_string =
print(varlist,random_var)
countdown_string + str(number) + ""
number = number-1
print (countdown_string)
#output should look like this
# if the user enter 5:
#5 4 3 2 1
#print (countdown_string)
By noeyarp Published 15th February, 2016. Sponsored by [Link]
[Link]/noeyarp/ Last updated 8th March, 2016. Learn to solve cryptic crosswords!
Page 7 of 7. [Link]