Learn Python · lesson 12 of 60 · about 8 minutes
Project: Can I Buy It?
Turn a family rule into code: the assistant asks whether someone at home will help, then decides whether Sam can buy the bike.
What you'll learn
- Turn rules into conditions
- Test a rule at its edges
- Turn a yes or no answer into True or False
Sam's rule
Sam's family has a rule for big buys:
1. You need enough saved to pay for it
2. It should leave at least 5 spare, unless someone at home will help
Each part becomes a comparison, and the words between them become and and or.
The rule, step by step
saved = 122
price = 120
home_help = False
enough = saved >= price
spare = saved - price >= 5
print(enough and (spare or home_help))Output
FalseA yes from input()
input() gives text, so a typed yes isn't True yet. Compare it: answer.strip().lower() == "yes" is True for yes, Yes and YES with spaces around it, and False for anything else.
Turning an answer into a boolean
home_help = input("Help from home? ").strip().lower() == "yes"
print(home_help)Output
Help from home? TrueTest the edges
Rules break at their edges. Saved exactly 120: is that enough? Exactly 5 spare: is that allowed? Test those first, then pick >= or > to match the words. At least 5 includes 5 itself, so it's >= 5.
Tip
Names like enough and spare make a long rule easy to read and to test, one part at a time.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.