Thursday, October 19, 2023

Understanding Control Flow in Python: A Step-by-Step Guide

  • Control flow is a fundamental concept in programming, and it plays a crucial role in Python. 
  • In this blog post, we will delve into control flow in Python, providing a step-by-step, in-depth explanation with full Python examples to help you master this essential aspect of the language.

Section 1: Conditional Statements⚙️

1: The if Statement
  • The if statement is used to make decisions in Python. It allows you to execute specific code blocks based on a condition. Here's how it works:

x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
2: The elif Statement
  • The elif statement is used to handle multiple conditions. It's often used after an initial if statement to test additional conditions.

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

Section 2: Looping⚙️

1: The for Loop
  • A for loop is used to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each item in the sequence.

fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
2: The while Loop
  • A while loop continues to execute a block of code as long as a given condition is True.

count = 0 while count < 5: print("Count is", count) count += 1

Section 3: Control Flow Statements⚙️

1: The break Statement
  • The break statement is used to exit a loop prematurely. It's often used when a specific condition is met.

fruits = ["apple", "banana", "cherry"] for fruit in fruits: if fruit == "banana": break print(fruit)
2: The continue Statement
  • The continue statement is used to skip the current iteration of a loop and move to the next iteration.

fruits = ["apple", "banana", "cherry"] for fruit in fruits: if fruit == "banana": continue print(fruit)
3: The pass Statement
  • The pass statement is a placeholder used when a statement is syntactically required but doesn't need any action.

if x > 5: pass # Placeholder for future code

Exercise_1 - Rock Paper Scissors Game 

  • The user is prompted to select a choice from Rock, Paper, or Scissors. The computer generates a random choice. The user's choice and the computer's choice are displayed. 
  • The game determines the winner (user, computer, or draw) based on the rules of Rock, Paper, Scissors. In case of an invalid input, the game provides an error message.

import random # Define the three hand gestures as string variables rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' # Create a list containing the three hand gestures choices = [rock, paper, scissors] def get_user_choice(): while True: try: user_choice = int(input( "What do you choose? Type 0 for Rock, 1 for Paper, or 2 for Scissors: ")) if 0 <= user_choice <= 2: return user_choice else: print("Invalid input. Please enter 0, 1, or 2.") except ValueError: print("Invalid input. Please enter a number (0, 1, or 2).") def main(): # Get the user's choice and print the corresponding gesture user_choice = get_user_choice() print("You chose:\n", choices[user_choice]) # Generate a random choice for the computer and print the corresponding gesture comp_choice = random.randint(0, 2) print("Computer chose:\n", choices[comp_choice]) # Compare the user's choice with the computer's choice and print the result if user_choice == comp_choice: print("Match draw...") elif (user_choice == 0 and comp_choice == 2) or (user_choice == 1 and comp_choice == 0) or (user_choice == 2 and comp_choice == 1): print("You Win! 😄") else: print("You Lose ☹️") if __name__ == "__main__": main()

Exercise_2 - Treasure Quest: The Island of Secrets Game 

  • The game begins with a visual representation and a welcoming message.
  • The player is presented with a choice at a crossroad: "left" or "right." The player is prompted to enter their choice.
  • If the player chooses "left," they are faced with another choice at a lake. They can choose to "wait" for a boat or "swim" across.
  • If the player chooses to "wait," they arrive at an island with a house containing three doors (red, yellow, and blue). The player must choose a door color.
  • Depending on the door color they choose, the player receives different outcomes:
  • Choosing the "red" door leads to a room full of fire, resulting in a Game Over. Choosing the "yellow" door leads to finding the treasure and winning the game. Choosing the "blue" door leads to entering a room of beasts, resulting in a Game Over. If the player enters an invalid choice, they are prompted to enter a correct choice. If the player chooses to "swim" across the lake, they get attacked by an angry trout, leading to a Game Over.
  • If the player chooses "right" at the initial crossroad, they are informed that they chose a door that doesn't exist, resulting in a Game Over.
  • Treasure Island game  Flowchart.
import time def print_slow(text, delay=0.03): for char in text: print(char, end='', flush=True) time.sleep(delay) print() def game_over(message="Game Over."): print_slow(message) play_again = input("Do you want to play again? (yes/no): ").strip().lower() if play_again == "yes": start_game() else: print_slow("Thanks for playing!") def start_game(): print_slow(''' _ ,--.\`-. __ _,.`. \:/," `-._ ,-*" _,.-;-*`-.+"*._ ) ( ,."* ,-" / `. \. `. ," ,;" ,"\../\ \: \ ( ,"/ / \.,' : )) / \ |/ / \.,' / // ,' \_)\ ,' \.,' ( / )/ ` \._,' `" \../ \../ ~ ~\../ ~~ ~~ ~~ \../ ~~ ~ ~~ ~~ ~ ~~ __...---\../-...__ ~~~ ~~ ~~~~ ~_,--' \../ `--.__ ~~ ~~ ~~~ __,--' `" `--.__ ~~~ ~~ ,--' `--. '------......______ ______......------` ~~ ~~~ ~ ~~ ~ `````---""""" ~~ ~ ~~ ~~~~ ~~ ~~~~ ~~~~~~ ~ ~~ ~~ ~~~ ~ ~~ ~ ~~~ ~~~ ~ ~~ ~~ ~ ~~ ~~~ ~ ''') print_slow("Welcome to the Choose Your Own Adventure game! In this game, you'll be faced with different scenarios and choices that will determine your fate. You'll have to use your wit and strategy to navigate through the challenges and reach the end goal. Are you ready to embark on this adventure? Let's begin!") f_choice = input( '\nYou\'re at a crossroad. Where do you want to go? Type "left" or "right": ').strip().lower() if f_choice == "left": s_choice = input( "\nYou've come to a lake. There is an island in the middle of the lake. Type 'wait' to wait for a boat or 'swim' to swim across: ").strip().lower() if s_choice == "wait": t_choice = input( '\nYou arrive at the island unharmed. There is a house with 3 doors. One red, one yellow, and one blue. Which color do you choose?: ').strip().lower() if t_choice == "red": game_over("It's a room full of fire.") elif t_choice == "yellow": print_slow("Congratulations! You found the treasure. You Win!") elif t_choice == "blue": game_over("You enter a room of beasts.") else: print_slow("Please enter a valid choice.") start_game() elif s_choice == "swim": game_over("You get attacked by an angry trout.") else: print_slow("Please enter a valid choice.") start_game() elif f_choice == "right": game_over("You chose a path that doesn't exist.") else: print_slow("Please enter a valid choice.") start_game() start_game()

Exercise_3 - Hangman_Game

Exercise_4 - Blackjack_Game

Exercise_5 - Guess The Number Game

Conclusion

  • Understanding control flow in Python is essential for writing effective and efficient code. By mastering conditional statements, loops, and control flow statements, you'll have the tools needed to create powerful and dynamic Python programs. Practice these concepts, and you'll be well on your way to becoming a proficient Python developer.
  • In this blog post, we've covered the basics of control flow in Python with full Python examples, breaking it down into a step-by-step guide. 
  • Remember that practice is key to mastering these concepts, so be sure to write and experiment with your own code to solidify your understanding.

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS