Python Comparison Operators

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

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.

False (B)

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.

<p>&lt;=</p>
Signup and view all the answers

Match the comparison operators with their descriptions:

<p>== = Equal to != = Not equal to</p> <blockquote> <p>= = Greater than or equal to &lt; = Less than</p> </blockquote>
Signup and view all the answers

What is the result of the expression (5 > 3) and (2 < 4) in Python?

<p>True (A)</p>
Signup and view all the answers

Chained comparison operators in Python allow you to combine multiple comparisons in a single expression.

<p>True (A)</p>
Signup and view all the answers

What is the purpose of the or statement when chaining comparison operators in Python?

<p>Checks if at least one comparison is true</p>
Signup and view all the answers

In Python, the ___ statement is used to check if both conditions in a chained comparison are true.

<p>and</p>
Signup and view all the answers

Match the following logical operators with their functions:

<p><code>and</code> = Returns True if both statements are true <code>or</code> = Returns True if one of the statements is true</p>
Signup and view all the answers

In Python, how do 'if' statements differ syntactically from similar constructs in languages like C++?

<p>Python uses indentation to define the scope of the code block. (B)</p>
Signup and view all the answers

Python requires semicolons at the end of each statement, similar to Java.

<p>False (B)</p>
Signup and view all the answers

What punctuation mark is typically used at the end of a condition in an if statement in Python?

<p>:</p>
Signup and view all the answers

In Python, the amount of _________ used determines which statements will be executed in an if block.

<p>indentation</p>
Signup and view all the answers

Match the code structure from other languages to its Python equivalent:

<p>Curly braces <code>{}</code> in C++ = Indentation in Python Semicolons at the end of statements = End of line</p>
Signup and view all the answers

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")

<p>&quot;X is less than y&quot; (A)</p>
Signup and view all the answers

In a nested if statement, the inner if block will always be executed regardless of the outer if condition.

<p>False (B)</p>
Signup and view all the answers

In Python, if you want to check multiple conditions in sequence, what keyword is used after the initial if?

<p>elif</p>
Signup and view all the answers

The _____ statement in Python is used to execute a block of code when none of the preceding if or elif conditions are true.

<p>else</p>
Signup and view all the answers

Match each conditional statement with its use case:

<p><code>if</code> = To execute code if a condition is true <code>elif</code> = To check an additional condition if the previous <code>if</code> condition is false <code>else</code> = To execute code if all previous conditions are false</p>
Signup and view all the answers

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")

<p>&quot;Fail&quot; (D)</p>
Signup and view all the answers

In Python, an elif block can only be used after an else block.

<p>False (B)</p>
Signup and view all the answers

What is the first keyword used to start a conditional block in Python?

<p>if</p>
Signup and view all the answers

In Python, you can include multiple _____ statements to test different conditions in a sequential order.

<p>elif</p>
Signup and view all the answers

Match the keywords with their functions in a conditional structure:

<p><code>if</code> = Begins a conditional block <code>elif</code> = Tests an additional condition <code>else</code> = Provides a default action if no conditions are met</p>
Signup and view all the answers

What does the term 'iterable' mean in the context of Python for loops?

<p>Able to have its elements accessed one by one. (D)</p>
Signup and view all the answers

A for loop can only iterate through numerical sequences in Python.

<p>False (B)</p>
Signup and view all the answers

In a for loop, what keyword is used to specify the variable that will take on the value of each element in the iterable?

<p>for</p>
Signup and view all the answers

In the syntax of a Python for loop, a _____ must be placed after the iterable.

<p>:</p>
Signup and view all the answers

Match these terms with what they can iterate over:

<p>String = Every character List = Every item Dictionary = Every key</p>
Signup and view all the answers

What parameter is used with the print() function to display items on the same line in Python?

<p>end (D)</p>
Signup and view all the answers

Using an asterisk * before a list's name when passed to a function unpacks the list elements as individual arguments.

<p>True (A)</p>
Signup and view all the answers

What argument in Python's print() function lets you specify how to separate the items being printed?

<p>sep</p>
Signup and view all the answers

The ____ parameter when used with the print() function specifies what character to include after the last value is printed.

<p>end</p>
Signup and view all the answers

Match the following:

