DEV Community

Alireza Razinejad
Alireza Razinejad

Posted on

Brief detail about conditional statements, loops, and control flow in Python

Here's a brief detail about conditional statements, loops, and control flow in Python, along with three challenges to solidify your understanding

Conditional Statements (if/else)

Conditional statements allow you to perform different actions based on different conditions. In Python, the if statement is used to execute a block of code if a certain condition is true. The else statement can be used to execute a different block of code if the condition is false.

Challenge 1: Write a Python program that takes a user's age as input and prints whether they are eligible to vote or not.

Challenge 2: Create a program that determines whether a given year is a leap year or not. A leap year is divisible by 4 but not divisible by 100, except if it is also divisible by 400.

Loops (for/while)

Loops allow you to repeatedly execute a block of code until a certain condition is met. In Python, the for loop is used to iterate over a sequence of elements, while the while loop is used to repeat a block of code as long as a certain condition is true.

Challenge 3: Write a Python program that prints the sum of all numbers from 1 to 100 using a loop.

Control Flow

Control flow statements allow you to alter the execution path of your program. The break statement is used to exit a loop prematurely, while the continue statement is used to skip the current iteration and move to the next one.

Challenge 4: Create a program that asks the user to enter a series of numbers. Implement a loop that keeps asking for numbers until the user enters a negative number. Print the sum of all the positive numbers entered.

Challenge 5: Write a program that generates a random number between 1 and 10. Allow the user to guess the number, and provide feedback if their guess is too high or too low. Repeat the guessing process until the user guesses the correct number.

These challenges will help you practice and reinforce your understanding of conditional statements, loops, and control flow in Python. Feel free to explore additional concepts and experiment with different scenarios to further enhance your skills. Happy coding!

Top comments (0)