Problems with scripts

Steve D'Aprano steve+python at pearwood.info
Mon Feb 13 18:41:58 EST 2017


On Tue, 14 Feb 2017 03:30 am, lauren.sophia1998 at gmail.com wrote:

> Hello! I have 2 python assignments that I just can't figure out. The first
> one returns the same thing no matter what I input and the second won't
> accept "done" to stop the program and return answers. Please help!

Hi Lauren,

Best to ask one question per post, unless they are very closely related. You
might like to resend your second question in a new message, with a
different SUBJECT line.



> print("How old are you: 17, 18, 19, or 20?")
> answer = input("> ")

After this line, "answer" is a string. Even if it looks like a number, it is
still a string. Have you learned about the differences between strings and
integers yet?

How do you think you might change answer to an int, or a float, if and only
if it can, but leave it as a string if not?


> if answer == 17 or 18 or 19 or 20:
>     print("Wow, you are old!")


Nice try, but not quite! Python code is very close to English, but not
*that* close. In English, you can say:

if the answer equals 17 or 18 or 19 or 20

but Python doesn't understand that. You can write this instead:

if answer == 17 or answer == 18 or answer == 19 or answer == 20:

but perhaps an easier way is:

if answer in (17, 18, 19, 20):

(But remember, at the moment answer is still a string. Strings are never
equal to ints, even if they look the same.)


> elif answer != 17 or 18 or 19 or 20:

There's no need to repeat the test, just say

else:

instead.


>     if type(answer) is int or float:
>         print("You just can't follow drections, can you? Choose either 17,
>         18, 19, or 20.") input("> ")
>     elif type(answer) is str:
>         print("That isn't even a number. Choose either 17, 18, 19, or
>         20.") input("> ")




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list