Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Introduction to python

The document provides an overview of conditional statements, operators, and loops in Python, detailing how to use booleans, comparison operators, and control flow with if, elif, and else statements. It explains the syntax and application of for and while loops, including how to integrate conditional statements within these loops for more complex workflows. Additionally, it introduces keywords like 'in' and 'not' for checking conditions within data structures.

Uploaded by

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

Introduction to python

The document provides an overview of conditional statements, operators, and loops in Python, detailing how to use booleans, comparison operators, and control flow with if, elif, and else statements. It explains the syntax and application of for and while loops, including how to integrate conditional statements within these loops for more complex workflows. Additionally, it introduces keywords like 'in' and 'not' for checking conditions within data structures.

Uploaded by

tanushitcet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

1.

Conditional statements and operators


00:00 - 00:09
Python offers vast functionality to make comparisons and conditionally perform
tasks. Let's look at how we can do this!
2. Booleans
00:09 - 00:21
Remember, we can work with booleans, which have values of true or false. These
can be used to compare variables, data structures, and values!
3. Operators
00:21 - 00:46
We do this using comparison operators. These are symbols or combinations of
symbols that compare things, similar to symbols used to perform calculations. The
first comparison we can make is to check if two things are equal. We use the equals
symbol to assign a variable, so to check for equality we use two equals symbols.
4. Checking for equality
00:46 - 01:13
Here, we check if two is equal to three. We get the boolean value of False, as they
are different. Alternatively, to check for inequality, we use an exclamation mark
followed by an equals. This now returns True. A common use case for equality
comparisons is checking submitted login details against information stored in a
user's account.
5. Numeric comparison operators
01:13 - 01:33
We can use a left arrow to check if one value is less than another. To check if it is
less than or equal to another value, we also include an equals symbol. We can
change the arrow direction to ask if a value is greater or equal to another.
6. Other comparisons
01:33 - 02:02
We mentioned that we can check for equality in strings, but what about asking
Python if one string is greater than another? Surprisingly, this works! If we check
whether James is greater than Brian, Python confirms this is True. This is because
strings are evaluated in alphabetical order, so because James starts with a J, it is
greater than Brian, which starts with a B.
7. Conditional statements
02:02 - 02:39
Now we know how to conduct comparisons, we can extend this to build a workflow
that conditionally perform tasks. We can check if one value is equal to another and
perform a task if this is True or do nothing if it is False. We can use the if keyword to
perform this. Say we want to check if we've met the target for the number of units
sold on an e-commerce website. We start with the if keyword then check if units-sold
is greater than or equal to the sales-target.
8. Conditional statements
02:39 - 02:48
We finish the line with a colon, which lets Python know that we are about to provide
a task to perform if this condition is met.
9. Conditional statements
02:48 - 03:02
We put the task in a new line underneath. Notice that we indent, which is where we
use a tab or four spaces. As we exceeded our target, the print statement is
executed!
10. Indentation
03:02 - 03:12
Whenever we end a line with a colon Python expects an indentation in the following
line. If we don't do this then we will get an error.
11. Elif statement
03:12 - 03:45
We can extend our workflow to perform an action if the condition following the if
keyword is not met, such as in this case where we have a lower value for units-sold.
We do this using the elif keyword, which is short for else if. Here, if we haven't met
our target but have sold at least 320 units then we print "Target almost achieved".
We can customize further by using as many elif keywords as we like!
12. Else statement
03:45 - 04:04
If the previous two conditions are not true then nothing will be printed, meaning
there's only one option left. If there's only one other action we want to take, then we
use the else keyword, providing a print statement in an indented line underneath.
13. Comparison operators cheat sheet
04:04 - 04:11
You can use all operators and keywords shown in the video within conditional
statements to build custom workflows!
14. Let's practice!
04:11 - 04:20
If the video is complete then proceed to the exercises, else continue watching.
1. For loops
00:00 - 00:05
Let's examine a new way of working with data structures - looping!
2. Individual comparisons
00:05 - 00:20
If we have a list of prices, we can individually check if the value at each index is
more than 10 dollars, less than five dollars, or in between. This becomes tedious
when working with lots of values.
3. For loop syntax
00:20 - 01:02
We can use a for loop instead! This can be read as "For each value in a sequence,
perform this action". Notice the action is indented because the line before ends with
a colon. The sequence is known as an iterable, as it can be iterated over. It can be
any data structure with multiple elements. The value is known as an iterator. Value is
a placeholder, meaning we can give it any name. It's common to use the letter i as
shorthand for the index number of the sequence.
4. Print individual values
01:02 - 01:35
We can use a for loop to print each price separately. We do this by looping through
prices then printing the individual price. Here, price is the iterator, and prices is the
iterable. Python interprets this as "Find and print the first value in prices, repeat for
the second value, and so on". Hence, we see each price on a single line in the
output.
5. Conditional statements in for loops
01:35 - 01:44
Earlier, we individually checked if a price was more than 10 dollars. We can achieve
this using a for loop.
6. Conditional statements in for loops
01:44 - 01:53
We include an if statement inside the loop to check if the iterator, price, is more than
10.
7. Conditional statements in for loops
01:53 - 02:04
Afterwards, we indent again. Here, we provide an action to print "More than 10
dollars" if this condition is true.
8. Conditional statements in for loops
02:04 - 02:17
We then use elif, meaning that if the price is not more than 10 dollars then we check
if it is less than five. If so, we print this.
9. Conditional statements in for loops
02:17 - 02:36
We finish the for loop with an else keyword, allowing us to print the price if the
previous conditions are not met, meaning it is between five and 10 dollars. This
syntax is the same as we've seen previously, just indented inside a for loop.
10. Conditional statements in for loops
02:36 - 02:43
The output shows three items cost between five and 10 dollars!
11. Looping through strings
02:43 - 02:51
We can loop over strings too! This code will print each character in the username
string variable.
12. Looping through dictionaries
02:51 - 03:08
To loop through a dictionary's keys and values we can use the dot-items method. As
this produces tuples of keys and values, we need to provide two iterators, one for the
keys and another for the values.
13. Looping through dictionaries
03:08 - 03:19
If we just want the keys or values we can loop over the dot-keys or dot-values
methods respectively, using a single iterator.
14. Range
03:19 - 04:09
We can perform other tasks with for loops, such as updating variables. To do this,
let's introduce a new built-in function called range. It takes a starting number followed
by an end number. Note that the start is inclusive but the end number is not, so it will
be one less than what we provide. This means we should add one to this value to
get the end number we want. Range is commonly used in Python programs and is
helpful for generating or modifying values. Here, we print all values in a range from
one to five, using six as the last number in the range function.
15. Building a counter
04:09 - 04:52
Say we want to build a counter to track visits to a website. We create a variable
called visits equal to zero. We loop through the numbers in a range from one to
eleven, where each number represents a new visit. We can update the visits variable
using the plus equals syntax, which is the same as saying the variable is equal to
itself plus another value - in this case, one. Outside of the loop, we print visits and
can see it has updated to the last number in our range, ten.
16. Let's practice!
04:52 - 04:56
Let's loop into some exercises!
1. While loops
00:00 - 00:16

