0
votes

I am trying to create a simple while loop that checks whether any of three values are negative, and if True, asks for those three values again.

Here is my code:

def vyohykeliput():

    rivi = input("How many AB-zone trips do you make per month?\n")
    ABmatka = int(rivi)
    rivi1 = input("How many BC-zone trips do you make per month?\n")
    BCmatka = int(rivi1)
    rivi2 = input("How many ABC-zone trips do you make per month?\n")
    ABCmatka = int(rivi2)

    while ABmatka or BCmatka or ABCmatka < 0:
        print("The given values cannot be negative!")
        rivi = input("How many AB-zone trips do you make per month?\n")
        ABmatka = int(rivi)
        rivi1 = input("How many BC-zone trips do you make per month?\n")
        BCmatka = int(rivi1)
        rivi2 = input("How many ABC-zone trips do you make per month?\n")
        ABCmatka = int(rivi2)
vyohykeliput()

But all I managed to get as output is printing "The given values..." each time I run the program, whether the given numbers are negative or not. Also, I've managed to make it print "The given values..." an infinite number of times.

2
Your while condition is interpreted as while ABmatkla is True or BCmatka is True or ABCmatkca is lesser than 0 in python a non empty string is considered True and any non 0 integer as well. This means that ABmatkla, BCmatka are always evaluated as True. Just add < 0 to all variables in the condition should make it workPlopp

2 Answers

1
votes

What you want to do is:

while ABmatka < 0 or BCmatka < 0 or ABCmatka < 0:
    # ...

A short-hand (at least for more values or an iterable of values) for that would be

while any(x < 0 for x in (ABmatka, BCmatka, ABCmatka)):
   # ...

ABmatka or BCmatka or ABCmatka < 0 is truthy if either of the following expressions is truthy:

ABmatka
BCmatka
ABCmatka < 0
0
votes

Put like this:

while ABmatka < 0 or BCmatka < 0 or ABCmatka < 0:

If you only put like this you are asking if ABmatka or BCmatka are not None or any other falsy value like 0, "", [],

while ABmatka or BCmatka or ABCmatka < 0: