Skip to content
Advertisement

Indefinite while loop not exited by giving it empty str

Can someone please explain to me why this program returns an error about not being able to convert '' to int? I know it can’t be converted, but why does it even go into the while loop after entering ''?

x = input('Enter a number: ')
difference = 0

while str(x) != '':
    y = x
    x = input()
    if difference < int(y) - int(x):
        difference = int(y) - int(x)
else:
    print(difference)

Result:

Traceback (most recent call last):
  File "E:ProgramingPythonUloha.py", line 7, in <module>
        if difference < int(y) - int(x):
ValueError: invalid literal for int() with base 10: ''

Advertisement

Answer

You’re not checking if x equals '' in between getting it via input and attempting to pass it to int:

    x = input()
    if difference < int(y) - int(x):

It’s already in the while loop at that point. You could rearrange things like this:

y = x = input('Enter a number: ')
difference = 0

while x != '':
    new_difference = int(y) - int(x)
    if difference < new_difference:
        difference = new_difference
    y = x
    x = input()

print(difference)

This way it will check the condition after input, and only run the loop again if x isn’t ''.

Also note that x is already a string, so str(x) is unnecessary, and there’s no need to calculate the new difference twice each time. (The else isn’t necessary here either, since there’s no possibility you’ll break out of the loop.)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement