Programming Essentials Python - Basic Programming Constructs - Conditionals

Description Paragraph:

This article provides a comprehensive guide on understanding conditionals in Python. From basic “if else” statements to more complex boolean operations, readers will learn how to implement conditionals effectively in Python. The article includes code examples and hands-on tasks to solidify the concepts.

Explanation for the video:

The video linked in this article serves as a visual guide to complement the text content. It provides a practical demonstration of conditionals in Python, allowing readers to follow along with real-time examples.

Put a place holder for the video here with text so that I can replace as part of the automation

Key Concepts Explanation

Conditionals in Python

Conditionals in Python are implemented using the “if else” statements. These statements help in executing specific blocks of code based on certain conditions.

Example:

``````i = 5

if i % 2 == 0:
print("even")
else:
print("odd")
``````

Ternary Operator

The ternary operator in Python allows for concise conditional expressions with a one-liner syntax.

Example:

``````i = 5
print("even") if i % 2 == 0 else print("odd")
``````

Determine the category of the baby based on age in months.

• Print New Born or Infant till 6 months.
• Print Toddler from 7 to 18 months.
• Print Grown up from 19 to 144 months.
• Print Youth from 145 to 216 months.
``````age = int(input('Enter age in months: '))

if age <= 6:
print('New Born or Infant')
elif 7 <= age <= 18:
print('Toddler')
elif 19 <= age <= 144:
print('Grown up')
elif 145 <= age <= 216:
print('Youth')
else:
``````
Check if the number is even or divisible by 3.

``````n = int(input('Enter integer: '))

if n % 2 == 0 or n % 3 == 0:
print(f'Number {n} is even or divisible by 3')
``````
Check if the number is even and divisible by 3.

``````n = int(input('Enter integer: '))

if n % 2 == 0 and n % 3 == 0:
print(f'Number {n} is even and divisible by 3')
elif n % 3 == 0:
print(f'Number {n} is divisible by 3 but not even')
elif n % 2 == 0:
print(f'Number {n} is even but not divisible by 3')
``````

Conclusion

In conclusion, understanding conditionals in Python is crucial for controlling the flow of your programs based on specific conditions. By mastering conditionals, you can write more dynamic and flexible code. Practice the hands-on tasks provided in this article to reinforce your understanding of Python conditionals and start building more advanced programs. Join the community to engage with fellow learners and further enhance your Python skills.

Watch the video tutorial here