Basic programming course: Lesson #4 Control structures. Part 1

in devjr-s20w4 •  last month  (edited)

Control structures. Part 1.png

Edited By Canva

Hello Steemit friends!

I am delighted to participate in this competition organized by @alejos7ven, which addresses a fundamental topic in programming: control structures, in particular conditionals. As a computer science teacher, conditionals are at the heart of many programs that I develop and teach. They allow me to create algorithms that can make decisions based on defined criteria, making programs more dynamic and interactive.

In this lesson, I will further explore the use of conditionals in Python, explaining not only their syntax but also sharing practical examples that I encounter in my daily life. This approach allows me not only to strengthen my programming skills but also to effectively transmit them to my students.

Describe your understanding of conditional structures and mention 2 situations of everyday life where you could apply this concept.

Conditional structures are a cornerstone of programming, and they allow me to add flexibility and intelligence to the programs I create. My goal with conditional structures is to be able to execute certain instructions only if specific conditions are met. This allows me to handle different situations in an automated way and to introduce decision-making elements into my codes.

When I write a program, I often want it to be able to react to different values ​​or events. This could be user input, calculation results, or system states. Conditional structures allow me to handle these variations. I use them to ensure that blocks of code are executed only if certain conditions are met.

Components of conditional structures:

  1. if :
    I use the if keyword to specify a condition that will be checked. If this condition is true, then the code inside the if block will be executed. Otherwise, the program will move on to the next statement.

  2. elif (else if):
    After an if, if I want to add more conditions to check, I use elif. This statement will only be checked if the first if is false. This allows me to test multiple possibilities before moving on to a default action.

  3. else:
    If none of the previous conditions are met, I can use else to set a default behavior. The code in the else block will be executed when none of the other conditions are true.

These three components form the basis of decision-making in programming, and they are crucial to me when I want to make my programs more intelligent and adaptive.

Scenario 1: Daily Life: Monthly Budget Management

Let’s take an example to illustrate how I might use these structures. Let’s say I’m writing an app that helps me manage my monthly budget. I want the app to tell me whether I can afford to make a purchase based on my bank balance and my expected expenses. Here’s how I might use conditional structures:

if1.PNG

Explanation:

  1. First condition (if):
    I evaluate whether my bank balance is sufficient to cover both the cost of the purchase and my expected monthly expenses. If so, it means that I am financially comfortable making this purchase without risk.

  2. Second condition (elif):
    If the first condition is not met, I check if my balance is at least enough to cover the cost of the purchase alone. This means that I could make the purchase, but I would have to review my other planned expenses to avoid running out of money.

  3. Else (else):
    If neither of the two previous conditions is met, it means that my balance is insufficient to make the purchase. I then receive an alert telling me that I should wait before making this purchase.

Daily Life Scenario2: Heating Management at Home

I live in a house where I have installed a home automation system. I use conditional structures to automate the heating depending on the outside temperature. This allows me to maintain optimal comfort while saving energy. Here is how I could implement this:

image.png

Detailed explanation:

  1. First condition (if):
    If the outside temperature is below 18°C, I decide to activate the heating to maintain a comfortable temperature inside.

  2. Second condition (elif) :
    If the temperature is between 18°C ​​and 22°C, I consider that the temperature is ideal and that heating is not necessary. So I keep the heating off.

  3. Otherwise (else) :
    If the temperature is above 22°C, it is warm enough, and I make sure not to waste energy unnecessarily by leaving the heating off.

Create a program that tells the user "Welcome to the room What do you want to do?", if the user writes 1 then it shows a message that says "You have turned on the light" if the user writes 2 then it shows a message that says "you have left the room". Use conditionals.

image.png

Detailed Explanation:

1. Displaying a Welcome Message and Options:

When the program starts, I want to greet the user and present them with two options. This helps guide the user on what actions they can perform within this "room."

  • The program uses the print() function to display:
    Welcome to the room! What do you want to do?
    1: Turn on the light
    2: Leave the room
    
    Here, I’m giving clear instructions on how the user can interact with the program.

2. Gathering User Input:

Next, I ask the user for input. I want them to type either 1 (to turn on the light) or 2 (to leave the room). This input is captured using the input() function:

user_choice = input("Enter 1 or 2: ")
  • The input() function reads the user's response as a string. The input could be "1", "2", or potentially something else. This value is stored in the user_choice variable for further evaluation.

3. Conditional Logic:

