Conditional structures are fundamental to programming, enabling your code to make decisions and execute different paths based on certain conditions. In Python, conditional statements help you control the flow of your programs, making them more dynamic and responsive to varying inputs. This article provides practical exercises to help you master conditional structures in Python, progressing from beginner to advanced levels. ejercicios condicionales python
Beginner Level
1. Basic If Statement
Objective: Understand the basic syntax of the if
statement.
Exercise:
Write a Python program that checks if a given number is positive. If it is, print “The number is positive.”
number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
Explanation: This exercise introduces the if
statement, which executes the code block only if the condition is true.
2. If-Else Statement
Objective: Learn how to handle both true and false conditions.
Exercise:
Modify the previous program to also print “The number is not positive” if the number is zero or negative.
number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
else:
print("The number is not positive.")
Explanation: The else
statement provides an alternative path when the if
condition is false.
3. If-Elif-Else Statement
Objective: Work with multiple conditions.
Exercise:
Write a program that categorizes a number as positive, negative, or zero.
number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
Explanation: The elif
(else if) statement allows you to check multiple conditions in sequence.
Intermediate Level
4. Nested Conditional Statements
Objective: Understand how to use if
statements within other if
statements.
Exercise:
Write a program that checks if a number is positive and then determines if it is even or odd.
number = int(input("Enter a number: "))
if number > 0:
if number % 2 == 0:
print("The number is positive and even.")
else:
print("The number is positive and odd.")
else:
print("The number is not positive.")
Explanation: Nested if
statements help manage more complex decision-making scenarios.
5. Logical Operators
Objective: Use logical operators to combine multiple conditions.
Exercise:
Create a program that checks if a number is between 10 and 20 (inclusive).
number = int(input("Enter a number: "))
if 10 <= number <= 20:
print("The number is between 10 and 20.")
else:
print("The number is outside the range 10 to 20.")
Explanation: Logical operators like and
, or
, and not
can be used to combine conditions for more nuanced checks.
6. Conditional Expressions
Objective: Use conditional expressions for concise conditionals.
Exercise:
Write a program that prints “Even” if a number is even and “Odd” if it is odd using a conditional expression.
number = int(input("Enter a number: "))
print("Even" if number % 2 == 0 else "Odd")
Explanation: Conditional expressions allow for a compact way to perform conditional checks and assign values.
Advanced Level
7. Complex Conditional Logic
Objective: Handle complex conditional logic with nested conditions and logical operators.
Exercise:
Write a program that determines if a person qualifies for a discount based on age and membership status.
age = int(input("Enter your age: "))
membership = input("Are you a member (yes/no)? ").strip().lower()
if age < 18 or age > 65:
print("You qualify for a discount due to age.")
elif membership == 'yes':
print("You qualify for a discount due to membership.")
else:
print("You do not qualify for a discount.")
Explanation: Combining multiple conditions with both logical operators and nested conditions allows for more complex decision-making.
8. Using Dictionaries for Conditional Logic
Objective: Utilize dictionaries to simplify complex conditional logic.
Exercise:
Create a program that uses a dictionary to determine the price of a ticket based on the type of ticket.
ticket_type = input("Enter ticket type (regular, student, senior): ").strip().lower()
prices = {
"regular": 20,
"student": 15,
"senior": 10
}
price = prices.get(ticket_type, None)
if price:
print(f"The price of a {ticket_type} ticket is ${price}.")
else:
print("Invalid ticket type.")
Explanation: Dictionaries can be used to map values to conditions, making code more readable and easier to manage.
9. Handling Multiple Conditions with Functions
Objective: Encapsulate conditional logic within functions for better organization.
Exercise:
Write a function that checks whether a number is prime and use it to determine the result in a main program.
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
number = int(input("Enter a number: "))
if is_prime(number):
print("The number is prime.")
else:
print("The number is not prime.")
Explanation: Functions help modularize code, making it easier to manage and test complex conditional logic.
Conclusion
Mastering conditional structures in Python is crucial for developing effective and efficient programs. By practicing these exercises, you can progressively build your skills from basic to advanced levels, enabling you to handle increasingly complex scenarios with ease. Remember, the key to proficiency is consistent practice and applying these concepts to real-world problems. Happy coding!