Foundations of Python

You are currently auditing this course.
71 / 134

Conditional Execution

Conditional statements give us the ability to check conditions and change the behavior of the program accordingly. Most basic is if statement,

if x > y:
    print("Yes x is greater than y")
elif x == y:
    print("Oops! x is equal to y")
else:
    print("No x is not greater than y")

The boolean expression after the if statement is called the condition. We end the if statement with a colon character (:) and the line(s) after the if statement are indented. Same is valid for elif and else statements.

If the logical condition is true, then the indented statement gets executed. If the logical condition is false, the indented statement is skipped and the flow goes forward to elif or else statement whatever is present. It may be possible nothing is present after the if statements depending upon the requirement.

elif is an abbreviation of "else if." There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn't have to be one necessarily.

One conditional can also be nested within another.

if x == y:
    print('x and y are equal')
else:
    if x < y:
        print('x is less than y')
    else:
        print('x is greater than y')
INSTRUCTIONS

Define a function with name conditional_statements that takes 4 arguments as num1, num2, num3 and num4. Inside the function implement a conditional that checks if all the following conditions are true,

  • num1 is less than num2, greater than num3 and equal to num4
  • num3 is the smallest of all the other arguments
  • num2 is a float value
  • num1, num3 and num4 are int values

If all the above conditions are true return the sum of all numbers else return None.

You can test your function by calling it using different arguments and printing the result. See if it returns the appropriate result.


Loading comments...