How can I make this more complex?
dn
PythonList at DancesWithMice.info
Mon Nov 9 21:35:02 EST 2020
On 10/11/2020 10:04, Quentin Bock wrote:
> grade = input("Enter your grade: ")
> if grade >= 90:
> print("You got an A ")
> if grade >= 80:
> print("You got a B ")
> if grade >= 70:
> print("You got a C")
> if grade >= 60:
> print("You got a D ")
> if grade >= 50:
> print("You failed")
First: open a Python terminal (REPL) and try:
import this
(wrt the post's title, lines three and four apply. This output is known
as "The Zen of Python"!)
Did you ever run the code? Hint: it won't work, and even when 'fixed'
won't work the way you want, either. What if the grade is < 50?
If the grade is 55, which message(s) should be printed?
(compare: syntax errors, semantic errors, and errors in logic)
Others have mentioned elif. Why?
If the code looks like a "ladder" with criteria being applied to the
same variable at every step, only one will be chosen with an elif
structure, but >=1 choice will be made without (as above).
Complexity?
Sure, if that's what you want, we've got complexity, but it'll cost you...
(as I tell my trainees: "just because we can do it, does not make it a
good idea!")
Build a dictionary of "buckets" - with the (lowest point) grade-steps as
keys and the applicable messages as values (this will actually be easier
to maintain than the 'ladder'!), eg
90:"You got an A "
80:"You got a B "
...
0:"You didn't say what should happen"
Take the grade, check, and properly prepare it(!)
(why "check"?)
Loop through the dictionary:
if the grade 'fits into' this bucket:
print the message
break # no point in continuing to loop
# otherwise continue looping
Not to be recommended
- but if you are a 'glutton for punishment', don't bother with the
dictionary's 0/last entry. Instead use a for-else structure...
Such would be an excellent case-study illustration of why 'simple' beats
'complex'!
(sorry for the sardonic humor, disregard the last paragraph - most
professional coders (in fact, all that I know) eschew for-else, or-else!)
--
Regards =dn
More information about the Python-list
mailing list