Jack Porter
Jack Porter

Reputation: 1

How to end a while loop in python 3

So I am using modular arithmetic to work out what day it will be in "x" amount of days. I have tried to use the break command to end the while loop but when I do it prints what the answer will be for all of the loops. This is my code for one of the loops

while (x) == ('Monday') or ('monday'):
    if round_4 == ".1":
        print ("It will be Tuesday")
    elif round_4 == ".2":
        print ("It will be Wednesday")
    elif round_4 == ".3":
        print ("It will be Thursday")
    elif round_4 == ".4":
        print ("It will be Friday")
    elif round_4 == ".5":
        print ("It will be Saturday")
    elif round_4 == ".6":
        print ("It will be Sunday")
    elif round_4 == ".7":
        print ("It will be Monday")
    elif round_4 == ".8":
        print ("It will be Tuesday")
    elif round_4 == ".9":
        print ("It will be Wednesday")
    elif round_4 == ".0":
        print ("It will be Monday AGAIN")
    else:
        print ("Sorry, there has been a tecnical difficulty! Please try again!")

If round_4 was say ".2" it would print the ".2" elif for all the while loops. Sorry, I'm a bit of a n00b to python!

Upvotes: 0

Views: 596

Answers (2)

Blckknght
Blckknght

Reputation: 104802

Leaving aside whether this loop is a good way to solve your larger problem, one reason your current while loop is not ever ending is because you've messed up the condition. The expression (x) == ('Monday') or ('monday') is always true, because the == operator is not distributed over the or. It is equivalent to (x == 'Monday') or 'monday', and since any non-empty string is truthy, the condition is always met.

A more correct way to write the expression would be x == 'Monday' or x == 'monday', or perhaps x in ['Monday', 'monday'].

However, I'd suggest using the lower or upper methods on the x string and testing only a single case (this will allow any form of capitalization): x.lower() == 'monday'.

Another issue, pointed out a comment by Elizon, is that you're not ever changing the value of x in the loop, so if the condition is true at the start, it will remain true forever. If you only expect this code to be run at most once, you probably want an if rather than a while.

Upvotes: 0

Kevin
Kevin

Reputation: 30171

So I am using modular arithmetic to work out what day it will be in "x" amount of days.

No you're not. Python has built-in support for modular arithmetic in the modulus operator, %:

>>> 29 % 7
1

You do not need looping or recursion to solve this problem.

Assuming you have an integer variable today (with zero standing for Monday, one for Tuesday, etc.), this is very simple math:

return (today+x) % 7

You can then use dictionaries to convert between day names and numbers.

Upvotes: 1

Related Questions