0% found this document useful (0 votes)
23 views58 pages

Python Conditional Statements Guide

The document provides an introduction to Python programming, focusing on conditional statements, operators, and loops. It explains the use of boolean variables, comparison operators, and the structure of if, elif, and else statements, along with practical examples. Additionally, it covers for loops, while loops, and the use of keywords like 'in', 'not', 'and', and 'or' for building complex workflows.

Uploaded by

Khushwant Arya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views58 pages

Python Conditional Statements Guide

The document provides an introduction to Python programming, focusing on conditional statements, operators, and loops. It explains the use of boolean variables, comparison operators, and the structure of if, elif, and else statements, along with practical examples. Additionally, it covers for loops, while loops, and the use of keywords like 'in', 'not', 'and', and 'or' for building complex workflows.

Uploaded by

Khushwant Arya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Conditional

statements and
operators
INTRODUCTION TO PYTHON FOR DEVELOPERS

Jasmin Ludolf
Senior Data Science Content Developer
Booleans
# Boolean variable
the_truth = True
print(the_truth)

True

Used to make comparisons

INTRODUCTION TO PYTHON FOR DEVELOPERS


Operators
Comparison operators
Symbols or combinations of symbols

Used to compare values


Check if two things are equal
==

INTRODUCTION TO PYTHON FOR DEVELOPERS


Checking for equality
# Compare if 2 is equal to 3
2 == 3

False

# Check that 2 is not equal to 3


2 != 3

True

Common use-case: checking login details

INTRODUCTION TO PYTHON FOR DEVELOPERS


Numeric comparison operators
# Is 5 less than 7? # Is 5 greater than 7?
5 < 7 5 > 7

True False

# Is 5 less than or equal to 7? # Is 5 greater or equal to 7?


5 <= 7 5 >= 7

True False

INTRODUCTION TO PYTHON FOR DEVELOPERS


Other comparisons
# Is James greater than Brian
"James" > "Brian"

True

Strings are evaluated in alphabetical order

INTRODUCTION TO PYTHON FOR DEVELOPERS


Conditional statements
if condition is met, then perform action, otherwise skip

# Check pasta quantities


required_quantity = 500
pasta_quantity = 200

# Compare pasta quantities


if pasta_quantity >= required_quantity

INTRODUCTION TO PYTHON FOR DEVELOPERS


Conditional statements
if condition is met, then perform action, otherwise skip

# Check pasta quantities


required_quantity = 500
pasta_quantity = 200

# Compare pasta quantities


if pasta_quantity >= required_quantity:

INTRODUCTION TO PYTHON FOR DEVELOPERS


Conditional statements
if condition is met, then perform action, otherwise skip

# Check pasta quantities


required_quantity = 500
pasta_quantity = 200

# Compare pasta quantities


if pasta_quantity >= required_quantity:
print("You have enough pasta!")

INTRODUCTION TO PYTHON FOR DEVELOPERS


Indentation
# Check pasta quantities
required_quantity = 500
pasta_quantity = 200

# Compare pasta quantities


if pasta_quantity >= required_quantity:
print("You have enough pasta!") # This line is not indented

print("You have enough pasta!")


^
IndentationError: expected an indented block

INTRODUCTION TO PYTHON FOR DEVELOPERS


Elif statement
# Check pasta quantities
required_quantity = 500
pasta_quantity = 200
# Compare pasta quantities
if pasta_quantity >= required_quantity:
print("You have enough pasta!")
elif pasta_quantity >= 300:
print("Nearly enough pasta. Try a smaller portion.")

Can use as many elif keywords as we like!

INTRODUCTION TO PYTHON FOR DEVELOPERS


Else statement
# Check pasta quantities
required_quantity = 500
pasta_quantity = 200
# Compare pasta quantities
if pasta_quantity >= required_quantity:
print("You have enough pasta!")
elif pasta_quantity >= 300:
print("Nearly enough pasta. Try a smaller portion.")
# Otherwise...
else:
print("Not enough pasta.")

Not enough pasta.

