Qpython 3 if/Elif/Else

Asked

Viewed 196 times

1

Why doesn’t Mey Qpython Android accept a simple if/Elif/Else condition? I’m using Python 3.

x = input('Select an option... ')
if x == 1:
    print('xxxx')
elif x == 2:
    print('yyyy')
elif x == 3:
    print('zzzz')
else:
    print('lalalalala')

(https://i.stack.Imgur.com/qlS40.jpg)

I’m sure everything is indented correctly, but still it always gives me the first elif as a syntax error, someone knows why?

  • Welcome to [en.so]! I removed the part in English because this site is only in Portuguese. And using the code that is in the question, there is no syntax error, so there must be some other detail elsewhere in the code...

1 answer

1

The function input returns a string, and we if's you are comparing with numbers. So you can choose whether to compare with strings (by placing the numbers between quotes):

x = input('Select an option... ')
if x == '1':
    print('xxxx')
elif x == '2':
    print('yyyy')
elif x == '3':
    print('zzzz')
else:
    print('lalalalala')

Or becomes the result of input in a number, using int:

x = int(input('Select an option... '))
if x == 1:
    print('xxxx')
elif x == 2:
    print('yyyy')
elif x == 3:
    print('zzzz')
else:
    print('lalalalala')

Remembering that int can launch a ValueError if you don’t enter a number. Then you can use a while which, until a number is entered, keeps asking the user to type again:

while True:
    try:
        x = int(input('Select an option... '))
        break # número digitado, pode sair do while
    except ValueError:
        print('Você não digitou um número, tente novamente')

if x == 1:
    print('xxxx')
elif x == 2:
    print('yyyy')
elif x == 3:
    print('zzzz')
else:
    print('lalalalala')
  • Good evening hkotsubo. I appreciate the welcome and the attention. I tried your suggestion and that doesn’t seem to be the problem. I tried exhaustively to find any other error, but the application always indicates the same line of Elif as the source of the problem. I am learning, but I already made a similar code on the computer and it worked smoothly. Qpython 3 for android was the first to give problem. By the way, if you don’t mind, how did you format the code to appear "intelligible" that way?

  • @Lehetex To format the code here on the site, follow these tips. As for the syntax error, with the code you passed it does not happen to me. If it worked in another editor, maybe the problem is something in Qpython, I don’t know. It can be tabs and mixed spaces or some other detail...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.