How can I get a program shut down by typing an empty space (' ') into python

Asked

Viewed 113 times

1

How can I make a repeat loop while stopping when the user inserts a blank space (" ")?

I tried to do so:

while num != '':
    num = int(input("Insira um número: "))

But the variable is not an integer, so when inserting a blank space, it presents an error.

When inserting the blank space, it continues and shows the result.

  • Empty space is somewhat dubious. Type a space character followed by a ENTER or just a ENTER? Maybe just convert to numeric string typed has length greater than zero and if it is not a space?

  • is for the user to keep typing for example: 1 3 5 and then when he does not type anything, just enter, show the final result

  • So it’s not for him to enter a space? In this case just check if the input is an empty string.

  • @Gustavocarvalho Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how to do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

3

I do not know if I should do so, but if I want to insist I would have to do the two-step operations, treat it as text and if it is not that then treat it as a number, but the ideal would be to treat a typo, it was important before, doing so becomes even more important, something like that:

while True:
    entrada = input("Insira um número: ")
    if entrada == ' ':
        break
    try:
        num = int(entrada)
        print(num)
    except ValueError:
        print('Dado inválido')

print('fim')

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I didn’t find a very nice way either, but my teacher wants it so we do it

Browser other questions tagged

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