kuansterful
Posts: 1
Joined: Fri Apr 05, 2019 8:50 pm

[HELP] Try Except Input Failure

Fri Apr 05, 2019 8:59 pm

So I´m trying to create a (y/n) input on Python with the Try Except Function that I saw from this website below:

https://geek-university.com/python/the- ... tatements/

I followed it and created this code:

Code: Select all

try:
    start = str(input('Start? (y/n): '))
    if start == (str('y') or str('Y')):
        print('you just started.')
        print('start = ' + start)
    else:
        print('you DID NOT start.')    
except:
    print ('You have entered an invalid value.')
When I ran it, it can take lowercase y but not uppercase y. Also, when I enter numbers, it should print You have entered an invalid value but it didnt. Can anyone see whats wrong? I altered the code so many times but it cant function as I want it to be. :(

B.Goode
Posts: 7730
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: [HELP] Try Except Input Failure

Sat Apr 06, 2019 8:22 am

Welcome to the Raspberry Pi forums.

(Although this isn't exclusively a Raspberry Pi problem. But we can still be helpful.)

The problem isn't with Try/Except.

Get a python reference book, or online tutorial like the one you are using, and check this line:

Code: Select all

    if start == (str('y') or str('Y')):
That looks like a reasonable translation from plain English, but the python interpreter almost certainly does not process it in the way you expect or require.

Hint: as with everyday maths, brackets force certain things to be evaluated first. What does (str('y') or str('Y')) actually result in?

The interactive interface mode used by python run directly from the shell (command line) prompt can be useful for debugging your ideas in situations like this.

User avatar
Paeryn
Posts: 2517
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: [HELP] Try Except Input Failure

Sat Apr 06, 2019 1:36 pm

Whilst not related to your problem, your calls to str() are superfluous. input() returns a string, 'y' and 'Y' are already strings so there's no need to make calls to get the string representation of any of them, just use them as-is.
She who travels light — forgot something.

dasagrivamanu
Posts: 2
Joined: Sun Jan 27, 2019 5:26 am

Re: [HELP] Try Except Input Failure

Tue May 21, 2019 5:00 pm

It's better to use python 'in' operator in such cases. See below:

Code: Select all

if start in ('y', 'Y'):
After replacing the if condition as per the above statement, your code will run just fine. However, you can refer to this Python try-except tutorial to resolve any doubts on exceptional handling.

Return to “Python”