Beginning Python Flashcards
Foundations of Python
Visualize how to import a library
import library
Visualize a for loop that uses a list and describe what each part is doing in the for loop
for side in [1,2,3,4]:
x.forward(100)
x.right(100)
side is a variable and the for is assigning a value/item in the list to the side variable each time the loop runs.
Visualize a list
list = [a,b,c,d]
Visualize a nested loop
for x in [1,2,3,4]:
t.forwad(100)
t.right(90)
for side in [1,2,3,4]:
t.forward(10)
t.right(90)
The loop runs 16 times. 4x4 = 16
What is a compound statement
A compound statement contains other statements inside of it.
like a for loop
They change the the control flow of information
Visualize how to use range in a for loop
For x in range(4):
print(x)
What is a method
A method is a function that’s associated with an object. They are used to give objects behaviors.
All methods are functions, but not all functions are methods.
What is a parameter?
A parameter is a variable that is defined in a function definition.
def spiral(sides)
Sides is the variable
What is an argument?
An argument is an input that we pass to a function.
Spiral(100). 100 is the argument.
What is the scope of a variable that is passed inside a function?
It is a local scope, and can only be used inside the function.
What is the scope of a variable passed outside of a function
It is a global scope and can be used both inside functions and outside functions.
What is a conditional statement?
A conditional statement tells python to run only when a condition is met.
Visualize a conditional statement
x = t.Turtle()
if x == 1:
x.color(‘blue’)
else:
x.color(‘yellow’)
What is the modulo operator %?
The modulo operator divides one number by another and then gives the remainder of that division.
5 % 1 is 0
5 % 2 is 1
6 % 3 is 0
What happens if a % b and b is bigger?
The remainder will be a:
For example:
7 % 10 gives the result 7
7 % 100 gives the result 7
7 % 1000 gives the result 7
Visualize how to use % in a for loop
for n in range(12):
if n % 3 == 0:
draw_triangle()
else:
draw_square()
The loop will run 12 times. When n is 0,3,6, or 9, the result will be 0
Visualize how to use rand.choice
import random
A.
color = random.choice([‘red’,’blue’,’green’])
B.
colors = [‘red’,’blue’,’green’]
color = random.choice(colors)
Visualize how to use to use random.randint
import random
roll_die = random.randint(1,6)
Visualize all of the operators
a == b, a < b, a > b, a <= b, a >= b, a != b
How does an elif work in an if statement? Visualize how to use an elif
Nesting if else statements is the same as using elif
if mood == “happy”:
color = “pink”
elif mood == “calm”:
color = “lightBlue”
else:
color = “red”
What is Bash?
Bash, short for Bourne-Again SHell, is a shell program and command language supported by the Free Software Foundation and first developed for the GNU Project by Brian Fox
What do you type for BASH to recall your last command?
!!
Visualize how to create a variable in bash
x=100
echo $x
100
How do you list the contents of the current directory in BASH?
ls
How do you change directory in BASH? How do you go up one directory?
cd
cd ..
A. How do you make a directory in BASH?
B. How do you move folders?
C. Visualize how to make a directory and move .jpg and .gif into the folders?
D. How would you check the files moved?
A. mkdir
B. mv
C.
mkdir Photos
mv *.jpg Photos
mkdir Animations
mv *.gif Animations
D. ls
How do you rename files in BASH?
mv old_filename.txt new_filename.txt
A. How do you download a file from the Web using BASH?
B. How do you output the data to a file?
A.
curl ‘http://www.url.com’
curl -L ‘http://www.url.com’
B.
curl -L -o filename.html ‘http://www.url.com’
A. How would you delete the folder created in BASH?
B. Command -r (recursive)
A. rmdir Folder
B. rm -r file_name
C. rm -i file_name (gives warnings)
Visualize all the ways to display the contents of a file
A. cat (to display the contents) filename.txt
B. nano (to edit the file) filename.txt
C. vim (to edit the file) filename.txt
D. less (to view the file) filename.txt
Scroll down = spacebar | DA
Scroll up = b | UA
Search = /
Exit less = q
Visualize how to use vim in BASH
vim filename.txt
Press i to enter Insert mode
Press Esc to exit Insert mode
to save changes :w and press Enter
To save and exit :wq and press Enter
Quit vim with :q
To exit without saving :q!
You can exit ZZ
Visualize how to run python
python3 filename.py
Visualize how to open a file in BASH
open filename.txt
Visualize how to remove multiple folders and files
A. rmdir folder1 folder2 folder3
B. rm file1 file2 file3
Visualize how to open the files
touch filename.txt
A. Visualize how to import the os module in Bash
B. Change the directory
C. Create a new file
D. Verify the file is created with list
A. import os
B. os.chdir(‘path’)
C. os.system(‘touch filename.txt’)
D. os.listdir()
A. Visualize how to use OS to return to the current working directory in BASH.
B. Visualize how to create a new directory given by the path
C. Visualize how to create a directory recursively
D. Remove the file at the specified path
E. Remove the directory at the specified path
A. os.getcwd(path)
B. os.mkdir(path)
C. os.makedirs(path)
D. os.remove(path)
E. os.rmdir(path)
A. Visualize how to rename a file or directory using OS in BASH from src to dst
B. Visualize how to join one or more path components
C. Visualize how to return True if a path exits or false otherwise
D. Visualize how to execute the command (the string) in a subshell
A. os.rename(src, dst)
B. os.path.join(path, *paths)
C. os.path.exists(path)
D. os.system(“command”)
What are the ways to exit BASH?
exit(), quit()
Visualize how to print functions to the terminal
A.
x = say_hello()
print(x)
B.
print(say_hello())
What will say_hello() print to the screen? and why?
def say_hello():
return “Hello!”
return “Goodbye!”
print(say_hello())
It will only return “Hello!” Because functions end after the first return
What will animal_count() print to the screen? Why?
def animal_count():
print(“Forty-Two”)
return 42
Only Forty-Two will print because we returned the value , but nothing gets done with the returned value.
What will more_confused() print to the screen? Why
def more_confused():
2+2
None.
A function without a return statement returns None.
Visualize how to import modules
Create file_name.py and write code
* In terminal, type:
* * python3
* * import file_name
Visualize how to use a function directly without the module prefix after importing
from file_name import function()
x = function()
print(x)
This imports the function directly and allows you to call it without the module name
What is dot notation and how does it work?
Dot notation is the period used on a function to denote to python where the module is located. chance.die_roll() is saying to python “call the die_roll() function, which is located in the chance module”.
Visualize how to use the newline charachter
“For a line break\n”
“Type the newline character\n”
Using an if statement, visualize how to count the number of objects in a list inside a function
list = len([1,2,3,4,5])
for x in list:
print(x)
the function len() counts lists and characters in strings
What module lets you look up characters by emoji names?
unicodedata
import unicodedata
unicodedata.lookup(“snake”)
visualize how to loop over a list
for number in [1,2,3,4]:
print(number)
variable number is assigned each object in list and printed on screen
T or F: loops can loop over strings
True:
for greeting in “Bonjour!”:
print(greeting)
What does it mean to make a directory recursively?
It means to create the directory and any necessary parent directories in the specified path if they do not already exist.
ex. home/user/documents/reports/2024
if reports and 2024 do not exist, it will create both folders.
Non-recursive will fail to create 2024 if reports do not exist.
Visualize how to create a function and pass parameters
def create_function(x, y):
x = 0
for y in string:
if y == variable_targe:
x = x + 1
return x
Visualize how to use range in a for loop
for side in range(4):
print(side)
What does it mean for the function range() to be exclusive
It means the number you give is excluded.
range(4) is equivalent to [0,1,2,3]
What does each number in range(0, 10, 2) mean?
Each number represents a parameter.
0 - the number to start with
10 - the number to stop at
2 - the step size or how large to increment
Visualize how to use an f string
x = “string”
f”Hello {x}!”
f-strings will convert numerical values into strings
answer = 42
f”The answer is {answer}”
“The answer is 42!”
What affect does * have on strings?
- operator performs string repetition.
For ex.
n = “2”
n * 3
“222”
What method is used to check if a f string starts with another?
.starts_with()
What is the not operation? And visualize it’s use
A logical operator used to negate or reverse a boolean value. It returns True if the operand is False, and False if the operand is True.
not x is true if x is false
not x is false if x is true
What operations work on all sequence types?
the indexing operation
the slicing operation
the len function
How can you add 4 to the end of this list numbers = [1,2,3]
numbers.append(4)
What does .extend() do?
Treats its argument as a sequence and adds each item in the sequence to the end of the list. In other words, it adds a sequence of items to a list.
How do you sort a list?
list = [1,2,3]
list.sort()
How do you reverse the order of a list?
list = [1,2,3]
list.reverse
What is an augmented assignment statement?
Shorthand way to update the value of a variable using an operator in Python.
+=, -=, /=, *=
How does a while loop works?
A while loop runs while some condition is True.
n = 1
while n < 3:
print(n)
n += 1
How do you end an infinite loop in the terminal?
Ctrl + C
What would the impact be on this
my_list = [1,2,3]
my_list.append([4,5,6])
my_list.extend([4,5,6])
my_list.append(“abc”)
my_list.extend(“abc”)
my_list.append([4,5,6]) = [1, 2, 3, [4, 5, 6]]
my_list.extend([4,5,6]) = [1, 2, 3, 4, 5, 6]
my_list.append(“abc”) = [1, 2, 3, ‘abc’]
my_list.extend(“abc”) = [1, 2, 3, ‘a’, ‘b’, ‘c’]
What does .append() do?
Adds its argument as a single item to the end of the list. It only ever adds one item to a list.
for word = “cat”
for index in range(len(word)
If we were to add a print statement, what is the difference between print(word) and print(word[index])
word refers to the whole string (“cat”)
word[index] extracts the specific character at position index in the string
What are the characteristics of a for loop?
Comes with a variable
Loops over a sequence of items, assigning to the variable.
Stops when it gets to the end of a sequence
What are the characteristics of a while loop?
Do not necessarily loop over a sequence
Does not automatically come with or need a variable
Runs while true or until condition is met
Visualize a linear search with a for loop
def until_dot(string):
for index in range(len(string)):
if string[index] == ‘.’:
# A dot! Return everything up to here.
return string[:index]
else:
# We ran out of string without seeing any dots.
# Return the whole string.
return string
Visualize how to do a linear search using a function with a while loop
def until_dot(s):
index = 0
while index < len(s) and s[index] != ‘.’:
# No dots yet, keep going.
index += 1
# We either found a dot or ran out of string.
return s[:index]
Visualize how to create a while loop that runs infinitely
while True:
while True:
print(“I’m trapped.”)
break
Visualize how to use the “in” operator for a list and a string
‘box’ in ‘big box of trouble’
True
3 in [1, 2, 3, 4]
True
Visualize how to use the “not” operator for a list and a string
3 not in [1,2,3,4]
False
What is pycodestyle and how can you use it?
pycodestyle helps you write uniform stylistic Python code.
pip3 install pycodestyle
pycodestyle example.py
How can we split very long lines?
story = (“Once upon a time there was a very long string that was “
“over 100 characters long and could not all fit on the “
“screen at once.”)
Visualize a function that replaces every period in a sentence with a space and “\n”
def breakify(string):
return string.replace(“. “, “.\n”)
# Apply the breakify function
output = breakify(intro)
# Print the result
print(output)
Visualize how to use join
A. on a list of strings
B. on a path
A. words = [“Hello”, “I”, “am”, “Bob”, “the”, “Breakfast”, “Bot”]
# Combine the list of words with spaces between them
sentence = “ “.join(words)
print(sentence)
#### Output: Hello I am Bob the Breakfast Bot
B. # Apply the breakify function
output = breakify(intro)
# Print the result
print(output)
When do you need to refractor your code?
- The code is more repetitive than it needs to be
- The code is overly complex or difficult to read
- The code is hard to maintain or modify
- The code is hard to re-use
T or F: When defining a function, it should have more than one purpose.
False. Refractor functions to have one purpose.
T or F: Loops are the only code that is repeatable
F: Functions also run repeatable code.
How do we access variables from other functions?
By passing functions or variables from other fuctions
Visualize how to flip this string using splicing:
mystring = ‘hello’
mystring[::-1]
Print out ‘e’ using indexing
Print out ‘o’ using indexing
s = ‘hello’
s[1]
s[-1]
Using keys and indexing grab hello
A. d = {‘simple_key’:’hello’}
B. d = {‘k1’:{‘k2’:’hello’}}
C. d = {‘k1’:[{‘nest_key’:[‘this is deep’,[‘hello’]]}]}
A. d[‘simple_key’]
B. d[‘k1’][‘k2’]
C. d[‘k1’][0][‘nest_key’][1]
Visualize a Tuple
tuple = (1,2,3)
Visualize a set
set = (1,2,3)
Visualize adding a list to a set
list = [1,2,3,4,3,3,2,4]
myset = set(list)
What short key will explain methods in Jupyter?
Shift + tab
Visualize how to use the the .format()
A. With no indexes
B. With indexes
C. With variables
A. print(‘This is a string {}’.format(‘INSERTED’))
B. print(‘The {2} {1} {0}’.format(‘fox’, ‘brown’, ‘quick’))
C. print(‘The {f} {q} {b}’.format(f=’fox’, b=’brown’, q=’quick’))
Visualize how to format result = 0.128700128 to 3 decimal places using .format()
“The float result would be {r:1.3f}”.format(r=result))
f: specifies the value if a float
.3: the number of decimal places to round
1: Minimum width
Dictionary
dictionary = {‘k1’: 1, ‘k2’: 2}
How do you return the keys of a dictionary?
dictionary.keys()
How do you return the values of a dictionary
dictionary.values()
How do you return the key-value pairs?
.items()
Visualize how to read and write a file in Jupyter
with open(file.txt, mode=’r’) as new_file:
content = new_file.read()
Visualize how to open and close a new file in Jupyter
my_new_file = open(‘text_file.txt’)
contents = my_new_file.read()
my_new_file.close()
. mode=’r+’ (Read and Write)
Allows reading existing content and writing/modifying data.
Writing starts from the beginning unless you move the cursor.
mode=’a’ (Append Only)
You can only write to the file (at the end).
Existing content is preserved, and new data is appended.
mode=’w’ (Write Only)
You can only write to the file, not read from it.