Now, I need to decide what action the program should take based on the user's input. For this, I use conditional statements (if, elif, else). These statements allow the program to make decisions based on the value of user_choice.

  • Case 1 (if):
    If the user enters "1", it means they want to turn on the light, so I use:

    if user_choice == "1":
        print("You have turned on the light.")
    

    This if condition checks if the user's input is equal to "1". If true, the program executes the code inside the block, which is printing the message, "You have turned on the light."

  • Case 2 (elif):
    If the user enters "2", they want to leave the room. For this scenario, I use the elif condition:

    elif user_choice == "2":
        print("You have left the room.")
    

    This checks if the user_choice is "2". If true, it prints the message "You have left the room."

  • Default Case (else):
    Finally, if the user enters anything other than "1" or "2", I handle it with an else statement:

    else:
        print("Invalid option, please enter 1 or 2.")
    

    This handles any invalid input. For example, if the user types "3", "kouba01", or leaves the input empty, the program responds by saying that the input is invalid.

Flow of Execution:

Here is the step-by-step execution process for the program:

  1. The program displays the welcome message and options.
  2. The user enters a choice.
  3. The program checks the value of the input:
    • If it’s "1", the light is turned on.
    • If it’s "2", the user leaves the room.
    • If it’s anything else, an error message appears telling the user that the option is invalid.

This flow ensures that the user receives immediate feedback based on their actions.

Example of Program Output:

Here are a few different scenarios to demonstrate how the program reacts based on user input:

  1. User enters "1":

    Welcome to the room! What do you want to do?
    1: Turn on the light
    2: Leave the room
    Enter 1 or 2: 1
    You have turned on the light.
    
  2. User enters "2":

    Welcome to the room! What do you want to do?
    1: Turn on the light
    2: Leave the room
    Enter 1 or 2: 2
    You have left the room.
    
  3. User enters something invalid (e.g., "kouba"):

    Welcome to the room! What do you want to do?
    1: Turn on the light
    2: Leave the room
    Enter 1 or 2: kouba
    Invalid option, please enter 1 or 2.
    
    

Create a program that asks the user for 4 different ratings, calculate the average and if it is greater than 70 it shows a message saying that the section passed, if not, it shows a message saying that the section can improve.

image.png

Explanation:

1. Gathering Ratings:

The program prompts the user to enter four different ratings. These ratings are collected using the input() function and converted to floats using float() to handle decimal numbers.

2. Calculating the Average:

The average of the four ratings is calculated by summing the ratings and dividing by 4.

average_rating = (rating1 + rating2 + rating3 + rating4) / 4

3. Conditional Check:

A conditional check (if) is used to determine whether the average rating is greater than 70. If it is, the program displays a message that the section passed; otherwise, it suggests that the section can improve.

if average_rating > 70:
    print("The section passed.")
else:
    print("The section can improve.")

4. Displaying the Average:

The program also displays the calculated average using formatted output with two decimal places ({:.2f}).

Example of Program Output:

  1. Example 1: Section Passed
Enter the first rating: 85
Enter the second rating: 90
Enter the third rating: 75
Enter the fourth rating: 80
Average Rating: 82.50
The section passed.
  1. Example 2: Section Can Improve
Enter the first rating: 50
Enter the second rating: 65
Enter the third rating: 70
Enter the fourth rating: 55
Average Rating: 60.00
The section can improve.

Thank you very much for reading, it's time to invite my friends @josepha, @lhorgic, @mohammadfaisal to participate in this contest.

Best Regards,
@kouba01

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Hi, @kouba01,

Your post has been manually curated!

Dear Sir, I am inspired by your program and coding. I want to be a programmer like you. I have already started studying programming languages ​​along with the job. I am still far behind in learning programming languages. I wish I can be like you one day. Good luck to you.

Screenshot_2024-10-01-19-48-12-73_40deb401b9ffe8e1df2f1cc5ba480b12.jpg
My learning course schedule

Upvoted. Thank You for sending some of your rewards to @null. It will make Steem stronger.

You have done well, which I have also learnt from you. Thanks for the invite and good luck to you.

Loading...

Your post has been rewarded by the Seven Team.

Support partner witnesses

@seven.wit
@cotina
@xpilar.witness

We are the hope!

Hi prof, you have practiced coding very, very well, I think this is no doubt that you are indeed a smart programmer. Always success, I need to learn a lot from you prof.