Show Menu
Cheatography

Python cheat sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

1

value/­object is interc­han­geable, assigned to variable
type of value/­object: print(­type( ))
type provides class: int, str, math, float, character
integers with commas are not legal (ie 42,000 --> 42 0)
integers with commas are treated as pair values

Functions and Parameters

Function Definition Syntax
def name( parameters ): statements
The syntax for a function definition is:

Functions and Parameters

Function Style 
def header(): 
     indent 4 spaces for statements

Compound Statements

used for condit­ional execution:
if_stmt ::=  "­if" expression "­:" suite

  ( "­eli­f" expression "­:" suite )*

   ["el­se" "­:" suite]

Chatbot

 

Bugs

error: variables must already have values in order to be used on the rh side
common errors: parse error (55%) type (15%) name (11%) value(10%)
other errors: URI, Token, Syntax, TimeLimit, Indent­ation, Attribute, Import, Index
ex's: parse: missing bracket, interprets as another parameter to function
EOF..: python got to the end of the file and was still looking for something
ValueE­rror: when you pass a parameter to a function and the function - the type you pass is not the expected one
Finding clues: print values and types in statement causing error
Name Error: you already used that name, wrong name or input etc

Bugs

1.  Adding two strings is not the same as adding two integers (be aware to convert user inputs)   
2.  Test boundary conditions: inside, outside and parameters themselves .  
3. Deal with input values outside the parameter: use modulo operator 

Example: use %24 to keep within parameters (0,23)! 
current_time= int(input("input hrs between 0-23") 
wait_time= int(input("how many hours do you want to wait?") 
final = (current_time + wait_time) % 24

Creating an Algorithm

1. Design the algorithm (instr­uctions with #)
2. Input code under hashes
 

Modules

modules are data objects - module objects contain other python elements
1. import module as whatever
to use something within a module, use dot notation
turtle.Turtle : In the module turtle, access the Python element called Turtle
others: math, random, pi, e
example: math.s­qrt(x), math.s­in(­mat­h.r­adi­ans­(de­gre­es)), math.pi will print 3.14.., math.e will print 2.718
random.ra­ndom() gives random number between [0.0, 1.0)
random.ra­ndr­ang­e(x,y)
other modules to check out: game

Examples

import random

howmany = 10 
for counter in range(howmany):
  arandom = random.random()
  print(arandom) #prints 10 random numbers

Important Section

 
Built In Types: Truth Values, Boolean Operators, Compar­isons, (Bitwise operat­ors), Additional methods on: integers, floats, strings, (Iterator and Generator Types), Sequence (str, list, tuple etc) Types, String Methods, String format­ting, etc : https:­//d­ocs.py­tho­n.o­rg/­2/l­ibr­ary­/st­dty­pes.html