For loops and conditional statements such as if, elif, and else keywords, are great
tools for building a custom workflow. Let's extend our toolkit by examining another
technique - while loops.
2. If statement
00:16 - 00:34

Before we discuss while loops, let's reiterate the flow of an if statement. It checks for
a condition, which, if met, triggers an action, and then ends. If the condition is not
met, the action is skipped.
3. If statement versus while loop
00:34 - 00:52

A while loop is similar to an if statement - it executes code if the condition is True.


However, as opposed to the if statement, the while loop will continue to execute this
code over and over again as long as the condition is true.
4. While loop
00:52 - 01:31

The syntax for while loops is similar to an if statement. We start with the while
keyword followed by a condition and end the line with a colon. The next line is
indented and contains the action to perform while the condition is met. They are
useful for continuous tasks. For example, think of a racing game where a player
should accelerate while a button is pressed. Or monitoring traffic to a website and
allowing access while there is less than a predefined threshold of unique IP
addresses.

1. 1
https://unsplash.com/@joaoscferrao

5. While loop
01:31 - 02:08

Let's show an example in action. We have a variable called stock, set to 10,
representing how much stock of an item we have available in an online store. We
have another called num-purchases, equal to zero. We want to evaluate whether the
number of purchases is below the stock count. Inside the while loop, for every new
purchase, we increment the num-purchases variable by one. We then print the
remaining stock by subtracting the number of purchases from the stock.
6. Output
02:08 - 02:19

The output prints the remaining capacity during each iteration of the loop. It runs
down to zero then the while loop exits.
7. A word of caution
02:19 - 02:33

