import random as r
print(
"""
Welcome to the Custom Counter!
Type in your starting value and your
ending value. Then, enter the amount
by which to count.
""")
x = True
start = int(input("Starting number: "))
while x != False or start != "":
fin = int(input("Ending number: "))
amount = int(input("Count by: "))
if amount > 0 or amount < 0:
x = False
result = r.randrange(start, fin, amount)
print(result)
input("Hit enter to exit.")
I made the while loop in hopes to exit the program when you clicked enter. Unfortunately, this will not let me exit the while loop no matter what I do. I am a noob at python. What is wrong with my condition?
Thank you!
CodePudding user response:
Welcome to stackoverflow and welcome to Python!
Try to use and
instead of or
.
In your line:
while x != False or start != "":
You say to python, you want to run until 1st or 2nd condition is true. Since the 2nd condition stays always true, while will run forever.
Even more simple:
while x and start:
Hope you will enjoy Python as I do!
CodePudding user response:
my code :
import random as r
print(
"""
Welcome to the Custom Counter!
Type in your starting value and your
ending value. Then, enter the amount
by which to count.
""")
while True:
try:
start = int(input("Starting number: "))
fin = int(input("Ending number: "))
amount = int(input("Count by: "))
except ValueError as verr:
print('error : ', verr,'\n restarting ....')
else:
break
result = r.randrange(start, fin, amount)
print('result : ' ,result)
input("Hit enter to exit.")
this one I believe takes into account inputting of non int
s and restart program from scratch when encountering such kind of inputs.
See The try statement specifies exception handlers and/or cleanup code for a group of statements
PS your code doesnt handle invalid values (i.e. fin < start
)