These examples demonstrate some alternate ways to program decisions in Python.
Example: Alternate ways to program decisions in Python
a = 3
b = 2
x = 10
y = 20
result = x if a > b else y
print(result)
Output:
10
Example: Alternate ways to program decisions in Python
x = 10
print(0 if x == 9 else 1)
Output:
1
Example: Alternate ways to program decisions in Python
age = int(input("Enter your age: "))
print('You are not able to vote yet.' if age < 18 else 'You can vote.')
Output:
Enter your age: 22 {user input)
You can vote.
Example: An If statement in a function return
def calcBonus(units):
return .10 if units > 500 else .025
units = int(input("How many units did you sell this month? "))
bonus = calcBonus(units)
print("Your bonus is ", bonus*100, "%.")
Output:
How many units did you sell this month? 900 {user input}
Your bonus is 10.0 %.