Podcast
Questions and Answers
In Python, what value type do comparison operators produce?
In Python, what value type do comparison operators produce?
- String
- Float
- Integer
- Boolean (correct)
In Python, the =
operator is used for making comparisons between two values.
In Python, the =
operator is used for making comparisons between two values.
False (B)
What operator is used in Python to check if two values are equal?
What operator is used in Python to check if two values are equal?
==
The ___
operator in Python checks if the value on the left is less than or equal to the value on the right.
The ___
operator in Python checks if the value on the left is less than or equal to the value on the right.
Match the comparison operators with their descriptions:
Match the comparison operators with their descriptions:
What is the result of the expression (5 > 3) and (2 < 4)
in Python?
What is the result of the expression (5 > 3) and (2 < 4)
in Python?
Chained comparison operators in Python allow you to combine multiple comparisons in a single expression.
Chained comparison operators in Python allow you to combine multiple comparisons in a single expression.
What is the purpose of the or
statement when chaining comparison operators in Python?
What is the purpose of the or
statement when chaining comparison operators in Python?
In Python, the ___
statement is used to check if both conditions in a chained comparison are true.
In Python, the ___
statement is used to check if both conditions in a chained comparison are true.
Match the following logical operators with their functions:
Match the following logical operators with their functions:
In Python, how do 'if' statements differ syntactically from similar constructs in languages like C++?
In Python, how do 'if' statements differ syntactically from similar constructs in languages like C++?
Python requires semicolons at the end of each statement, similar to Java.
Python requires semicolons at the end of each statement, similar to Java.
What punctuation mark is typically used at the end of a condition in an if
statement in Python?
What punctuation mark is typically used at the end of a condition in an if
statement in Python?
In Python, the amount of _________ used determines which statements will be executed in an if
block.
In Python, the amount of _________ used determines which statements will be executed in an if
block.
Match the code structure from other languages to its Python equivalent:
Match the code structure from other languages to its Python equivalent:
If x = 10 and y = 20, what will be the output of the following code?
if x>y:
print("X is greater than y:")
elif x<y:
print("X is less than y")
else:
print("x equal y")
If x = 10 and y = 20, what will be the output of the following code?
if x>y:
print("X is greater than y:")
elif x<y:
print("X is less than y")
else:
print("x equal y")
In a nested if
statement, the inner if
block will always be executed regardless of the outer if
condition.
In a nested if
statement, the inner if
block will always be executed regardless of the outer if
condition.
In Python, if you want to check multiple conditions in sequence, what keyword is used after the initial if
?
In Python, if you want to check multiple conditions in sequence, what keyword is used after the initial if
?
The _____
statement in Python is used to execute a block of code when none of the preceding if
or elif
conditions are true.
The _____
statement in Python is used to execute a block of code when none of the preceding if
or elif
conditions are true.
Match each conditional statement with its use case:
Match each conditional statement with its use case:
What will the following code print? marks = 60
if marks >= 90:
print("Excellent")
elif marks >= 80:
print("Very Good")
elif marks >= 70:
print("Good")
else:
print("Fail")
What will the following code print? marks = 60
if marks >= 90:
print("Excellent")
elif marks >= 80:
print("Very Good")
elif marks >= 70:
print("Good")
else:
print("Fail")
In Python, an elif
block can only be used after an else
block.
In Python, an elif
block can only be used after an else
block.
What is the first keyword used to start a conditional block in Python?
What is the first keyword used to start a conditional block in Python?
In Python, you can include multiple _____
statements to test different conditions in a sequential order.
In Python, you can include multiple _____
statements to test different conditions in a sequential order.
Match the keywords with their functions in a conditional structure:
Match the keywords with their functions in a conditional structure:
What does the term 'iterable' mean in the context of Python for loops?
What does the term 'iterable' mean in the context of Python for loops?
A for
loop can only iterate through numerical sequences in Python.
A for
loop can only iterate through numerical sequences in Python.
In a for
loop, what keyword is used to specify the variable that will take on the value of each element in the iterable?
In a for
loop, what keyword is used to specify the variable that will take on the value of each element in the iterable?
In the syntax of a Python for
loop, a _____ must be placed after the iterable.
In the syntax of a Python for
loop, a _____ must be placed after the iterable.
Match these terms with what they can iterate over:
Match these terms with what they can iterate over:
What parameter is used with the print()
function to display items on the same line in Python?
What parameter is used with the print()
function to display items on the same line in Python?
Using an asterisk *
before a list's name when passed to a function unpacks the list elements as individual arguments.
Using an asterisk *
before a list's name when passed to a function unpacks the list elements as individual arguments.
What argument in Python's print()
function lets you specify how to separate the items being printed?
What argument in Python's print()
function lets you specify how to separate the items being printed?
The ____
parameter when used with the print()
function specifies what character to include after the last value is printed.
The ____
parameter when used with the print()
function specifies what character to include after the last value is printed.
Match the following:
Match the following:
What does the %
operator do in Python?
What does the %
operator do in Python?
The continue
statement, when encountered inside a loop, will terminate the loop entirely.
The continue
statement, when encountered inside a loop, will terminate the loop entirely.
What built-in function in Python can quickly generate a list of integers?
What built-in function in Python can quickly generate a list of integers?
The ____
function in Python is used to iterate over a sequence while keeping track of the index of each element.
The ____
function in Python is used to iterate over a sequence while keeping track of the index of each element.
Match each function with its description:
Match each function with its description:
What is the result of using the input()
function?
What is the result of using the input()
function?
List comprehensions provide a more concise way to create lists compared to using for
loops with append()
.
List comprehensions provide a more concise way to create lists compared to using for
loops with append()
.
What is the fundamental operation in a list comprehension that builds a new list?
What is the fundamental operation in a list comprehension that builds a new list?
In a list comprehension, you can use an _____
statement to include elements that satisfy a certain condition.
In a list comprehension, you can use an _____
statement to include elements that satisfy a certain condition.
Match the following parts of a test:
Match the following parts of a test:
Flashcards
Comparison Operators
Comparison Operators
Operators in Python to compare variables and output a Boolean value (True or False).
Chained Comparison Operators
Chained Comparison Operators
An interesting feature of Python is the ability to chain multiple comparisons to perform a more complex test.
and
and
Checks if both conditions are true.
or
or
Signup and view all the flashcards
Python Statements
Python Statements
Signup and view all the flashcards
Indentation
Indentation
Signup and view all the flashcards
if, elif, else Statements
if, elif, else Statements
Signup and view all the flashcards
Iterable
Iterable
Signup and view all the flashcards
For Loops
For Loops
Signup and view all the flashcards
end=' '
end=' '
Signup and view all the flashcards
sep
sep
Signup and view all the flashcards
Modulo
Modulo
Signup and view all the flashcards
While Loops
While Loops
Signup and view all the flashcards
break
break
Signup and view all the flashcards
continue
continue
Signup and view all the flashcards
pass
pass
Signup and view all the flashcards
range()
range()
Signup and view all the flashcards
enumerate()
enumerate()
Signup and view all the flashcards
zip()
zip()
Signup and view all the flashcards
in
in
Signup and view all the flashcards
not in
not in
Signup and view all the flashcards
min()
min()
Signup and view all the flashcards
max()
max()
Signup and view all the flashcards
from random import shuffle
from random import shuffle
Signup and view all the flashcards
from random import randint
from random import randint
Signup and view all the flashcards
input()
input()
Signup and view all the flashcards
List Comprehensions
List Comprehensions
Signup and view all the flashcards
Study Notes
Comparison Operators
- Comparison operators allow the comparison of variables
- The operator outputs a Boolean value (True or False)
Comparison Operators Examples
- 2 == 2 returns a True Boolean because the values are equal
- 1 == 0 returns a False Boolean because the values are not equal
- 2 < 4 returns a True Boolean
- 2 < 1 returns a False Boolean
- 2 >= 2 and 2 >= 1 returns a True Boolean since 2 is greater than or equal to 2, and greater than or equal to 1
- 2 <= 2 and 2 <= 4 returns a True Boolean since 2 is less than or equal to 2, and less than or equal to 4
==
is a comparison operator, while=
is an assignment operator
Chained Comparison Operators
- Python allows the chaining of multiple comparisons to perform complex tests
- Chained comparisons are shorthand for larger Boolean expressions
and
statement examples:1<2 and 2<3
returns a True Boolean because both conditions are true.1<3 and 3>2
returns a True Boolean because the constraints are both still metor
statement example:1==2 or 2<3
returns a True Boolean because one condition is true- With the
or
operator, only one of the conditions needs to be true for the total check to be true
Python Statement Introduction
- Overview of Python statements is helpful to emphasize the differences between Python, C++, and other languages
- Gaining an understanding of Python is made quick and simple for those migrating from different languages
- Learning about Python enables understanding and reading code in other languages more easily
Python vs Other Languages
- Compared to other languages, Python is less cluttered and more readable
- Python does away with
()
and{}
by using a colon and whitespace/indentation practices - The statement ends with a colon, and whitespace (indentation) describes what takes place in the statement
- Python does not use semicolons. Instead, the end of a line is the same as the end of a statement
Indentation
- Code readability is a core part of the design of Python
- Whitespace and indentation in Python serves the same function as parenthesis in other languages, defining the scope and execution block of statements
Print Multiple Variables
- To print multiple variable with an inline string use the following syntax:
band = 8
name = "Sarah Fier"
print("The band for ", name, "is", band, "out of 10")
- Use
(+)
before parameters
Statement: Nested If
- Nested if statements allow conditional checks within conditional checks
- Example:
if x>y:
if y>10:
print(x)
print(y)
print(x+5) # always executed
If Elif & Else Statements
- Often, code should only should execute when a particular condition as been met
- Conditional flow of logic is controlled using the keywords:
if
,elif
, andelse
if Statements
allow the computer to perform actions based on a certain set of results/alternative actions- Can be expressed verbally as: "Hey if this case happens, perform some action"
elif
andelse
statements allow expansion to tell the computer: "Hey if this case happens, perform some action. Else, if another case happens, perform some other action. Else, if none of the above cases happened, perform this action."- Code example:
if x>y:
print("X is greater than y:")
elif x<y:
print(" X is less than y")
else:
print("x equal y")
- A first example of how to use an
If
,elif
andelse
statement demonstrates using inline logic using anif True
statement:
if True:
print('It was true!')
- Adding some
else
logic example:
x = False
if x:
print('x was True!')
else:
print('I will be printed in any case where x is not true')
Multiple Branches
if, elif
, andelse
can be used to take us far, can be a nested structure- The
if, elif
, andelse
line up, showing what theif
is related to, forelif
andelse
statements - The nested if statements are each checked until a True boolean causes the nested code below it to run
- It is possible to put in many elif statements before closing off with an else
For Loops
- Many objects in Python are iterable, meaning every element in the object can be iterated over
- For loops allows the program to execute a block of code for every iteration of said object
- Iterable means over every character in a string, every item in a list, and every key in a dictionary is accessible
- The syntax for a for loop is:
my_iterable = [1,2,3]
for item_name in my_iterable:
print(item_name)
For Loops and Lists
- Iterating through a list can occur by implementing the following:
## Automate this sort of list,
list1= [1,2,3,4,5,6,7,8,9,10]
for num in list1:
print(num)
- When printing multiple iterations, the
print
command should be placed on the same line to display all results linearly - Example:
list=[1,2,3,4,5,6,7,8,9]
for item in list:
print(item,end=" ")
Asterisks for Unpacking into Function
- Asterisks unpack items into a function call
fruits = ['lemon', 'pear','watermelon', 'tomato']
print(fruits[0], fruits[1],fruits[2], fruits[3])
print(*fruits)
sep
sep
can be declared to specify parameters in the items that are unpacked
fruits = ['lemon', 'pear','watermelon', 'tomato']
print(*fruits,sep="**")
- In the result each word would be separated by two asterisks
Modulo operator
- Modulo gives the remainder in a division/uses %, returns the values inline with the original statement
For Loops / Lists
list=[1,2,3,4,5,6,7,8,9,10]
sum=0
for item in list:
sum=sum +item
print(sum)
- Above example shows the sum of a list
- Important to note the effect of indentation here. Indentation inside an active for loop causes functions like print() to return a result on each iteration
For Loops
end=''
will return inline output if it's declared in iterativefor
loops
For Loops/Tuples
- Example of a for loop used with a tuple:
tup = (1,2,3,4,5)
for t in tup:
print(t)
List of Tuples
- When iterating through a sequence that contains tuples, the item can be the tuple itself, serving as an example of tuple unpacking.
list = [(1,2), (3,4), (5,6), (7,8)]
for item in list:
print (item)
Dictionary
- A for loop only produces the keys of a dictionary
.keys()
is a new dictionary method. Output = all keys in the dictionary.values()
is a new dictionary method. Output = all values in the dictionary.items()
is a new dictionary method. Output = all key/value pairs in dictionary- Dictionaries are unordered
- Keys and values come back in arbitrary order
- A sorted list can be obtained using
sorted()
Dictionary unpacking
d={'k1':1, 'k2':2, 'k3':3}
for k,v in d.items():
print(k)
print(v)
While Loops
- While loops will continue to execute a block of code while some condition remains True
- Example:
while some_boolean_condition:
#do something
else:
#do something different
- Another example:
x=0
while x < 10:
print(x)
x+=1
else:
print('DONE')
Break, Continue and Pass
break
,continue
, andpass
, are statements added to loops to add additional functionalitybreak
: Breaks out of the current closest enclosing loopcontinue
: Goes to the top of the closest enclosing looppass
: Does nothing at all- Break and continue statements can appear anywhere inside the loop's body
- Often put them further nested in conjunction with an if statement to perform an action based on some condition
- Example:
x = 0
while x < 10:
print('x is currently: ',x)
x+=1
if x==3:
continue
print('x==3')
print('Continue')
#continue
elif x==8:
print('Reach 8...')
break
- The difference between Pass and Continue - "pass" statement
s = "geeks"
# Pass statement
for i in s:
if i == 'k':
print('Pass executed')
pass
print(i)
g
e
e
Pass executed
k
- The difference between Pass and Continue - "Continue" statement
s = "geeks"
## Continue statement
for i in s:
if i == 'k':
print('Continue executed')
continue
print(i)
g
e
e
Continue executed
s
Useful Operators
- "Operators" and built in functions that don't fit well into any category
- RANGE is a function allows the user to create a list of integers, requires that they be cast with the
list()
function to be properly implemented. You can include a start, stop, and steplength as range parameters
Enumerate
- Python Enumerate can be used in code when there is a frequent need to track how many loops have gone through
- List out the process without looping:
index_count = 0
for letter in 'abcde':
print("At index {} the letter is {}".format(index_count, letter))
index_count += 1
Enumerate - Tuple Unpacking
- For the code:
for i, letter in enumerate('abcde'):
print("At index {} the letter is {}".format(i, letter))
- The output shows each letter and its place in the object
Zip
- Enumerate returns a list - format is enumerated using .list() - and meaning you can use tuple unpacking during our for loop
- The zip() function acts by quickly is used to create a list of tuples by "zipping" up together two lists
list1=[1,2,3,4,5]
list2=['A','B', 'C','D','E']
for a,b in zip(list1, list2):
print(a)
print(b)
The *in` Operator
- This operator is used to check to quickly check if an object is in a list
Combination Operators
- Example: combine
in
withnot
, to check if some object or variable is NOT present in a list
Min and Max operators
- Used to check the minimum or maximum of a list
Random Operators
- The Random function shuffle the list in place
from random import shuffle
mylist = [40, 10, 100, 30, 20]
shuffle(mylist)
- The Function "shuffle", shuffles the list in place - meaning it won't return
List Comprehensions
- List Comprehensions acts like a way of quickly is a unique way of creating lists with Python
- Can be used as a good alternative if the user is using a for loop along with .append() to create a list
Creating Lists with List Comprehension
1st = [x for x in 'word']
- Square numbers in a range and turn into a list
1st = [x**2 for x in range(0,11)]
- check for even numbers in a range
1st = [x for x in range(11) if x % 2 == 0]
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.