Remember, we saw that when using a while loop the code will continually execute as
long as the condition is met. What if don't increment num_purchases by one inside
the while loop?
8. Running forever
02:33 - 02:44

The loop will continue to run forever because the stock is always larger than the
number of purchases, meaning the condition is always met!
9. Breaking a loop
02:44 - 03:19

To avoid this we have a couple of options. We can use the break keyword inside the
loop, which will terminate the code. This can be helpful if we just want to do
something once or add additional code to set the number of times an action is
performed. Break can also be used in for loops. If we're already running the code
and want to terminate the Python program we can press Control and C on Windows
or Command and C on a Mac to interrupt it.
10. Conditional statements within while loops
03:19 - 03:56

Just like how we can include conditional statements in for loops, we can also do this
in while loops! Rather than printing how much stock is left, we can customize the
print statement based on the remaining stock! If stock is more than seven we print
"Plenty of stock remaining". Using elif, we print "Some stock remaining" if there are
more than 3 items left. Another elif checks whether any stock is left, printing "Low
stock!". Otherwise, we print "No stock!"
11. Conditional statements output
03:56 - 04:06

The output is now customized depending on the state at that point in the while loop,
and it still exits when stock reaches zero.
12. Let's practice!
04:06 - 04:11

While you're enjoying the course, let's try out some exercises!

1. Courses

2. Introduction to Python for Developers

Course Outline




o
o

o
o

Daily XP1720

Exercise
Exercise
Converting to a while loop
You can often achieve the same tasks using either a for or while loop.

To demonstrate this, you're going to take the for loop you built earlier in the course and modify it
to use a while loop that achieves the same results!

# Create the tickets_sold variable


tickets_sold = 0

# Create the max_capacity variable


max_capacity = 10

# Loop through a range up to and including max_capacity's value


for tickets in range(1, max_capacity + 1):

# Add one to tickets_sold in each iteration


tickets_sold += 1

print("Sold out:", tickets_sold, "tickets sold!")

 Create a while loop to run while tickets_sold is less than max_capacity.


 Inside the loop, increment tickets_sold by 1, representing an increase for each ticket
sold.
 Outside of the loop, print tickets_sold.
Lighttickets_sold = 0

max_capacity = 10

# Create a while loop


while tickets_sold < max_capacity:

# Add one to tickets_sold in each iteration


tickets_sold += 1

# Print the number of tickets sold


print("Sold out:", tickets_sold, "tickets sold!")

Conditional while loops


You've offered to help build a program that LLM Camp can use to promote an upcoming new
course launching on the 26th of the month.

Today's date is the 22nd, and they have a pre-release version available from the 24th for all
users who purchase a subscription on or before the 24th!

You'll need to build a custom workflow that provides tailored messages depending on the date.

 Create a while loop based on current_date being less than or equal to release_date.
 Increment current_date by one for each day that passes.
 Check if current_date is less than or equal to 24 and, if so, print "Purchase before the
25th for early access"
 Otherwise, check if current_date is equal to 25, printing "Coming soon!".
release_date = 26
current_date = 22

# Create a conditional loop while current_date is less than or


equal to the release_date
while current_date <= release_date:

# Increment current_date by one


current_date += 1

# Promote purchases
if current_date <=24:
print("Purchase before the 25th for early access")

# Check if the date is equal to the 25th


elif current_date ==25:
print("Coming soon!")
else:
print("Available now!")
1. Building a workflow
00:00 - 00:05

Let's round out our knowledge by examining some additional techniques to use
when building workflows.
2. Complex workflows
00:05 - 00:36

When developing software we might need to implement extensive custom logic. For
example, we may need to loop through multiple data structures, evaluate them
against multiple conditions, update variables based on these checks, and display
various outputs depending on the results. We have the majority of the knowledge
required for this complex workflow, given our ability to use for and while loops,
boolean operators, and if, elif, and else statements.
3. The "in" keyword
00:36 - 01:09

Let's examine some more conditional keywords and techniques to help us design
complex workflows. First, there's in, which is used to check if a value exists in a
variable or data structure. Using our dictionary, products_dict, containing product IDs
as keys and prices as values, we can check whether the ID "OS31" is included in the
dictionary keys, printing True if so, and False if not.
4. The "not" keyword
01:09 - 01:33

Next is the not keyword, which is used to confirm that a condition has not been met.
We can combine it with the in keyword to confirm that a value is not in a data
structure! Here, we check if "OS31" is not in the dictionary's keys. If not, we print
False, otherwise, we print True.
5. The "and" keyword
01:33 - 02:01

