Beginners guide to Control Flow Magic: Making Your Code Branch and Loop
?????????????????????? ????????????????????
??????????????? & ?????? ???? ??????????????????????????????????? ?????????????????????? | ???????????????????? |?????? ?????????????????? ???????????? ?????????????? ???????????????? | CUSTOMER RELATIONSHIP MANAGER
Hey ! Sreelakshmi here :)
This edition is for those beginners who love to start Python .... Let's make the tough part easier ....
Imagine your code as a magical assistant, ready to follow your instructions. But sometimes, you need your assistant to make decisions or repeat tasks until something happens. That's where control flow magic comes in!
Here are two essential spells for your coding toolbox:
1. The "If" Spell and its Loyal Companion "Else"
The "if" spell lets your code check a condition, like a magical question. If the answer is "true," your code performs a specific task.
For example:
if age >= 18: # This is the condition
print("You are old enough to vote!")
else: # This is the "else" part, for when the condition is "false"
print("Sorry, you cannot vote yet!")
Here, the code checks if age is greater than or equal to 18. If it is, it prints the first message. Otherwise, the "else" part kicks in and prints the second message.
2. The "For" Loop: A Speedy Repeater
The "for" loop lets your code repeat a block of instructions a certain number of times. Imagine casting a spell on a list of ingredients, and each one gets magically chopped!
For example:
fruits = ["apple", "banana", "orange"]
for fruit in fruits: # This loop iterates over each fruit in the list
print(f"Chopping {fruit}...")
Here, the loop goes through each item in the fruits list, one by one. For each fruit, it prints a message with the fruit's name.
And Ta-da :0 !!! Here is your Bonus Spell .....
Bonus Spell: The "While" Loop - Repeating Until Satisfied
The "while" loop is similar to "for," but it keeps repeating as long as a condition remains "true." It's like casting a spell until a magical potion reaches the perfect bubbling state!
For example:
guess = 0
answer = 7 # This is the secret number to guess
while guess != answer: # The loop keeps going until the guess is correct
guess = int(input("Guess a number between 1 and 10: "))
if guess == answer:
print("Congratulations! You guessed the number!")
This code keeps asking the user to guess a number until they guess the correct answer stored in the answer variable.
Remember:
With these spells, you can control the flow of your code, making it perform amazing feats! Practice these spells, and soon you'll be a master coder, casting spells to bring your programs to life!
So ...let's continue preparing for your Python Interviews......
Best!
Sreelakshmi Ajayakumar