1
votes

I have a code where the user is asked to input two integers, separated by a " ". This should continue as long as the user does not input anything, causing a ValueError, and breaking the While loop. However, I can't figure out what am I doing wrong:

def syote():
 koepisteet_all = []
 harjoitukset_all = []
 while True:
    koepisteet, harjoitukset = input('Koepisteet ja harjoitusten määrä: ').split()
    if ValueError:
        break
    else:
        koepisteet_all.append(koepisteet)
        harjoitukset_all.append(harjoitukset)


print(koepisteet_all)
print(harjoitukset_all) 

if __name__ == "__main__":
     
syote()

As wished, I do get a ValueError "ValueError: not enough values to unpack (expected 2, got 0)", but the code stops running.

1
Use try/except to catch errors, not if.Barmar
I don't get it : you say "should continue" and "break the loop" at the same time, should it ask again or stop ?azro
With the current indentation, thet function syote() ends after the while loop. Did you want the two print statements to be executed after the loop? Then you have to indent them correctly.jps

1 Answers

0
votes

You need a try/except structure :

  • if a ValueError is raises (because of wrong input), then stop with break
  • if 2 values are given, save them
def syote():
    koepisteet_all, harjoitukset_all = [], []
    while True:
        try:
            koepisteet, harjoitukset = input('Koepisteet ja harjoitusten määrä: ').split()
            koepisteet_all.append(koepisteet)
            harjoitukset_all.append(harjoitukset)
        except ValueError:
            break

    print(koepisteet_all)
    print(harjoitukset_all)