If Statement
Share: Facebook |
Twitter |
Whatsapp |
Linkedin Visits: 629
Python if Statement
#ScriptsKart
# if statement to execute a block of code based on a specified condition
# colon (:) that follows the condition is very important. If you forget it,
# you’ll get a syntax error
age = input('Enter your age:')
if int(age) >= 18:
print("You're eligible to vote.")
else:
print("You're not eligible to vote.")
# If you want to check multiple conditions and perform an action accordingly,
# you can use the if...elif...else statement. The elif stands for else if
age = input('Enter your age:')
# convert the string to int
your_age = int(age)
# determine the ticket price
if your_age < 5:
ticket_price = 5
elif your_age < 16:
ticket_price = 10
else:
ticket_price = 18
# show the ticket price
print(f"You'll pay ${ticket_price} for the ticket")
# Summary
# Use the if statement when you want to run a code block based on a condition.
# Use the if...else statement when you want to run another code block if the
# condition is not True.
# Use the if..elif..else statement when you want to check multiple conditions
# and run the corresponding code block that follows condition that evaluates
# to True.
#ScriptsKart