INTRODUCTION TO PYTHON FOR DEVELOPERS


Comparison operators cheat sheet
Operator Function Keyword Function Use
== Equal to First in the
if If condition is met workflow
!= Not equal to
elif Else check if After if
condition is met
> More than
else
Else perform this After elif
>= More than or equal to action

< Less than

<= Less than or equal to

INTRODUCTION TO PYTHON FOR DEVELOPERS


Let's practice!
INTRODUCTION TO PYTHON FOR DEVELOPERS
For loops
INTRODUCTION TO PYTHON FOR DEVELOPERS

Jasmin Ludolf
Senior Data Science Content Developer
Individual comparisons
# Ingredient quantities
quantities = [500, 400, 15, 20, 30, 5]

# Validate values
quantities[0] < 10

False

quantities[1] < 10

False

INTRODUCTION TO PYTHON FOR DEVELOPERS


For loop syntax
for value in sequence:
action

for each value in sequence , perform this action


action is indented because of the colon in the previous line

sequence = iterable e.g., list, dictionary, etc.

value = iterator, i.e., the index


Placeholder (can give it any name), i is common

INTRODUCTION TO PYTHON FOR DEVELOPERS


Print individual values
# Ingredients list
ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]

# Loop through and print each ingredient


for ingredient in ingredients:
print(ingredient)

pasta
tomatoes
garlic
basil
olive oil
salt

INTRODUCTION TO PYTHON FOR DEVELOPERS


Conditional statements in for loops
quantities = [1000, 800, 40, 30, 30, 15]

for qty in quantities:

INTRODUCTION TO PYTHON FOR DEVELOPERS


Conditional statements in for loops
quantities = [1000, 800, 40, 30, 30, 15]

for qty in quantities:


# Check if quantity is more than 500
if qty > 500:
print("Plenty in stock")
elif qty >= 100:
print("Enough for a small portion")
else:
print("Nearly out!")

INTRODUCTION TO PYTHON FOR DEVELOPERS


Conditional statements in for loops
Plenty in stock
Enough for small
Nearly out!
Nearly out!
Nearly out!

INTRODUCTION TO PYTHON FOR DEVELOPERS


Looping through strings
ingredient_name = "pasta"
# Loop through each character
for letter in ingredient_name:
print(letter)

p
a
s
t
a

Useful for validating text, checking for special characters

INTRODUCTION TO PYTHON FOR DEVELOPERS


Looping through dictionaries
ingredients = {"pasta": 500, "tomatoes": 400, "garlic": 30}

# Loop through keys and values


for item, qty in [Link]():
print(item, ":", qty, "grams")

pasta : 500 grams


tomatoes : 400 grams
garlic : 30 grams

item = key (ingredient name)

qty = value (quantity)

INTRODUCTION TO PYTHON FOR DEVELOPERS


Looping through dictionaries
ingredients = {"pasta": 500, "tomatoes": 400, "garlic": 30}
factor = 2
# Calculate scaled quantities
for item, qty in [Link]():
scaled_qty = qty * factor
print(item, ":", scaled_qty, "grams")

pasta : 1000 grams


tomatoes : 800 grams
garlic : 60 grams

INTRODUCTION TO PYTHON FOR DEVELOPERS


Looping through dictionaries
# Loop through keys only # Loop through values only
for item in [Link](): for qty in [Link]():
print(item) print(qty, "grams")

pasta 500 grams


tomatoes 400 grams
garlic 30 grams

INTRODUCTION TO PYTHON FOR DEVELOPERS


Range
range(start, end + 1)

start = starting number

end = ending number

Used to generate or modify values

for i in range(1, 6):


print(i)

1
2
3
4
5

INTRODUCTION TO PYTHON FOR DEVELOPERS


Let's practice!
INTRODUCTION TO PYTHON FOR DEVELOPERS
While loops
INTRODUCTION TO PYTHON FOR DEVELOPERS

Jasmin Ludolf
Senior Data Science Content Developer
If statement
If statement

INTRODUCTION TO PYTHON FOR DEVELOPERS