Another important keyword is and, which allows us to check if multiple conditions are
met. Here, we check if "HT91" is a key in the dictionary and that the minimum price
of all products is more than 5 dollars. If both of these conditions are met, we print
True. If either or both of these conditions are not met, we print False.
6. The "or" keyword
02:01 - 02:42

The last keyword for us to discuss is or. This allows us to provide multiple conditions
and evaluate if at least one of them is true. Modifying our previous example, here,
we again check if "HT91" is a key in the dictionary, but now we use or to look at
whether the minimum price is less than five dollars. If one or both of these conditions
is met then we print True, otherwise, we print False. As "HT91" is a key in the
dictionary, it returns True, despite the minimum price being more than five dollars.
7. Adding/subtracting from variables
02:42 - 03:16

We can combine keywords with other techniques to build custom workflows. One
example is updating variables based on loops or conditions. Recall that we can
increment the value of a variable using a for loop, like so. We can also swap the
plus-equals for minus-equals to subtract one from the value of a variable, such as
stock. However, we might need other ways to update variables, such as a data
structure like a list.
8. Appending
03:16 - 03:51

Say we want to use a list to store information that meets certain criteria, such as the
product IDs for all products that cost at least 20 dollars. To do this, we first create an
empty list, like so. We then loop through the keys and values in our dictionary. Inside
the loop, we check if the value, or price, is 20 or more. If so, we the list.append
method to append the key, or product ID, to the list.
9. Appending
03:51 - 03:59

Outside of the loop, we print the list, which returns the four product IDs that met our
price criterion!
10. Let's practice!
03:59 - 04:04

Time for you to build your own workflow!

Appending to a list
You've been provided with a dictionary called authors, which has information about 20 of the
most popular fiction authors in the World. It contains the names of authors as keys and the
number of books they've created as values.
You're interested in finding out how many of these authors have made less than 25 books. To do
this, you will create a list called authors_below_twenty_five, filling it with author names
conditionally based on whether they have created less than 25 books.
Instructions

 Create an empty list called authors_below_twenty_five.


 Loop through key and value in the authors dictionary.
 Inside the for loop, check if the number of books is less than 25.
 If so, append the author's name to the authors_below_twenty_five list.
 # Create an empty list
 authors_below_twenty_five = []

 # Loop through the authors dictionary
 for key, value in authors.items():

 # Check for values less than 25
 if value < 25:

 # Append the author to the list
 authors_below_twenty_five.append(key)

 print(authors_below_twenty_five)
Book genre popularity
Previously, you worked with a dictionary containing information about authors and the number of
books that they have written.

In this exercise, data about the same authors has been aggregated to create a new dictionary
called genre_sales, where the keys are the genre and the values are the average sales for that
genre among the 20 most popular authors.

Your job is to find the most and least popular genres among these authors, along with their
average sales revenue.

Instructions

 Filter where average_sale is equal to the largest sales revenue (5166000000)


in genre_sales.
 Print the genre with the largest average sales.
 Next, filter where average_sale is equal to the smallest sales revenue (80000000).
 Lastly, print the genre with the smallest average sales.
 for genre, average_sale in genre_sales.items():

 # Filter for the maximum sales value
 if average_sale == 5166000000:

 # Print the genre
 print("Most popular genre: ", genre)
 print("Average sales: ", average_sale)

 # Filter for the minimum sales value
 elif average_sale == 80000000:

 # Print the genre
 print("Least popular genre: ", genre)
 print("Average sales: ", average_sale)
Working with keywords
Working with the genre_sales dictionary again, this time you will apply multiple conditions
simultaneously to find out information about book genres and average sales!
Instructions

 Loop through the keys and values of the genre_sales dictionary.


 Inside the loop, check if the genre is "Horror" or "Mystery".
 # Loop through the dictionary
 for genre, sale in genre_sales.items():

 # Check if genre is Horror or Mystery
 if genre == "Horror" or genre == "Mystery":
 print(genre, sale)
 Check if genre is "Thriller" and average sales is more than or equal to 3000000.
 # Loop through the dictionary
 for genre, sale in genre_sales.items():

 # Check if genre is Horror or Mystery
 if genre == "Horror" or genre == "Mystery":
 print(genre, sale)

 # Check if genre is Thriller and sale is at least 3 mil
lion
 elif genre =="Thriller" and sale >=3000000:
 print(genre, sale)

You might also like