Vocabulary
Algorithm
Pseudocode
Flowchart
Comments
Documentation
String
Concatenation
Concepts
variables are place holders
assignment of values, data flow, goes from right to left
conditionals
loops
if/else statements
Nested structures
loops allow you to execute set of instructions multiple times
indentation tells python what instructions belong to the loop
Syntax
# assign 54 to variable x x = 54
# Display a message print("My name is Lily") # Display a product print( 3 * 2 ) # Display the content of a variable x = 54 print(x)
Conditionals and loops
# prompt the user for input - allows data from keyboard to your program name = input("what is your name? ") # prompt the user for a number # input assigns a string value # so it must be converted to integer for math operations or comparisons age = int(input("What is your age? ")) # Display messages and string variables using the concatenation operator + print("My name is " + name + " and yours? ") # Display messages and numerical variables print("My age is ", age, " and yours? ") or print("My age is " + str(age) + " and yours? ") # checking conditions if x > y: print( x," is larger than ",y) # loops while yesNo = "y":
Random Module
randNumber = random.randrange(1,8) random.randrange([start], stop[, step])
Lists
working with lists of numbers
Printing all the items in a list:
>>> intList = [54,32,78,23,45] >>> for i in intList: print(i,end=' ') 54 32 78 23 45 >>>
Adding all the items in a list
>>> intList = [54,32,78,23,45] >>> total = 0 >>> for i in intList: total += i >>> total 232 >>> or >>> sum(intList) 232 >>>
>>> len(intList) # number of items in the list 5 >>> import random >>> ranList=[] >>> ranList=[0,0,0,0,0,0,0,0,0,0,0,0,0] >>> # assign random integers from 3 through 51 included to a list >>> for i in range(len(ranList)): ranList[i]=random.randint(3,51) >>> ranList [43, 51, 43, 44, 37, 12, 7, 25, 32, 46, 14, 32, 20]
working with lists of strings
>>> wordList = ['red','yellow','black','green','blue'] >>> for word in wordList: print(word, end=' ') red yellow black green blue >>> for word in wordList: print(word) red yellow black green blue >>>
>>> for i in range(len(wordList)): print(i,wordList[i]) 0 red 1 yellow 2 black 3 green 4 blue >>>
>>> wordList = ['red','yellow','black','green','blue'] >>> len(wordList) 5 >>> wordList[0] 'red' >>> wordList[4] 'blue' >>> print(random.randint(0,len(wordList)-1)) 1 >>> print(random.randint(0,len(wordList)-1)) 4 >>> print(random.randint(0,len(wordList)-1)) 1 >>> print(random.randint(0,len(wordList)-1)) 1 >>> print(random.randint(0,len(wordList)-1)) 2 >>> print(random.randint(0,len(wordList)-1)) 0 >>> # Now we can select randomly any item in the list as many times as we want >>> print(wordList[random.randint(0,len(wordList)-1)]) red >>>