If statement versus while loop
If statement While loop

INTRODUCTION TO PYTHON FOR DEVELOPERS


While loop
while condition:
action

Any continuous task


Accelerate while a button is pressed

1 [Link]

INTRODUCTION TO PYTHON FOR DEVELOPERS


While loop
ingredients_to_add = 5
items_added = 0

# Keep adding while we have items left


while items_added < ingredients_to_add:
items_added += 1
remaining = ingredients_to_add - items_added
print(remaining, "ingredients left to add")

INTRODUCTION TO PYTHON FOR DEVELOPERS


Output
4 ingredients left to add
3 ingredients left to add
2 ingredients left to add
1 ingredients left to add
0 ingredients left to add

Loop exits when items_added equals ingredients_to_add

INTRODUCTION TO PYTHON FOR DEVELOPERS


A word of caution
while runs continually while the condition is met

ingredients_to_add = 5
items_added = 0

while items_added < ingredients_to_add:


remaining = ingredients_to_add - items_added
print(remaining, "ingredients left")

INTRODUCTION TO PYTHON FOR DEVELOPERS


Running forever
ingredients_to_add = 5
items_added = 0

# INFINITE LOOP - never exits!


while items_added < ingredients_to_add:
remaining = ingredients_to_add - items_added
print(remaining, "ingredients left")
# Forgot to increment items_added!

Condition never becomes False


Loop runs forever, program freezes
Common developer mistake

INTRODUCTION TO PYTHON FOR DEVELOPERS


Breaking a loop
while items_added < ingredients_to_add:
remaining = ingredients_to_add - items_added
print(remaining, "ingredients left")

# Terminate the loop


break

break can also be used in for loops

If the code is already running: Control + C / Command + C

INTRODUCTION TO PYTHON FOR DEVELOPERS


Conditional statements within while loops
ingredients_to_add = 5
items_added = 0

while items_added < ingredients_to_add:


items_added += 1
remaining = ingredients_to_add - items_added
if remaining > 3:
print("Several ingredients remaining")
elif remaining >= 1:
print("Almost done!")
else:
print("Shopping list complete!")

INTRODUCTION TO PYTHON FOR DEVELOPERS


Conditional statements output
Several ingredients remaining
Several ingredients remaining
Almost done!
Almost done!
Shopping list complete!

INTRODUCTION TO PYTHON FOR DEVELOPERS


Let's practice!
INTRODUCTION TO PYTHON FOR DEVELOPERS
Building a workflow
INTRODUCTION TO PYTHON FOR DEVELOPERS

Jasmin Ludolf
Senior Data Science Content Developer
Complex workflows
Loops through data structures
for , while

Evaluate multiple conditions


if , elif , else , > , >= , < , <= , == , !=

Update variables
+=

Return outputs
print()

INTRODUCTION TO PYTHON FOR DEVELOPERS


The "in" keyword
in = check if a value is in a variable/data structure

recipe = {"pasta": 500, "tomatoes": 400,


"garlic": 15, "basil": 20}

if "pasta" in [Link]():
print(True)
else:
print(False)

True

Faster than looping through every key

INTRODUCTION TO PYTHON FOR DEVELOPERS


The "not" keyword
not = check if a condition is not met

Useful for validating that something is missing

pantry_items = ["flour", "sugar", "olive oil"]


# Check if "salt" is NOT in our pantry
if "salt" not in pantry_items:
print(True)
else:
print(False)

True

INTRODUCTION TO PYTHON FOR DEVELOPERS


The "and" keyword
and = check if multiple conditions are met

Use when multiple requirements must be met

pasta_quantity = 600
olive_oil_quantity = 30
# Check if we have enough of BOTH ingredients
if pasta_quantity >= 500 and olive_oil_quantity >= 30:
print(True)
else:
print(False)

True

INTRODUCTION TO PYTHON FOR DEVELOPERS


The "or" keyword
or = check if one (or more) condition is met

Use when any of several options are acceptable

