Bytes

Control Statements in Python

Module - 3 Loops and Iterations in Python
Control Statements in Python

Control statements direct the flow of a Python program's execution. They introduce logic, decision-making, and looping. Key control statements in Python include if/else, for/while, break/continue, and pass. Let's get into our lesson to understand these concepts clearly.

What are Control Statements in Python?

Control Statements in Python

Control Statements in Python

Flow control in Python is the process of controlling and directing the progression of program execution by utilizing conditional statements , iterative loops ūüĒĀ, and reusable functions ūüĒĄ. It helps govern a program's logic and coherence, permitting code to execute only when certain predefined conditions have been satisfied. In particular, flow control allows a program to make decisions :thinking: and perform repetitive tasks ūüĒĀ.

Conditional statements like if-else tests enable a program to evaluate expressions and execute code only if certain conditions are true or false. Loops like for and while loops ¬†enable a program to reiterate through a block of code multiple times. Functions ūüĒĄ allow a program to encapsulate and call a code block from multiple locations.

Together, conditional statements , loops , and functions  provide the mechanism to control the flow of a program and craft complex logic in a readable and maintainable fashion. Flow control is a foundational concept in programming that allows one to craft programs that can make judgments , perform recurring actions , and execute in a nonlinear manner. For these reasons, flow control is essential for creating Python programs that are versatile, capable, and resilient.

Let’s look at the control statements in python with examples for understanding:

Reservation Checking in Restaurant

  • :fork_knife_plate: :man_office_worker: A restaurant manager checks if a customer has a reservation. If the customer has a reservation, they are shown to their table.
  • ūüßź ‚Ěď If not, the restaurant checks if there are any available tables.
  • ūü™Ď ‚úÖ If there are available tables, the customer is seated.
  • ‚õĒ ‚ĚĆ If not, the customer is told that the restaurant is fully booked and cannot accommodate them.

Let's visualize this example first, then talk about it using Python code.

Reservation Checking in Restaurant

Reservation Checking in Restaurant

Importance of Control Statements in Python

We require flow control to customize his program's flow and make it operate precisely how he wants it to. Moreover, he makes use of this in daily life. For instance, he determines if he can safely cross a road before we do so.ūüö¶If not, we wait until the situation is safe before moving further. Just deciding which sentence should run before or after another, how the code should behave in specific circumstances, etc., is all he is doing. With Python, we have elegant, clear techniques to create flow control. ūüíĽ Let's talk about them.

Types of Control Statements in Python

In Python, loops and conditional statements control code execution on a specific condition. There are two types of control statements in python, as discussed below:

Conditional Control Statements in Python

"Conditional" refers to something dependent on a specific condition or circumstance. In programming, a conditional statement executes different codes based on whether a particular condition is true or false. ūüí°Three conditional statements will help him. Let's help him understand each one with an example.

if condition

if condition

if condition

if age >= 18:
    print("You are eligible to vote")

This code is an example of an if statement. It checks if the value stored in the variable "age" is greater than or equal to 18. If the statement is true, the code will print, "You are eligible to vote.‚ÄĚ

if else condition

x = 5
if x > 10:
    print("x is greater than 10")
else:
    print("x is not greater than 10")

In this example, x is set to 5, using an if-else condition to test whether x is greater than 10. If x is greater than 10, it will print "x is greater than 10"; otherwise, it will print "x is not greater than 10".

if elif else condition

x = 5
if x > 10:
    print("x is greater than 10")
elif x<20:
    print("x is greater than 20")
else:
    print("x is not greater than 10 and 20")

In this example, x is set to 5, and an if-else condition is used to test whether x is greater than 10. If x is greater than 10, it will print "x is greater than 10", else it will try if x is greater than 20; if x is greater than 20, it will print "x is greater than 20", otherwise it will print "x is not greater than 10 and 20".

Loop Control Statements in Python

Loop control statements in python are control structures in programming that allow a piece of code to be executed repeatedly, either a specific number of times or until a particular condition is met ‚Źį.

For Loop

for i in range(11):
    print(i)

This program uses a for loop to iterate through numbers from 0 to 10. For each iteration, the value of i is printed. The for loop will continue until it reaches 11, which is not included in the range.

While Loop

num = 1
while num <= 10:
    print(num)
    num = num + 1

This program prints the numbers from 1 to 10 using a while loop. The loop starts at 1 and continues until it reaches 10. The loop terminates when the value of num is greater than 10.

ūüí° Did You know?

In Python, you can check multiple conditions simultaneously using multiple comparisons. This is different from other programming languages, where you cannot randomly chain comparison operators and instead follow a particular order of operators.

Conclusion

This lesson provides an overview of control statements in Python, including their importance and types. Python control statements allow for logic, decision-making, and looping in a program. Conditional statements like if/else and loops like for/while are discussed, along with their syntax and examples 

Key Takeaways

  1. If a specified condition evaluates True, the if statement allows you to execute a code block. You can use if statements to execute code only when certain conditions are met. :woman_tipping_hand:
  2. The for statement allows you to iterate over a sequence, like a list or string, and execute a block of code once for each element in the sequence; for statements are helpful when you want to repeat an action a specific number of times. ūüĒĀ
  3. The while statement allows you to execute a code block repeatedly as long as a specified condition remains True. While statements will continue looping as long as the condition evaluates to True, you need to ensure there is a way for the condition to become False to prevent an infinite loop eventually. ūüĒā
  4. To properly execute, all control statements in Python must be indented at the same level. The indentation level determines which statements are part of the control statement block. ūüďŹ
  5. In addition to the three main control statements, Python supports break and continue statements. The break statement exits a for or while loop immediately. The continue statement skips the rest of the current iteration of the loop and jumps back to the top of the loop. ‚õĒ
  6. Control statements are a fundamental part of any Python program and allow you to control the flow and logic of your code. Using the appropriate python control statements, you can create complex and robust programs in Python. ūüöÄ

Quiz

  1. What is the purpose of the 'if' statement?
    1. Execute code if a condition is true 
    2. Execute code if a condition is false 
    3. Execute code no matter what 
    4. Execute code multiple times

Answer: A) Execute code if a condition is true

  1. How do you use if statements in Python?
    1. if condition: 
    2. if: condition  
    3. if (condition): 
    4. Both A and C

Answer: D) Both A and C

  1. What is an else statement used for?
    1. Execute code if a condition is true 
    2. Execute code if a condition is false 
    3. Execute code no matter what 
    4. Execute code multiple time

Answer: B) Execute code if a condition is false

Recommended Courses
Certification in Full Stack Data Science and AI
Course
20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.
Masters in CS: Data Science and Artificial Intelligence
Course
20,000 people are doing this course
Join India's only Pay after placement Master's degree in Data Science. Get an assured job of 5 LPA and above. Accredited by ECTS and globally recognised in EU, US, Canada and 60+ countries.

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

avatar
Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter

Vikash SrivastavaCo-founder & CPTO AlmaBetter

Vikas CTO

Related Tutorials to watch

Top Articles toRead

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2023 AlmaBetter