In this part of the course, you will complete various challenges with a range of difficulty levels. In doing so, you will learn the fundamentals of programming.
We will be using the website https://inventwithpython.com/invent4thed/ and following the chapters closely. This free resource is also written as a book which the author, Al Sweigart, sells on Amazon.
It will help your understanding greatly if you read the chapters for homework prior to the lessons, starting with the Introduction. However, do not install Python according to the instructions in the introduction - please go to the Getting Started page to do this as this is a much more up-to-date version of Python (and Pygame).
PROGRAMMING VOCABULARY
Click this link to go to a generic programming vocabulary list.
Click this link to create your own list of Subject Specific Words for this subject. This link is also on the task sheet (Major Project).
Accompanying Video: https://www.youtube.com/watch?v=7qHMXu99d88
• Operators
• Integers and floating-point numbers
• Values
• Expressions
• Syntax errors
• Storing values in variables
What are the four maths operators used in Python?
Write 3 examples of an integer.
Write 3 examples of a floating-point number.
Fill in the blank: An expression is made up of ________ connected by __________.
BEDMAS is used in computer programming. Evaluate the following using the Interactive Shell:
(3 + 4) * 4 - 3
12 * (2 - 1) / 6 + 4 * 2
What is the name of an error which occurs because something isn't typed properly?
Variables are used to store numbers. What will 'secretNumber' have stored in it after execution of the following 3 lines of code?
• Strings
• String concatenation
• Data types (such as strings or integers)
• Using the file editor to write programs
• Saving and running programs in IDLE
• Flow of execution
• Comments
• The print() function
• The input() function
• Case sensitivity
Select the correct answer: In Python, text values are called strings | variables | integers.
A single-line comment in Python begins with which character?
True or False: Python is case-sensitive.
Choose the correct answers: Variable names are usually lowercase | uppercase, but if there’s more than one word in the variable name, it’s a good idea to capitalize each word after the first. This is called camel case and is used because it makes the variable names easier | harder to read. Programmers like to use long | short variable names.
The user enters text through the keyboard with the ____________() function, and the computer displays text on the screen with the ______________() function.
Write the hello.py program using the File Editor (use File > New File) and add three more lines to the program so that the computer also asks for the user's age, allows the user to enter it, and then thanks the user for entering their age.
• import statements
• Modules
• The randint() function
• for statements
• Blocks
• The str(), int(), and float() functions
• Booleans
• Comparison operators
• Conditions
• The difference between = and ==
• if statements
• break statement
randint() is a module | function | variable which is part of the random statement | module | function.
Find this statement which explains line 12 and fill in the blanks: A for statement begins with the __________ keyword, followed by a new __________ name, the ________ keyword, a call to the __________ () function that specifies the number of loops it should do, and a ________.
Blocks of code are separated in Python using parentheses () | curly brackets {} | indentation using 4 spaces at a time.
Increasing | Decreasing the indentation level means the block of code is inside the previous block.
When the indentation level decreases | increases, the block of code above has ended.
Using the int(), float(), and str() functions, you can take a value of one data type and return it as a value of a different data type. int('67') will evaluate to ______. float(45) will evaluate to _______. str(85.0) will evaluate to _____.
The Boolean data type has only 1 | 2 | 3 values.
What are the six comparison operators?
True or False: Whenever you use a comparison operator, the expression will always evaluate to True or False.
A single | double equals sign is used to assign a value to a variable, whereas a single | double equals sign is used to compare whether two values are equal.
When an if-statement is executed and proves to be False, the block of code following it is skipped | executed.
When a break statement is encountered, execution immediately jumps out of | back to the start of | to the end of | into the loop it is in.
Change the program so that it generates a number between 1 and 100. Test to see if it works.
Change the program so that the user only gets 5 chances to get the answer right. This can build on the previous task (i.e. it can still be between 1 and 100). Test to see if it works.
Change the extended Hello.py program (last question from Chapter 2) so that after asking for the user's age, the computer tells the user how old they will be in one year's time. Test your code.
• Escape characters
• Using single quotes and double quotes for strings
• Using print()’s end keyword parameter to skip newlines
An escape character means the following character is special and is to be treated differently to other characters. Match the escape character to it's printed result (these are jumbled):
\" tab
\\ newline
\n single quote (')
\' backslash (\)
\t double quote (")
2. One way of printing quotes is to surround them with the other type of quotation marks. I.e. if you want to print double quotes, send the string to the print() function with the single quotes on the ends, and vice-versa. Which statement below would work to print the single quote in Who's there? [Choose one answer only]
a) print('Who's there?')
b) print("Who's there?")
c) print("Who"s there?")
d) It's grammatically incorrect and should be 'Whose there?'... Or is it??
3. Which code would print the following correctly?
Knock knock.
Who's there?
a) print('Knock knock.')
print('Who's there?')
b) print('Knock knock.', end='' )
print("Who's there?")
c) print('Knock knock.')
print("Who's there?")
• Flowcharts
• Creating your own functions with the def keyword
• Multi-line strings
• while statements
• The and, or, and not Boolean operators
• Truth tables
• The return keyword
• Global and local variable scope
• Parameters and arguments
• The sleep() function and time module
Functions are defined using which keyword? Type the keyword (with no spaces)..
Functions must always have parentheses () as part of their name. True or False?
Function definitions should go at the beginning | end of programs.
A call to a function looks like which line of code? [Choose one answer only]
a) print()
b) def helloWorld():
c) noneOfTheAbove
5. Multi-line strings in Python begin with:
a) /*
b) " or '
c) ''' or """
d) #
6. A while loop will continue looping as long as its condition remains True | False
7. Another way a while statement may stop is when a def | and | or | break statement is reached inside the while-block.
8. The following is called a truth table. It is used for AND, OR and NOT key words.
Determine the result of computing True and False.
Determine the result of computing True or False.
Determine the result of computing not False.
Determine the result of computing True and True.
Determine the result of computing False or False.
Determine the result of computing not True.
Determine the result of computing True or True.
Determine the result of computing False and False.
9. Determine the result of computing the following:
4 + 1 == 5 and 5 > 4
1 == 1 or 1 != 1
2 > 2 or 3 > 3
True,
10. A return statement immediately completes a function call (the execution of the function immediately ends) and a return value is sent back to where the function call was made. In the Dragon Realm program, the value inside cave is returned. This could be:
a) either of the strings '1' or '2'
b) either of the integer values 1 or 2
c) True or False
11. In the illustration below, the first occurrence of spam (at point 1) is defined in a global | local scope, whereas the second occurrence (at point 3) is in the local | global scope. These are different | the same variables.
11. In the following program (image below), the parameter is the word spam | Alice, Bob or Carol | name | sayHello.
12. True or False? According to the code above, when sayHello() has 'Alice', 'Bob' or 'Carol' in between the parentheses, the argument ('Alice', 'Bob' or 'Carol') is assigned to the name parameter.
13. A parameter, when a function is run, becomes a variable stored within the local | global scope of that function call.
14. The time module has a function called sleep() that pauses the program. Line 21 passes the integer value 2 so that time.sleep() will pause the program for two milliseconds | seconds | minutes.
15. Else statements can come only after if | while | for statement blocks.
16. What line of code does the main game loop actually begin on (according to the website - not your own which may be different)?
4
11
35
36
Can you change the program the give the player three options, with three different outcomes? Each outcome should have a 1/3 chance of occurring.
• Three types of errors
• IDLE’s debugger
• The Go and Quit buttons
• Stepping into, over, and out
• Breakpoints
You are not required to complete a quiz for this section!
• ASCII art
• Designing a program with flowcharts
You are not required to complete a quiz for this section!
• Lists
• The in operator
• Methods
• The split(), lower(), upper(), startswith(), and endswith() string methods
• elif statements
A common way to show that you don't want the contents of a variable to change is to...
a) use abbreviated variable names
b) use all capital letters in variable names
c) put a comment to explain that it is a constant at each time the variable is referred to
d) use all lowercase letters in variable names
Lists in Python are created using...
a) [] square brackets
b) () parentheses
c) {} curly brackets
d) " " quotation marks
Lists items in Python, when often created, are separated by...
a) ; semicolons
b) : colons
c) , commas
d) () parentheses
Which line of code would access the third item in a list named "clothes"?
a) clothes(3)
b) clothes().3
c) clothes[3]
d) clothes[2]
The number which references an item in a list is known as its value | index | number. The first item in a list is always at position 0 | 1 .
True or False? The following line of code changes the contents of an item in a list called "clothes", as long as there are more than 4 items in the list to begin with:
clothes[4] = 'jumper'
In this chapter, we learn a new operator which can tell you whether a value is in a list/string or not. Write the operator here (with no spaces): ____
Methods are function calls attached to def statements | integers | values. They are used/called by attaching them using a full stop | a comma | an underscore.
What will print to the screen with the following 3 lines of code?
sentence = My very energetic mother just served us nachos.
sentence = sentence.split()
print(sentence[1])
a) My very energetic mother just served us nachos.
b) My
c) very
d) ['My', 'very', 'energetic', 'mother', 'just', 'served', 'us', 'nachos.']
e) Nothing; it will produce an error
What method is used to find the number of characters in a string or the number of items in a list?
a) len()
b) split()
c) list()
d) range()
Slicing occurs when strings or lists start and end at given points. Slicing is done using two integers with which character in between? Type the character with no spaces.
What will be the results of the following slices?
word = 'Hello'
word[1:]
word[1:4]
word[:]
In Al's code, what line makes it possible to treat uppercase letters entered by the user the same as their lowercase equivalents (i.e. it doesn't matter if they enter a capital letter or not)?
a) line 38
b) line 68
c) line 69
d) line 74
According to line 82, will the user get to play again if they enter "yoyo" when the input() function is executed?
How many conditions need to be met when the user enters a guess in order for it to be a valid guess? Enter a number.
Save your hangman.py program as hangman2.py . In hangman2.py, give the user another guess by adding an extra multiline string to the HANGMAN_PICS list. This can be at whatever point you like, but as a suggestion, the first picture could be simply a pole instead of a pole with a horizontal beam attached. Double-check that it works.
Save your hangman2.py program as hangman3.py. In this version, change the function playAgain() so that the user can only write Y/y or N/n and nothing else in order to continue the game or stop the game.
Can you reference a separate file which contains a word list (download here), so that you can make the game more interesting with a lot more words to choose from? This website should help you out, but you will need to work out how to store each line (word) in your 'words' list by iterating over the lines of code in the file and storing each word as you go.
The following line of code will be useful to use in your loop. It appends (attaches) another word to your 'words' list one at a time whilst deleting any whitespace on the end of each line (including new line characters):
words.append(line.rstrip()) # note, "line" refers to a variable... you can use any name here
Can you create a hangman program which uses only 5 letter words from the words.txt file provided?
Can you create a new program which allows the user to enter a number to find out how many times words of that length appear in the words.txt file?