<p>Asterisk (*) = Used for unpacking into a function call sep=&quot;**&quot; = Changes seperation between printed text</p>
Signup and view all the answers

What does the % operator do in Python?

<p>Returns the remainder of a division. (D)</p>
Signup and view all the answers

The continue statement, when encountered inside a loop, will terminate the loop entirely.

<p>False (B)</p>
Signup and view all the answers

What built-in function in Python can quickly generate a list of integers?

<p>range()</p>
Signup and view all the answers

The ____ function in Python is used to iterate over a sequence while keeping track of the index of each element.

<p>enumerate</p>
Signup and view all the answers

Match each function with its description:

<p>range() = Quickly generates a list of integers enumerate() = Iterates over a sequence while keeping track of the index of each element</p>
Signup and view all the answers

What is the result of using the input() function?

<p>String (B)</p>
Signup and view all the answers

List comprehensions provide a more concise way to create lists compared to using for loops with append().

<p>True (A)</p>
Signup and view all the answers

What is the fundamental operation in a list comprehension that builds a new list?

<p>Expression</p>
Signup and view all the answers

In a list comprehension, you can use an _____ statement to include elements that satisfy a certain condition.

<p>if</p>
Signup and view all the answers

Match the following parts of a test:

<p>.split() = Used to split the string into different parts For = Used to create a statement If = Create a statement with specific words</p>
Signup and view all the answers

Flashcards

Comparison Operators

Operators in Python to compare variables and output a Boolean value (True or False).

Chained Comparison Operators

An interesting feature of Python is the ability to chain multiple comparisons to perform a more complex test.

and

Checks if both conditions are true.

or

Checks if at least one condition is true

Signup and view all the flashcards

Python Statements

Emphasizes differences between Python and other languages

Signup and view all the flashcards

Indentation

Whitespace used to describe what takes place in case of the statement.

Signup and view all the flashcards

if, elif, else Statements

if Statements in Python allows us to tell the computer to perform alternative actions based on a certain set of results.

Signup and view all the flashcards

Iterable

Allows us to iterate over every element in the object.

Signup and view all the flashcards

For Loops

A control flow statement that allows code to be executed repeatedly.

Signup and view all the flashcards

end=' '

Used to print items in the same line within a loop.

Signup and view all the flashcards

sep

It separates the values.

Signup and view all the flashcards

Modulo

Allows us to get the reaminder in a division.

Signup and view all the flashcards

While Loops

A loop that continues to execute a block of code while some condition remains True.

Signup and view all the flashcards

break

Breaks out of the current closest enclosing loop.

Signup and view all the flashcards

continue

Goes to the top of the closest enclosing loop.

Signup and view all the flashcards

pass

Does nothing at all.

Signup and view all the flashcards

range()

Allows you to quickly generate a list of integers.

Signup and view all the flashcards

enumerate()

A very useful function to use with for loops.

Signup and view all the flashcards

zip()

Returns back some sort of index counter and then the object itself or the element at that particular iteration.

Signup and view all the flashcards

in

Keyword to check if an object is in a list

Signup and view all the flashcards

not in

Combines 'in' with a 'not' operator, to check if some object or variable is not present in a list.

Signup and view all the flashcards

min()

Quickly check the minimum of a list with this function.

Signup and view all the flashcards

max()

Quickly check the maximum of a list with this function.

Signup and view all the flashcards

from random import shuffle

There are a lot of functions included in this. It shuffles the list in place meaning it won't return.

Signup and view all the flashcards

from random import randint

Return random integer in the range.

Signup and view all the flashcards

input()

Wait user to enter value

Signup and view all the flashcards

List Comprehensions

Unique way of quickly creating a list with Python.

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 met
  • or 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
  • 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, and else
  • 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 and else 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 and else statement demonstrates using inline logic using an if 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, and else can be used to take us far, can be a nested structure
  • The if, elif, and else line up, showing what the if is related to, for elif and else 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 iterative for 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, and pass, are statements added to loops to add additional functionality
  • break: Breaks out of the current closest enclosing loop
  • continue: Goes to the top of the closest enclosing loop
  • pass: 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 with not, 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.

Quiz Team

Related Documents

More Like This

Use Quizgecko on...
Browser
Browser