Beginning Python Flashcards

Foundations of Python

1
Q

Visualize how to import a library

A

import library

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Visualize a for loop that uses a list and describe what each part is doing in the for loop

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Visualize a list

A

list = [a,b,c,d]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Visualize a nested loop

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a compound statement

A

A compound statement contains other statements inside of it.

like a for loop

They change the the control flow of information

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Visualize how to use range in a for loop

A

For x in range(4):
print(x)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a method

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is a parameter?

A

A parameter is a variable that is defined in a function definition.

def spiral(sides)

Sides is the variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is an argument?

A

An argument is an input that we pass to a function.
Spiral(100). 100 is the argument.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the scope of a variable that is passed inside a function?

A

It is a local scope, and can only be used inside the function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the scope of a variable passed outside of a function

A

It is a global scope and can be used both inside functions and outside functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a conditional statement?

A

A conditional statement tells python to run only when a condition is met.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Visualize a conditional statement

A

x = t.Turtle()

if x == 1:
x.color(‘blue’)
else:
x.color(‘yellow’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the modulo operator %?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What happens if a % b and b is bigger?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Visualize how to use % in a for loop

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Visualize how to use rand.choice

A

import random

A.
color = random.choice([‘red’,’blue’,’green’])

B.
colors = [‘red’,’blue’,’green’]
color = random.choice(colors)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Visualize how to use to use random.randint

A

import random

roll_die = random.randint(1,6)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Visualize all of the operators

A

a == b, a < b, a > b, a <= b, a >= b, a != b

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How does an elif work in an if statement? Visualize how to use an elif

A

Nesting if else statements is the same as using elif

if mood == “happy”:
color = “pink”
elif mood == “calm”:
color = “lightBlue”
else:
color = “red”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is Bash?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What do you type for BASH to recall your last command?

A

!!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Visualize how to create a variable in bash

A

x=100
echo $x
100

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How do you list the contents of the current directory in BASH?

A

ls

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How do you change directory in BASH? How do you go up one directory?
cd cd ..
26
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
27
How do you rename files in BASH?
mv old_filename.txt new_filename.txt
28
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'
29
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)
30
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
31
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
32
Visualize how to run python
python3 filename.py
33
Visualize how to open a file in BASH
open filename.txt
34
Visualize how to remove multiple folders and files
A. rmdir folder1 folder2 folder3 B. rm file1 file2 file3
35
Visualize how to open the files
touch filename.txt
36
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()
37
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)
38
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")
39
What are the ways to exit BASH?
exit(), quit()
40
Visualize how to print functions to the terminal
A. x = say_hello() print(x) B. print(say_hello())
41
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
42
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.
43
What will more_confused() print to the screen? Why def more_confused(): 2+2
None. A function without a return statement returns None.
44
Visualize how to import modules
Create file_name.py and write code * In terminal, type: * * python3 * * import file_name
45
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
46
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".
47
Visualize how to use the newline charachter
"For a line break\n" "Type the newline character\n"
48
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
49
What module lets you look up characters by emoji names?
unicodedata import unicodedata unicodedata.lookup("snake")
50
visualize how to loop over a list
for number in [1,2,3,4]: print(number) ## Footnote variable number is assigned each object in list and printed on screen
51
T or F: loops can loop over strings
True: for greeting in "Bonjour!": print(greeting)
52
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.
53
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
54
Visualize how to use range in a for loop
for side in range(4): print(side)
55
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]
56
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
57
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!"
58
What affect does * have on strings?
* operator performs string repetition. For ex. n = "2" n * 3 "222"
59
What method is used to check if a f string starts with another?
.starts_with()
60
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
61
What operations work on all sequence types?
the indexing operation the slicing operation the len function
62
How can you add 4 to the end of this list numbers = [1,2,3]
numbers.append(4)
63
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.
64
How do you sort a list?
list = [1,2,3] list.sort()
65
How do you reverse the order of a list?
list = [1,2,3] list.reverse
66
What is an augmented assignment statement?
Shorthand way to update the value of a variable using an operator in Python. +=, -=, /=, *=
67
How does a while loop works?
A while loop runs while some condition is True. n = 1 while n < 3: print(n) n += 1
68
How do you end an infinite loop in the terminal?
Ctrl + C
69
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']
70
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.
71
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
72
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
73
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
74
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
75
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]
76
Visualize how to create a while loop that runs infinitely
while True: while True: print("I'm trapped.") break
77
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
78
Visualize how to use the "not" operator for a list and a string
3 not in [1,2,3,4] False
79
What is pycodestyle and how can you use it?
pycodestyle helps you write uniform stylistic Python code. pip3 install pycodestyle pycodestyle example.py
80
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.")
81
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)
82
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)
83
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
84
T or F: When defining a function, it should have more than one purpose.
False. Refractor functions to have one purpose.
85
T or F: Loops are the only code that is repeatable
F: Functions also run repeatable code.
86
How do we access variables from other functions?
By passing functions or variables from other fuctions
87
Visualize how to flip this string using splicing: mystring = 'hello'
mystring[::-1]
88
Print out 'e' using indexing Print out 'o' using indexing s = 'hello'
s[1] s[-1]
89
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]
90
Visualize a Tuple
tuple = (1,2,3)
91
Visualize a set
set = (1,2,3)
92
Visualize adding a list to a set
list = [1,2,3,4,3,3,2,4] myset = set(list)
93
What short key will explain methods in Jupyter?
Shift + tab
94
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'))
95
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
96
Dictionary
dictionary = {'k1': 1, 'k2': 2}
97
How do you return the keys of a dictionary?
dictionary.keys()
98
How do you return the values of a dictionary
dictionary.values()
99
How do you return the key-value pairs?
.items()
100
Visualize how to read and write a file in Jupyter
with open(file.txt, mode='r') as new_file: content = new_file.read()
101
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()
102
. mode='r+' (Read and Write)
Allows reading existing content and writing/modifying data. Writing starts from the beginning unless you move the cursor.
103
mode='a' (Append Only)
You can only write to the file (at the end). Existing content is preserved, and new data is appended.
104
mode='w' (Write Only)
You can only write to the file, not read from it.