Python elif statement

Created By: chatGPT

In Python, the elif statement is a fundamental component used for conditional branching. It allows you to check multiple expressions for True and execute a block of code as soon as one of the expressions is found to be true. Essentially, it's a shorthand for chaining multiple if statements together.
if condition1:
    # Execute this block if condition1 is True
    do_something()
elif condition2:
    # Execute this block if condition1 is False and condition2 is True
    do_something_else()
else:
    # Execute this block if both condition1 and condition2 are False
    do_default_thing()
Here's a practical example demonstrating how to use elif: let's check a person's age and categorize them. Depending on the age, we can classify the person as a child, teenager, or adult.
age = 15

if age < 13:
    category = 'Child'
elif age < 20:
    category = 'Teenager'
else:
    category = 'Adult'

print(f'The person is categorized as: {category}')
In this example, we evaluate the variable age. If it is less than 13, the category will be set to 'Child'. If it's between 13 and 19, the category will be 'Teenager', and for anyone 20 and older, it will be 'Adult'. The program will then print the category accordingly.
age = 25

if age < 13:
    print('Child')
elif age < 20:
    print('Teenager')
else:
    print('Adult')
You can also use multiple elif statements for more precise control. Here's how you can check the temperature to determine whether it's cold, warm, or hot.
temperature = 30

if temperature < 10:
    print('Cold')
elif 10 <= temperature < 25:
    print('Warm')
elif 25 <= temperature < 35:
    print('Hot')
else:
    print('Very Hot')
Introduction And SetupVariablesData TypesIntFloatStrBoolListTupleSetDictMethodsString MethodsList MethodsDict MethodsSet MethodsControl FlowIf StatementElif StatementElse StatementFor LoopWhile LoopBreak StatementContinue StatementFunctionsDef StatementReturn StatementLambda FunctionsScopeParametersArgumentsDefault ParametersVariable Length ArgumentsOperatorsArithmetic OperatorsComparison OperatorsLogical OperatorsAssignment OperatorsIdentity OperatorsMembership OperatorsData StructuresListsTuplesSetsDictionariesCommentsSingle Line CommentsMulti Line CommentsSyntaxIndentationDocstringsEvent HandlingError HandlingTry StatementExcept StatementFinally StatementRaise StatementAssert StatementContext ManagersWith Statement