Python Statements Flashcards
What is a for loop?
A for loop is used for iterating over a sequence (that is either a list, tuple, dictionary or a string)
example
mylist = [‘cherry’, ‘banana’, 5, 6]
for item in mylist: print(item) if item == 'banana': print("I hit the number 5") break OUTPUT
cherry
banana
I hit the number 5
What is the continue statement?
The continue statement stops the current iteration of the loop, and continues with the next one. Basically it skips an item.
fruits = [“apple”, “banana”, “pear”]
for item in fruits:
if item == “banana”:
continue
print (item)
OUTPUT
apple
pear
What is a nested loop?
A nested loop is a loop, inside of a loop. Loop-ception.
adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "pear"]
for item in adj:
for fruit in fruits:
print (x, y)
How do you import a function from a library?
press tab after import to select list of functions from the library
from random from random import randint
randint(0,100)
OUTPUT #random number
How do you save a randint generated number?
savedrandomnumber = randint(0,10)
How do you accept user input?
By using in input function
userinput = input(‘Enter a number here: ‘)
What is the enumerate function?
The enumerate function essentially creates an index count for the string ‘abcdef’ in the form of tuples.
word = ‘abc’
for item in enumerate(word):
print(item)
OUTPUT
(0, ‘a’)
(1, ‘b’)
(2, ‘c’)
How do you unpack an enumerated string?
word = ‘ghi’
for index,letter in enumerate(word):
print(index)
print(letter)
print(‘\n’)
OUTPUT
0
g
1
h
2
i
What is List comprehension?
Give example
It’s essentially one line for loop built inside of brackets.
Example:
1st = [x for x in ‘word’]
OUTPUT
[‘w’, ‘o’, ‘r’, ‘d’]
mylist = [x for x in range(0,51) if x%3 ==0]
OUTPUT
mylist
[0, 3, 6, 9, 12, 15, …]
How could you square a number in range() and turn it into a list comprehension?
Example:
1st = [x**2 for x in range(0,11)]
OUTPUT
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
How do you add a if statement in a list comprehension?
Example:
1st = [x for xx in range(11) if x % 2 == 0]
OUTPUT
[0, 2, 4, 6, 8, 10]
How would you perform a nested list comprehension?
1st = [ x2 for x in [x2 for x in range(11)]]
OUTPUT
[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000]