Ask a user for a numerical input and store it as the variable 'number'. Print that number.
Front
>>>number = input("Enter a number: ")
>>>print(number)
Back
What are Python's Boolean operators?
Front
and, or, and not
In other programming languages, this is typically &&, ||, and !
Back
What is the output of the following?
>>>"Spam" + 'Eggs'
>>>5 + 4
>>>"5" + "4"
>>>"5" + 4
Front
'SpamEggs'
9
'54'
error
Back
What is concatenation? Are concatenated strings created with single or double quotes?
Front
The addition of two or more strings. It does not matter whether single or double quotes are used.
Back
What is the exponentiation operator?
Front
**
Back
What does the continue statement do?
Example code?
Front
It is a statement used within loops that, unlike breaks, causes the code to jump back to the top of the loop, rather than stopping it.
i = 0
while True:
>>>i = i + 1
>>>if i == 2:
>>>>>>print("Skipping 2")
>>>>>>continue
>>>if i = 5
>>>>>>print("Breaking")
>>>>>>break
>>>print(i)
print("Finished")
*Result:
1
Skipping 2
3
4
Breaking
Finished
Back
Assign the variable x to a value of 7 and print it using the print option.
Assign the variable spam to the string "eggs" and print it 3 times.
Taking into consideration operator precedence, evaluate the following as either True or False.
>>>False == False or True
>>>False == (False or True)
>>>(False == False) or True
Front
True
False
True
*In other words, == has a higher precedence than or
Back
Create the string 'Python' as the output.
Front
>>>'Python'
Back
What is the output for this?
>>>6 * 7.0
Front
42.0
Back
User input always has the type ___. Knowing this, convert user input into something that is not this type.
Front
string (str)
float(input("Enter a float: ")
int(input("Enter an integer: ")
Back
What is the output of this code?
num = 7
if num > 3:
>>>print("3")
if num < 5:
>>>print("5")
if num == 7:
>>>print("7")
Front
3
Back
What is the output of the following:
>>>print("spam" * 3)
>>>print("spam" * 3.0)
Front
spamspamspam
error, can't multiply a string and a float
Back
What is an elif statement short for? What does it do?
Front
An 'else if' statement. It is a shortcut statement to use when chaining if and else statements. A series of if elif statements can have a final else block, which is called if none of the if or elif expressions are True.
Back
Define iteration
Front
The repetition of a code being executed
Back
Write a program that displays "Hello world!"
Front
print('Hello world!')
Back
What is the output for this?
20 // 6
How do you determine the remainder?
Front
Output is 3. To find the remainder...
>>>20 % 6
Back
What is the output of this code?
>>>float("210" * int(input("Enter a number: ")))
Enter a number: 2
Front
210210.0
Back
What is a nested if statement?
Front
An if statement within an if statement
Back
Write a string that outputs the text 'Brian's mother'
Front
>>>'Brian\'s mother'
Back
What is a float?
Front
Numbers that are not integers (have decimals)
Back
Force x, which is assigned the integer 8, to become a string
Front
>>>str(x)
Back
Write the expression 'x = x + 3' more concisely.
Write the expression 'x = x * 3 more concisely.
Front
>>>x +=3
>>>x *=3
Back
What part of an if statement should be indented?
Front
The statements within it
Back
Mathematically, output '4'
Front
2 + 2 (or any other mathematical scenario equaling 4)
Back
What 3 characters are allowed in Python programming? In terms of naming variables, which of these 3 are you not allowed to have as the first character?
Front
Letters, numbers, and underscores.
Numbers
*Also note, Python is case sensitive
Back
What would be the output of the following:
>>>print(1 + 1)
Front
2
Back
Ask the user for input with "Please enter something: "
Front
For this we use the input() function
>>>input("Please enter something: ")
Back
Python is processed at runtime by the __. There is no need to __ the program before executing it.
Front
Interpretor; compile
Back
Write the general format of an if statement?
An if-else statement?
Front
if expression:
>>>statements
if expression:
>>>statements
else:
>>>statements
Back
What is the output of the following?
>>>x = "spam"
>>>x +="eggs"
>>>print(x)
Front
spameggs
Back
Triple quotes, strings, lesson 3
Front
Back
What is the result of this code?
x = 4
y = 2
if not 1 + 1 == y or x == 4 and 7 == 8:
>>>print("yes")
elif x > y:
>>>print ("no")
Front
Result is no
*Step 1:
if not 1 + 1 == y or x == 4 and 7 == 8
As per the operator precedence, the first 'and' is considered, x == 4 and 7 == 8, which evaluates to False. With this, the expression can be simplified to... if not 1 + 1 or False
Back
Evaluate as either True or False
>>>1 == 1 and 2 == 2
>>>1 == 1 and 2 == 3
>>>1 == 1 or 2 == 3
>>>2 < 1 or 3 != 3
>>>not 1 == 1
>>>not 1 > 7
Front
True
False
True
False
False
True
Back
What is the output of the following?
>>>int("3" + "4")
Front
34; this is become concatenation occurs first then the string is converted into an integer
Back
What is a while loop?
Give an example format of a while loop.
Front
A statement that can be run more than once. The statements within it execute as long as a condition holds. Once it evaluates to false, the next section of code executes.
i = 1
while i <=5:
>>>print(i)
>>>i = i + 1
Back
What is the output of this code?
>>>spam = "7"
>>>spam = spam + "0"
>>>eggs = int(spam) + 3
>>>print(float(eggs))
Front
73.0
Back
What is the output for this?
>>>10 / 2
Front
5.0
Back
Assuming it has already been assigned, delete the variable 'variable'.
Front
For this, we use del
>>>del variable
Back
What is the result of this code?
if 1 + 1 * 3 == 6:
>>>print("yes")
else:
>>>print("no")
Front
no
Back
Evaluate these as True or False
>>>7 > 5
>>>7 > 7
>>>7 >= 7.0
Front
True, False, True
Back
A list, a type of object in Python, is used to store an indexed list of items. It is created using ___ brackets with ___ separating items. Give an example format.
Front
square, commas
words = ["Hello", "world", "!"]
print(words[0])
print(words[1])
print(words[2])
*Result:
Hello
world
!
Back
To end a loop prematurely, the ___ statement can be used. Give an example of it in a while loop.
Front
break
i = 0
while 1 == 1:
>>>print(i)
>>>i = i + 1
>>>if i >= 5:
>>>>>>print("Breaking")
>>>>>>break
print ("Finished")
*Result is:
0
1
2
3
4
Breaking
Finished
Back
Write the code '2 raised to the 5th'
Front
2**5
Back
Which implementation of Python is the most popular?
Front
CPython
Back
In boolean terms, state that 2 is equal to 2. State that 2 is not equal to 3. State that hello is the same as hello.
Front
>>>2 == 2
>>>2 != 3
>>>"hello" == "hello"
All statements are True
Back
How many times can you reassign a variable?
Front
As many times as you want!
Back
What is the result of this code?
>>>7%(5//2)
Front
1
Back
How do you create a new line?
Front
Back
How do you perform a type conversion?
Convert the string "2" to an integer.
Convert the
Front
Back
Section 2
(46 cards)
What is the output of the following code?:
try:
>>>num1 = 7
>>>num2 = 0
>>>print(num1 / num2)
>>>print("Done calculation")
except ZeroDivisionError:
>>>print("An error occurred due to zero division error")
Front
An error occurred due to zero division error
Back
What does the return statement do?
What is the output of the following code?:
def max(x, y):
>>>if x >= y:
>>>>>>return x
>>>else:
>>>>>>return y
print(max(4, 7))
z = max(8, 5)
print(z)
Front
The return statement causes your function to exit and hand back a value to its caller. Return can be used alone to stop a function or it can be followed by the value to be returned.
7
8
Back
What does the following code do? / What is the output?
numbers = list(range(10))
print(numbers)
betweenNumbers = list(range(10, 15))
print(betweenNumbers)
Front
The range object creates a sequential list of numbers. Therefore, the code generated a list containing 10 integers.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14]
Back
What is the output of the following code?:
def print_with_exclamation(word):
>>>print(word + "!")
print_with_exclamation("spam")
print_with_exclamation("eggs")
How many arguments does it have?
Front
spam!
eggs!
The function has one argument.
Back
What does the insert method do and how do you use it?
Front
The insert method is similar to the append method, except that it allows you to insert a new item at any position in the list.
words = ["Python", "fun"]
index = 1
words.insert(index, "is")
print(words)
*Result:
['Python', 'is', 'fun']
Back
What is the output of the following?
for i in range(5):
>>>print("hello!")
Front
hello!
hello!
hello!
hello!
hello!
Back
Any statement that consists of a word followed by information in parentheses is called a ___ call.
Front
function
examples are:
print()
range()
str()
Back
What do the following function do?
max(list):
min(list):
list.count(obj):
list.remove(obj):
list.reverse():
Front
-Returns the list item with the maximum value
-Returns the list item with the minimum value
-Returns a count of how many times an item occurs in a list.
-Removes an object from a list
-Reverses objects in a list
Back
What is the output of the following code?:
def shortest_string(x, y):
>>>if len(x) <= len(y):
>>>>>>return x
>>>else:
>>>>>>return y
print(shortest_string(string, str))
Front
str
Back
What is the output of the following code?
def add(x, y):
>>>return x + y
def do_twice(func, x, y):
>>>return func(func(x, y), func(x, y))
a = 5
b = 10
print(do_twice(add, a, b))
Front
30
Back
What is the output of this code?
try:
>>>meaning = 42
>>>print(meaning / 0)
>>>print("the meaning of life")
except ZeroDivisionError:
>>>print("Divided by zero")
Front
Divided by zero
*Note that, print("the meaning of life") was skipped after the division by zero caused the execution of the except statement.
Back
What are the three types of modules in Python?
Front
Those you write yourself, those that you install from external sources, and those that are preinstalled with Python (Standard Library).
All standard library modules are available online at www.python.org
Back
What is the highest number printed by this code?
print(0)
assert "h" != "w"
print(1)
assert False
print(2)
assert True
print(3)
Front
1
This is because the assertion evaluated False whereas the first one was True
Back
Code can actually be called upon when an exception occurs. This is done by using the ___ statement. What is the general syntax of this?
Front
try/except
The try block contains the code that might throw an exception. If that exception occurs, the code in the try block stops being executed, and the code in the except block is run. If no error occurs, the code in the except block doesn't run.
Example format,
try:
>>>statements
except SpecificException
>>>statements
Back
How do you create an empty list?
Front
emptySet= []
Back
What is the output of this code?
def func(x):
>>>res = 0
>>>for i in range(x):
>>>>>>res += i
>>>return res
print(func(4))
Front
6
Back
Why are lists within lists often used to represent 2D grids?
Give an example
Front
Python lacks the multidimensional arrays that would be used for this in other languages.
number=3
things = ["string", 0, [1, 2, number], 4.56]
print(things[2])
print(things[2][2])
*Result:
[1, 2, 3]
3
Back
You can specify the ___ used to open a file by applying a second argument to the open function. Sending ___ means open in read mode (default), sending ___ means write mode for rewriting the contents of a file, sending ___ means append mode for adding new content to the end of the file. Adding a ___ means to open a file in binary mode which is used for non text files.
What is the result of the following code?
str = "Hello world!"
print(str[6])
Front
w
*Note that strings can be indexed like lists but integers cannot
Back
What is a module?
How do you import a module?
Front
Modules are pieces of code that other people have written to fulfill common tasks, such as generating random numbers, performing mathematical operations, etc.
The basic way to use a module is to add import module_name at the top of your code. Then using module_name.var to access functions and values with the name var in the module. For example, the following uses the module random to generate random numbers:
import random
for i in range(5):
>>>value = random.randint(1, 6)
>>>print(value)
Result:
2
3
6
5
4
Back
What does the index method do and how do you use it?
Front
The index method finds the first occurrence of a list item and returns its index.
letters = ['p', 'q', 'r']
print(letters.index('r'))
*Result:
2
Back
What does the append method do and how do you use it?
Front
The append method allows you to add an item to the end of an existing list.
nums = [1, 2, 3]
nums.append(7)
print nums
*Result:
[1, 2, 3, 7]
Back
An except statement without any exception specified will...
Front
Catch all errors
Back
What is the output of the following code?
print(1)
raise ValueError
print(2)
Front
1
ValueError
The raise statement allows you to raise exceptions, although you must specify the type of exception raised.
Back
The ___ statement is placed at the bottom of a try/except statement to ensure that specific code runs no matter what errors occur. It will always run after the execution of code in the try, and possible the except, blocks.
Example format?
Front
finally
try:
>>>print("Yo")
>>>print(1 / 0)
except ZeroDivisionError:
>>>print("Divided by zero")
finally:
>>>print("This code will run no matter what")
output:
Yo
Divided by zero
This code will run no matter what
Back
What is an exception?
Front
An event that occurs due to incorrect code or input. There are different exceptions for different reasons (i.e. ImportError, IndexError, etc). Third-party libraries also often define their own exceptions.
Back
What does the in operator do? What does the not operator do?
Give an example
Front
You can use the in operator to check if an item is in a list. You can use the not operator together with in to check if an item is not there.
words = ["spam", "egg", "spam", "sausage"]
print("spam" in words)
print("egg" in words)
print("tomato" in words)
*Result:
True
True
False
____
words = ["spam", "egg", "spam", "sausage"]
print(not "spam" in words)
print("egg" not in words)
print(not "tomato" in words)
*Result:
False
False
True
Back
An ___ is a sanity check that you can turn on or off when you have finished testing the program. An expression is tested and if the result comes up false, an expression is raised. For this, we use the ___ statement
Front
assertion, assert
Programmer often place assertions at the start of a function.
Back
What is the output of the following code?
name = "123"
raise NameError("Invalid name!")
Front
NameError: Invalid name!
Back
Many third-party Python modules are stored on the ___. The best way to install these is using a program called ___.
Front
Python Package Index (PyPI) and pip
Back
How do you access one specific function within a module?
For example, import both pi and sqrt from the math module
Front
from module_name import var
from math import pi, sqrt
Back
How do you annotate without disrupting the sequence of code?
Front
# followed by the comment you wish to enter. Anything after the # is ignored.
If you want to comment and it will take more than one line, use """. These are referred to as Docstrings (documentation strings)
For example:
code code code #this part is ignored
code code code
"""
this part is ignored
"""
codecode
The argument of the open function is the ___ to the file. If the file is in the same ___ as the program, you can specify only its name.
Front
path, directory
Back
What is the output of the following code?:
def print_sum(variable, y):
>>>variable += 1
>>>print(variable + y)
print_sum(5, 8)
How many arguments does it have?
Front
14
The function has two arguments
Back
How many except statements can follow a try statement?
Front
As many as necessary. For example:
try:
>>>statements
except ZeroDivisionError:
>>>statements
except(ValueError, TypeError):
>>>statements
*Note that the second except statement contains two exceptions, of which would be handled by the same statements.
Back
How do you get the number of items in a list?
Front
By using the len function.
nums = [1, 3, 5, 2, 4]
print(len(nums))
*Result:
5
Back
Create a list with the words "Hello" and "World". Then create a for loop that prints the words as such:
Hello
World
Front
array = ["Hello", "World"]
for word in array:
>>>print(word)
Back
Write the syntax to open a file, which has been assigned 'file', and create the argument to read it. Using the read method, print the contents of the file.
What is the output of this code?
list = [1, 1, 2, 3, 5, 8, 13]
print(list[list[4]])
Front
8
Back
Import the math module and it's sqrt function. Change the name of the sqrt function to 'square_root' and use it.
Front
For this you use as
from math import sqrt as square_root
print(square_root(100))
Back
How many lines will this code print?
while False:
>>>print("Looping...")
Front
0;
while statements work by checking if the condition is true. Another way of looking at the code is:
while False == True:
Since False never equals True, the loop will never run.
Back
In addition to using pre-defined functions, you can create your own functions by using the ___ statement.
Define a function called my_func that prints 'spamspamspam'.
How many arguments does this function have?
Front
def
def my_func():
>>>print("spamspamspam")
my_func()
This function has zero arguments.
Back
Python can be used to read and write the contents of files. The ___ files are the easiest to manipulate. Before it can be edited, it must be opened using the ___ function. After things are done to the file, it must be closed using the ___ method.
Show the syntax for this.
Front
.txt, open, close
myfile= open("filename.txt")
#do stuff to the file
myfile.close()
Back
What is the output of the following code?
try:
>>>num = 5 / 0
except:
>>>print("An error occured")
>>>raise
Front
An error occured
ZeroDivisionError: division by zero
Back
What is the output of the following code?
numbers1 = list(range(0, 10, 2))
numbers2 = list(range(0, 10, -2))
numbers3 = list(range(10, 0, -2))
print(numbers1)
print(numbers2)
print(numbers3)