# Python Control Statements

**Python Control Statements:** Control [statements](https://www.shiksha.com/online-courses/articles/conditional-statement-in-python/) are crucial in [Python](https://www.python.org/) [programming](https://kandi.openweaver.com/?landingpage=python_all_projects&utm_source=google&utm_medium=cpc&utm_campaign=promo_kandi_ie&utm_content=kandi_ie_search&utm_term=python_devs&gclid=Cj0KCQjwgNanBhDUARIsAAeIcAt4GUL3_pDRi5_Hk4dRYWbe-U0fDIPZ4Ca7FRtRnFZx_01KSmlgaXUaAvNDEALw_wcB) for managing code flow and behavior.

They come in conditional, [loop](https://cloudacademy.com/course/exploring-while-loops-python-2930/exploring-while-loops-in-python/?utm_feeditemid=&utm_device=c&utm_term=&utm_campaign=%5BSearch%5D+DSA+-+All+Website+-+India&utm_source=google&utm_medium=ppc&hsa_acc=5890858304&hsa_cam=13996404894&hsa_grp=128133670034&hsa_ad=651406237904&hsa_src=g&hsa_tgt=dsa-19959388920&hsa_kw=&hsa_mt=&hsa_net=adwords&hsa_ver=3&gclid=Cj0KCQjwgNanBhDUARIsAAeIcAuuaZ2BzcdAoLeGrYxAgnK6souOcTAw4qSe-eGZfy8GzdrBDYNpXy4aAl5OEALw_wcB), and control flow statements, and understanding their functions helps in writing well-structured, functional code that requires a comprehension of control statements, regardless of your level of [programming](https://www.intel.com/content/www/us/en/developer/tools/oneapi/distribution-for-python.html?cid=sem&source=sa360&campid=2023_q3_iags_in_iagsoapie_iagsoapiee_awa_text-link_exact_cd_dpd-oneapi-python_3500123524_google_div_oos_non-pbm_intel&ad_group=hpc-accelerated_computing_exact&intel_term=python+programming&sa360id=43700077484369764&gclid=Cj0KCQjwgNanBhDUARIsAAeIcAtABWtlmDlQfKPXVyhYNOR-KGIdvqzQWpvH5nfe4iZh-BMI6C08rvUaAi8XEALw_wcB&gclsrc=aw.ds#gs.59spy2) proficiency in [Python](https://docs.python.org/3/tutorial/datastructures.html).

* **Conditional Statements**
    
* **Loop Statements**
    
* **Control Flow Statements**
    

## **Conditional Statements**

1. IF [Statement](https://www.javatpoint.com/python-if-else)
    
2. IF … Else [Statement](https://pythonprogramming.net/)
    
3. IF … Else IF … Else [Statement](https://pythonbasics.org/)
    
4. Nested IF
    

### \`IF\` **Statement**

*"* `if` [*statement*](https://www.searchinfotoday.com/web?q=python%20full%20course&o=1671098&rch=ch1&clid=amg-searchinfotoday&utm_source=g&utm_medium=gcpc&ct=12198&campaignid=20444085111&agid=150729435245&adid=669495247188&kwid=kwd-298298813921&gclid=Cj0KCQjwgNanBhDUARIsAAeIcAuSxrhOJEaA4awcpG022NvKvPt6JLDCXPgXb7pCBdGYX_rI4vXWdy0aArdXEALw_wcB&akid=1_20444085111_150729435245_kwd-298298813921_g&ueid=0f4a9e4f-0f6b-485f-a640-f0ff956529a8&qo=semQuery&ad=semA&ag=fw4&an=google_s) *to execute a block of code if a condition is* `True`."

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1693811914777/5a559d97-073a-4fe1-bfc0-2291602b45e6.png align="center")

* [Python](https://docs.python.org/3/library/operator.html)'s decision-making construct is the if [statement](https://www.educative.io/path/python-for-programmers?utm_campaign=system_design&utm_source=google&utm_medium=ppc&utm_content=search&utm_term=course&eid=5082902844932096&utm_term=&utm_campaign=%5BNew%5D+System+Design-Search-+Exc+US+CN+IND&utm_source=adwords&utm_medium=ppc&hsa_acc=5451446008&hsa_cam=18181328148&hsa_grp=156877867652&hsa_ad=666805872228&hsa_src=g&hsa_tgt=aud-470210443676:dsa-437115340933&hsa_kw=&hsa_mt=&hsa_net=adwords&hsa_ver=3&gclid=Cj0KCQjwgNanBhDUARIsAAeIcAuFxus8eorpEqtP_VX3opx2O8Upx4lR-eTdkQFiJFIgrazbd8V04i4aAtGLEALw_wcB), enabling programmers to evaluate conditions and execute code blocks based on them.
    
* Indentation is used to define the scope of the code block.
    
* Curly braces are not required.
    

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Unlike some other languages like C, <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.python.org/downloads/" style="pointer-events: none">Python</a> does not require curly braces for code blocks; instead, it relies on indentation to define the scope of code within an <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.w3schools.com/python/python_conditions.asp" style="pointer-events: none">if statement</a></div>
</div>

**Syntax**

```python
if condition:
    # Code to execute if the condition is true
```

### **Example 1: Checking User Authentication**

In this example, the [if statement](https://www.geeksforgeeks.org/python-if-else/) checks if the entered username and password match the expected values, allowing or denying access accordingly.

```python
# User authentication example
username = input("Enter your username: ")
password = input("Enter your password: ")

if username == "admin" and password == "password123":
    print("Authentication successful. Welcome, admin!")
else:
    print("Authentication failed. Please check your credentials.")
```

### IF … Else Statement

`"if-else` *statement is used when you want to execute one block of code if a condition is* `True` *and another block if the condition is* `False"`

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1693815341205/2d5533f5-f50e-4906-92b9-2ed91f3307f5.png align="center")

**Syntax**

```python
if condition:
    # Code to execute if the condition is true
else:
    # Code to execute if the condition is false
```

### Example 2: Checking if a year is a leap year

The [if statement](https://www.programiz.com/python-programming/if-elif-else) checks if a year is a leap year using Gregorian calendar rules, enabling [Python](https://www.python.org/about/gettingstarted/) to make decisions and control [program](https://www.python.org/about/gettingstarted/) flow, enabling dynamic and responsive [programs](https://www.w3schools.com/python/python_intro.asp).

```python
# Checking if a year is a leap year
year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(f"{year} is a leap year.")
else:
    print(f"{year} is not a leap year.")
```

### IF … Else IF … Else Statement

*"The* `if-elif-else` *statement enables you to assess several conditions sequentially and execute various code blocks depending on the first* `true` *condition detected."*

### **Example 3: Grading students based on their score**

```python
#Grading Students based on their score
score = int(input("Enter your score:"))

if score >= 90:
   grade = "A"
elif score >= 80:
   grade = "B"
elif score >= 70:
   grade = "C"
elif score >= 60:
   grade = "D"
else:
   grade = "F"
print(f"Your grade is {grade}.")
```

The '`if-elif-else`' [statement](https://www.geeksforgeeks.org/introduction-to-python/) evaluates a student's score and assigns a corresponding letter grade.

### Nested IF

*"Nested-*[*if statement*](https://www.javatpoint.com/python-if-else)*s in* [*Python*](https://www.w3schools.com/python/) *create complex decision-making structures by evaluating conditions within conditions."*

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1693814023686/042544aa-3f13-41bf-8997-3f6db2b03415.png align="center")

**Syntax**

```python
if condition1:
    # Outer if block
    if condition2:
        # Code to execute if condition1 and condition2 are true
    else:
        # Code to execute if condition1 is true, but condition2 is false
else:
    # Code to execute if condition1 is false
```

### Example 4: Checking eligibility for a loan with nested [if statement](https://www.freecodecamp.org/news/how-to-use-conditional-statements-if-else-elif-in-python/)s

```python
credit_score = int(input("Enter your credit score:"))
income = float(input("Enter your annual income:"))

if credit_score >= 700:
    if income >= 50000:
       loan_amount = 100000
    else: 
       loan_amount = 50000
else: 
    loan_amount = 0
if loan_amount >0:
     print(f"Congratulations! You are eligible for a ${loan_amount} loan.")
else: 
     print("Sorry, you are not eligiable for a loan at this time.")
```

The example uses nested [if statement](https://www.freecodecamp.org/news/python-else-if-statement-example/)s to evaluate income conditions, determine loan amounts if **credit\_score** is above or equal to **700** and if not, set **loan\_amount** to **0**.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Nested-if<a target="_blank" rel="noopener noreferrer nofollow" href="https://en.wikipedia.org/wiki/Python_(programming_language)" style="pointer-events: none"> statements</a> can be used to create more intricate decision-making logic when multiple conditions need to be checked hierarchically.</div>
</div>

### **Loop Statements**

*"*[*Loop statements*](https://www.w3schools.com/python/python_conditions.asp) *in* [*Python*](https://en.wikipedia.org/wiki/Python_(programming_language)) *are used to execute a block of code repeatedly, allowing you to automate tasks and process data efficiently."*

* [For loops](https://www.geeksforgeeks.org/python-if-else/)
    
* [While loops](https://www.tutorialsteacher.com/python/python-while-loop)
    

### For loops

When you have a known or iterable sequence (such as lists, tuples, or strings) or when you wish to iterate a certain number of times, you use [loops](https://realpython.com/python-while-loop/).

They are frequently employed for iterating through elements in a collection or sequence.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1693819084950/ab348d13-22f6-4a12-bdcc-e40113528513.png align="center")

**Syntax**

```python
for element in iterable:
    # Code to execute in each iteration
```

### Example 5

```python
# Iterating through a list of student names and printing a greeting for each
Employee = ["Sanjay", "Amit", "Shashank", "David"]
for employee in employee:
    print(f"Hello, {employee}!")
# Counting the number of vowels in a given string
text = "Hello, World!"
vowel_count = 0

for char in text:
    if char.lower() in "aeiou":
        vowel_count += 1

print(f"There are {vowel_count} vowels in the text.")

# Printing numbers from 1 to 10 using a for loop with 'range'
for number in range(1, 11):
    print(number)
# Iterating through a dictionary of student grades and displaying results
grades = {"Alice": 95, "Bob": 88, "Charlie": 78, "David": 92}

for student, score in grades.items():
    if score >= 90:
        result = "Excellent"
    elif score >= 80:
        result = "Good"
    elif score >= 70:
        result = "Average"
    else:
        result = "Needs Improvement"
    
    print(f"{student}: {score} ({result})")
```

### [While loops](https://snakify.org/en/lessons/while_loop/)

"`while` [*loops*](https://www.geeksforgeeks.org/python-while-loop/) *are particularly useful when you want to repeat a block of code an unknown number of times, such as when waiting for user input or processing data until a specific condition is met*."

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1693820977317/f527dfce-5235-40b4-bd44-a32c2829d827.png align="center")

```python
while condition:
    # Code to execute as long as the condition is true
```

### **Example 6: Simulating a password-guessing game using a** [**while loop**](https://www.programiz.com/python-programming/while-loop)

```python
# Simulating a password guessing game using a while loop
correct_password = "secret"
attempts = 3

while attempts > 0:
    guess = input("Enter the password: ")
    
    if guess == correct_password:
        print("Congratulations! You've guessed the correct password.")
        break  # Exit the loop when the password is correct
    else:
        attempts -= 1
        print(f"Incorrect password. You have {attempts} attempts left.")
    
    if attempts == 0:
        print("Out of attempts. Access denied.")
```

A [while loop](https://www.w3schools.com/python/python_while_loops.asp) simulates a password guessing game, running until the attempts variable is greater than 0. If the user enters the correct password, the [loop](https://www.freecodecamp.org/news/while-loops-in-python-while-true-loop-statement-example/) breaks and the number of attempts decreases until the user guesses the correct password or runs out.

## **Control Flow Statements**

* **Break**
    
* **Continue**
    
* **Return**
    

### **Break**

*"Using the break* [*statement*](https://www.crio.do/projects/category/python-projects/?utm_source=adwords&utm_medium=Projects&utm_campaign=Python&utm_term=coding%20projects%20in%20python&gad=1&gclid=Cj0KCQjwgNanBhDUARIsAAeIcAurwd6_0i1wxnZ69x2jekVj2NGQSG32b2XrI8vdED7Vg46-FCOzXNAaAt0IEALw_wcB)*, you can end a loop before the condition of the loop is met"*

```python
for variable in iterable:
    if condition:
        break
```

### Example 7: Searching for a specific item in a list and using 'break' to exit the loop when found

```python
# List of programming languages
programming_languages = ["Python", "Java", "JavaScript", "C++", "Ruby"]

language_to_find = "JavaScript"
found = False

for language in programming_languages:
    if language == language_to_find:
        found = True
        break  # Exit the loop when the language is found

if found:
    print(f"{language_to_find} is in the list of programming languages.")
else:
    print(f"{language_to_find} is not in the list of programming languages.")
```

### **Continue**

*"The* `continue` [*statement*](https://www.programiz.com/python-programming/assert-statement) *is useful when you want to selectively process elements in a* [*loop*](https://realpython.com/python-conditional-statements/) *and skip certain iterations based on specific conditions."*

```python
for variable in iterable:
    if condition:
        continue
    # Code here will be skipped for the current iteration if the condition is met
```

### Example 8: Skipping even numbers and displaying only odd numbers using 'continue'

```python
# Skipping even numbers and displaying only odd numbers using 'continue'
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print("Odd numbers:")
for number in numbers:
    if number % 2 == 0:
        continue  # Skip even numbers
    print(number)
```

For [loop](https://www.softwaretestinghelp.com/python/python-conditional-statements/) iterates through **1-10** numbers, skips even numbers using the continue [statement](https://www.w3schools.com/python/ref_keyword_assert.asp), and prints only odd numbers to the console.

### **Return**

*"The* `return` [*statement*](https://www.geeksforgeeks.org/python-assert-keyword/) *allows functions to provide values as output, making it a fundamental part of building reusable and modular code in* [*Python*](https://en.wikipedia.org/wiki/Python_(programming_language))*."*

```python
def my_function():
    return value
```

### Example 9: Calculates the factorial of a number

```python
# A function that calculates the factorial of a number
def factorial(n):
    if n == 0:
        return 1  # Return 1 for the base case
    else:
        result = n * factorial(n - 1)  # Recursive calculation
        return result  # Return the calculated result

# Calculate the factorial of a number
number = 5
result = factorial(number)

# Display the result
print(f"The factorial of {number} is {result}")
```

## Pass Statement

*"Use the* `pass` [*statement*](https://www.programiz.com/python-programming/pass-statement) *to indicate that we intend to implement this logic later."*

The [pass statement](https://www.geeksforgeeks.org/python-pass-statement/) is a no-op placeholder in [Python](https://www.geeksforgeeks.org/python-programming-language/), used as a temporary placeholder for a [statement](https://www.geeksforgeeks.org/python-pass-statement/) without specific action, and often used in code for future implementation.

**Syntax**

```python
def my_function():
    # TODO: Implement this function later
    pass
```

### Example 10: Salary calculation

```python
#When the pass statement is encountered, Python does nothing and continues with the next statement.
class Employee:
    def __init__(self, name, employee_id):
        self.name = name
        self.employee_id = employee_id
        self.salary = 0  # Placeholder for salary calculation

    def calculate_salary(self):
        # TODO: Implement salary calculation logic
        pass

# Let's create some employee instances:
employee1 = Employee("John Doe", 101)
employee2 = Employee("Jane Smith", 102)

#  calculate the salaries for these employees.
employee1.calculate_salary()  # implement this method later
employee2.calculate_salary() # No action is taken, but the code runs without errors
```

The example uses a [pass statement](https://www.w3schools.com/python/ref_keyword_pass.asp) to indicate future implementation of the **calculate\_salary** method for each employee, allowing for code development without syntax errors.

## Assertion Statement

"*The* [*assert statement*](https://docs.python.org/3/reference/simple_stmts.html) *is a debugging and testing tool that evaluates expressions and raises an* [***AssertionError***](https://www.scaler.com/topics/python/assert-in-python/) *exception if they're* `False`*. It checks if conditions are* `true` *or* `false`*, indicating unexpected behavior.*"

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1693827568471/d1b8e4e7-3eb5-4553-99f1-ecc5bf61520b.png align="center")

**Syntax**

```python
assert <condition>
assert <condition>,<error message>
```

### Example 11: Calculating the discounted price

```python
def calculate_discount(price, discount_percentage):
    assert 0 <= discount_percentage <= 100, "Invalid discount percentage"
    discounted_price = price - (price * (discount_percentage / 100))
    return discounted_price
#calculate_discount function
try:
    discounted_price1 = calculate_discount(100, 20)  # Valid discount percentage
    print("Discounted Price 1:", discounted_price1)
except AssertionError as e:
    print("Error:", e)

try:
    discounted_price2 = calculate_discount(100, 150)  # Invalid discount percentage
    print("Discounted Price 2:", discounted_price2)
except AssertionError as e:
    print("Error:", e)
```

The [assert statement](https://www.browserstack.com/guide/assert-in-python) checks if the discount percentage is within the valid range (**0-100**) before calculating the discounted price. If `true`, the function proceeds, but if `false`, it raises an [**AssertionError**](https://www.softwaretestinghelp.com/python-assert-statement/), indicating the discount percentage is invalid.

<details data-node-type="hn-details-summary"><summary>Summary</summary><div data-type="detailsContent">To write attractive and effective code, developers must master <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.programiz.com/python-programming" style="pointer-events: none">Python</a> control statements. These assertions make it possible to make decisions, repeat operations, and deftly navigate complicated algorithms. <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.tutorialspoint.com/python/python_while_loop.htm" style="pointer-events: none">While</a> <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.scaler.com/topics/python/while-loop-in-python/" style="pointer-events: none">loop</a> statements provide for effective data processing, conditional statements enable dynamic <a target="_blank" rel="noopener noreferrer nofollow" href="https://log2base2.com/python?utm_src=search&amp;utm_target=spyDS&amp;gclid=Cj0KCQjwgNanBhDUARIsAAeIcAtNO33B3tC2s1QHFoZgKiKmRk5m-OQ6MySkJByeGnWeI2RjO9biIhcaAjYPEALw_wcB" style="pointer-events: none">programming</a>. Code execution is made more elegant by control flow <a target="_blank" rel="noopener noreferrer nofollow" href="https://realpython.com/python-assert-statement/" style="pointer-events: none">statements</a> like "<strong>break</strong>," "<strong>continue</strong>," and "<strong>return</strong>." Being able to comprehend these lines improves <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.tutorialspoint.com/python/index.htm" style="pointer-events: none">Python</a> <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.programiz.com/python-programming" style="pointer-events: none">programming</a> abilities and enables smooth code execution.</div></details>