pasta_quantity = 600
olive_oil_quantity = 30
# Check if we have enough of EITHER ingredient
if pasta_quantity >= 500 or olive_oil_quantity >= 30:
print(True)
else:
print(False)

True

INTRODUCTION TO PYTHON FOR DEVELOPERS


Adding/subtracting from variables
Combine keywords with other techniques to build complex workflows

ingredients_checked = 0
for ingredient in recipe_list:
# ingredients_checked = ingredients_checked + 1
ingredients_checked += 1
items_to_buy = 10
for item in shopping_list:
# items_to_buy = items_to_buy - 1
items_to_buy -= 1

+= adds to a variable, -= subtracts from it

Other ways to update variables

INTRODUCTION TO PYTHON FOR DEVELOPERS


Appending
Store information that meets specific criteria in a list

# Create empty list to hold results


shopping_list = []

# Loop through recipe ingredients


for ingredient, qty_needed in [Link]():
# Check if we need to buy it
if ingredient not in pantry:
# Add to shopping list
shopping_list.append(ingredient)

INTRODUCTION TO PYTHON FOR DEVELOPERS


Appending
print(shopping_list)

['tomatoes', 'salt']

INTRODUCTION TO PYTHON FOR DEVELOPERS


Let's practice!
INTRODUCTION TO PYTHON FOR DEVELOPERS
Congratulations!
INTRODUCTION TO PYTHON FOR DEVELOPERS

Jasmin Ludolf
Senior Data Science Content Developer
Chapter 1 recap
# Define quantity
quantity = 10

# Single quotes
ingredient_name = 'pasta'

# Double quotes also work


ingredient_name = "pasta"

INTRODUCTION TO PYTHON FOR DEVELOPERS


Chapter 2 recap
ingredient_name = "Basil Leaves" # List of ingredients
ingredients = ["pasta", "tomatoes", "garlic",
# Convert to lowercase "basil", "olive oil", "salt"]
ingredient_name = ingredient_name.lower() # Get the value at the first index
ingredients[0]

# Creating a dictionary # Create a set


recipe_dict = {"pasta": 500, ingredients_set = {"pasta", "tomatoes", "pasta",
"tomatoes": 400, "basil", "garlic", "olive oil",
"garlic": 15, "salt"}
"basil": 20, # Create a tuple
"olive oil": 30, serving_sizes = (1, 2, 4, 6, 8)
"salt": 5}

INTRODUCTION TO PYTHON FOR DEVELOPERS


Chapter 3 recap
Operator Function Keyword Function Use
== Equal to First in the
if If condition is met workflow
!= Not equal to
elif Else check if After if
condition is met
> More than
else
Else perform this After elif
>= More than or equal to action

< Less than

<= Less than or equal to

INTRODUCTION TO PYTHON FOR DEVELOPERS


Chapter 3 recap
# Ingredients list
ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]

# Loop through and print each ingredient


for ingredient in ingredients:
print(ingredient)

pasta
tomatoes
garlic
basil
olive oil
salt

INTRODUCTION TO PYTHON FOR DEVELOPERS


Chapter 3 recap
ingredients_to_add = 5
items_added = 0

while items_added < ingredients_to_add:


items_added += 1
remaining = ingredients_to_add - items_added

if remaining > 3:
print("Several ingredients remaining")
elif remaining >= 1:
print("Almost done!")
else:
print("Shopping list complete!")

INTRODUCTION TO PYTHON FOR DEVELOPERS


Chapter 3 recap
Keyword Function
and Evaluate if multiple conditions are true

or Evaluate one or more conditions are true

in Evaluate if a value is in a data structure

not Evaluate if a value is not in a data structure

[Link]()

INTRODUCTION TO PYTHON FOR DEVELOPERS


Next steps
Additional built-in functions Building custom functions
zip()

enumerate()
Intermediate Python for Developers course
Packages and modules
on DataCamp
os

time

venv

pandas

requests

numpy

INTRODUCTION TO PYTHON FOR DEVELOPERS


Congratulations!
INTRODUCTION TO PYTHON FOR DEVELOPERS

You might also like