Kurssisisältö
Introduction to Python (copy)
Introduction to Python (copy)
Range Function
The range()
function in Python is a built-in function that generates a sequence of numbers.
It is often used for iterating over a sequence with loops, particularly when you need to execute a loop a specific number of times.
This is ideal for handling tasks that involve a predictable repetition pattern, such as restocking shelves or scheduling sales in a grocery store setting.
Let's see how Alex utilizes the range()
function to manage routine tasks in our grocery store scenario efficiently:
Syntax and Arguments
The range()
function can take up to three arguments, making it versatile for various looping scenarios.
Here is the general syntax for the range
function:
python
start
: this is the first number of the sequence. It's optional, and if you don't include it, the sequence will start at0
.stop
: this is the last number of the sequence, but the sequence will stop just before this number. This argument is required.step
: this is the amount you add (or subtract) between each number in the sequence. It's optional, and if you don't include it, the sequence will increase by1
each time.
Now that you have a grasp of the range()
function syntax, let’s explore some examples to see how each argument — start
, stop
, and step
— influences the behavior of loops.
A Single Argument
When the range()
function is given a single argument, it treats this as the stop
parameter.
In our example, it generates a sequence of 7 elements starting from 0
and ending at 6
. The loop iterates over these elements, representing the first 7 days the store is open.
# Announce store opening every day for 7 days for day in range(7): print(f"Good morning! The store is now open on day {day}.")
Note
The sequence starts at
0
and ends at6
. This happens because Python often starts counting from0
, which reduces the need to adjust indexing in many situations.
Two Arguments
When two arguments are provided, like 25
(start
) and 32
(stop
), range()
generates a sequence from 25
to 31
(since the stop
value is excluded from the sequence).
# Planning seasonal sale days in the last week of December for day in range(25, 32): print(f"Seasonal sale on December {day}.")
Note
With this method of indexing, where the end element is excluded, you can easily calculate the number of elements in the sequence by subtracting the
start
argument from thestop
argument. For example,32 - 25 = 7
, meaning there are 7 elements in the sequence.
Three Arguments
By adding a third argument to range()
, you introduce a step
value, which defines the increment between each number in the sequence.
In this example, range()
takes 1
(start
), 13
(stop
), and 3
(step
), producing the numbers 1, 4, 7, 10
. These can represent the starting hours of staff shifts during a 12-hour workday.
# Schedule staff shifts every three hours throughout a 12-hour day for hour in range(1, 13, 3): print(f"Staff shift starts at hour {hour}.")
Example Application
With the range()
function, we can schedule tasks for each day of the week to make sure all sections of the store are covered.
This loop runs 7 times because range(7)
creates numbers from 0
to 6
(a total of 7 elements). In each loop, the variable day
takes a value from 0
to 6
, which is then used to access elements from both weekly_tasks
and weekdays
lists.
# List of daily tasks for a week weekly_tasks = [ "Restock Fruits", "Clean Dairy Section", "Review Meat Inventory", "Restock Vegetables", "Check Bakery Expiry Dates", "Organize Front Displays", "Prepare Weekly Sales Report" ] # List of weekdays corresponding to each task weekdays = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] # Loop through each day using the range function for day in range(7): task = weekly_tasks[day] # Access the task corresponding to the current day weekday = weekdays[day] # Access the corresponding weekday print(f"{weekday} Task: {task}")
Swipe to start coding
Use two lists — weekdays
and daily_promotions
— to print the promotion assigned to each day of the week.
- Use a
for
loop with therange()
function to iterate through the list indices. - In each iteration:
- Get the current
weekday
from theweekdays
list. - Get the corresponding promotion from
daily_promotions
using the same index.
- Get the current
- Print both values in the specified format.
Output Requirements
- For each day, print:
<weekday>: Promotion on <promotion>
Note
Ensure both lists have the same number of items to avoid indexing errors.
Ratkaisu
Kiitos palautteestasi!
Range Function
The range()
function in Python is a built-in function that generates a sequence of numbers.
It is often used for iterating over a sequence with loops, particularly when you need to execute a loop a specific number of times.
This is ideal for handling tasks that involve a predictable repetition pattern, such as restocking shelves or scheduling sales in a grocery store setting.
Let's see how Alex utilizes the range()
function to manage routine tasks in our grocery store scenario efficiently:
Syntax and Arguments
The range()
function can take up to three arguments, making it versatile for various looping scenarios.
Here is the general syntax for the range
function:
python
start
: this is the first number of the sequence. It's optional, and if you don't include it, the sequence will start at0
.stop
: this is the last number of the sequence, but the sequence will stop just before this number. This argument is required.step
: this is the amount you add (or subtract) between each number in the sequence. It's optional, and if you don't include it, the sequence will increase by1
each time.
Now that you have a grasp of the range()
function syntax, let’s explore some examples to see how each argument — start
, stop
, and step
— influences the behavior of loops.
A Single Argument
When the range()
function is given a single argument, it treats this as the stop
parameter.
In our example, it generates a sequence of 7 elements starting from 0
and ending at 6
. The loop iterates over these elements, representing the first 7 days the store is open.
# Announce store opening every day for 7 days for day in range(7): print(f"Good morning! The store is now open on day {day}.")
Note
The sequence starts at
0
and ends at6
. This happens because Python often starts counting from0
, which reduces the need to adjust indexing in many situations.
Two Arguments
When two arguments are provided, like 25
(start
) and 32
(stop
), range()
generates a sequence from 25
to 31
(since the stop
value is excluded from the sequence).
# Planning seasonal sale days in the last week of December for day in range(25, 32): print(f"Seasonal sale on December {day}.")
Note
With this method of indexing, where the end element is excluded, you can easily calculate the number of elements in the sequence by subtracting the
start
argument from thestop
argument. For example,32 - 25 = 7
, meaning there are 7 elements in the sequence.
Three Arguments
By adding a third argument to range()
, you introduce a step
value, which defines the increment between each number in the sequence.
In this example, range()
takes 1
(start
), 13
(stop
), and 3
(step
), producing the numbers 1, 4, 7, 10
. These can represent the starting hours of staff shifts during a 12-hour workday.
# Schedule staff shifts every three hours throughout a 12-hour day for hour in range(1, 13, 3): print(f"Staff shift starts at hour {hour}.")
Example Application
With the range()
function, we can schedule tasks for each day of the week to make sure all sections of the store are covered.
This loop runs 7 times because range(7)
creates numbers from 0
to 6
(a total of 7 elements). In each loop, the variable day
takes a value from 0
to 6
, which is then used to access elements from both weekly_tasks
and weekdays
lists.
# List of daily tasks for a week weekly_tasks = [ "Restock Fruits", "Clean Dairy Section", "Review Meat Inventory", "Restock Vegetables", "Check Bakery Expiry Dates", "Organize Front Displays", "Prepare Weekly Sales Report" ] # List of weekdays corresponding to each task weekdays = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] # Loop through each day using the range function for day in range(7): task = weekly_tasks[day] # Access the task corresponding to the current day weekday = weekdays[day] # Access the corresponding weekday print(f"{weekday} Task: {task}")
Swipe to start coding
Use two lists — weekdays
and daily_promotions
— to print the promotion assigned to each day of the week.
- Use a
for
loop with therange()
function to iterate through the list indices. - In each iteration:
- Get the current
weekday
from theweekdays
list. - Get the corresponding promotion from
daily_promotions
using the same index.
- Get the current
- Print both values in the specified format.
Output Requirements
- For each day, print:
<weekday>: Promotion on <promotion>
Note
Ensure both lists have the same number of items to avoid indexing errors.
Ratkaisu
Kiitos palautteestasi!