I am trying to make this code run so that when I enter 'done' it break me out of the loop. The issue is I put a try/except to try and catch anything that isn't a number and feed back and error message. This catches before the if statement that would break me out of the loop and instead feeds back an error message and catches me in an infinite loop. I've tried moving the try/except after all the if/else statements but then the string gets placed inside the value for maximum and this is not what I am trying to accomplish. Is there a way for me to get the try and except to run but still allow me to pass a 'done' command to exit the loop?
largest = None
smallest = None
while True:
num = input("Enter a number: ")
try:
num = float(num)
except:
print('Invalid Input')
continue
if num == "done" :
break
elif largest is None:
largest = num
elif smallest is None:
smallest = num
elif largest < num:
largest = num
elif smallest > num:
smallest = num
print(num)
print("Maximum", largest)
print("Minimum", smallest)
first test for done and then convert to float
And you can simplify the tests
The program should work if you enter none or one number
num = input("Enter a number: ")
if num == "done" :
break
try:
num = float(num)
except:
print('Invalid Input')
continue
largest = largest or num
smallest = smallest or num
largest = max(num, largest)
smallest = min(num, smallest)
The reason is that you're using checking if the input is a float before you're checking for "done" so when it's actually "done" it just continues before it checks for it.
I would fix it this way.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
# check if it's done first
if num == "done" :
break
try:
num = float(num)
except:
print('Invalid Input')
continue
elif largest is None:
largest = num
elif smallest is None:
smallest = num
elif largest < num:
largest = num
elif smallest > num:
smallest = num
print(num)
print("Maximum", largest)
print("Minimum", smallest)
Change this:
try:
num = float(num)
except:
print('Invalid Input')
continue
if num == "done":
break
to this:
try:
num = float(num)
except:
if num == "done":
break
print('Invalid Input')
continue
By putting the if inside the except, you allow the loop to break before it can continue.
Related
I am creating a program to find the LCM of two numbers. I want to return 1 when no input is given, but instead I end up with a ValueError as no integer input is given. I know that you can use Try and Except to ignore the ValueError, but I'm not exactly sure how you use them. This is my complete code:
def lcm(number1,number2):
if number1>number2:
largernumber= number1
else:
largernumber=number2
multiple=largernumber
while True:
if largernumber%number1==0 and largernumber%number2==0:
print("The LCM is", largernumber)
break
else:
largernumber=largernumber+multiple
number1=int(input("Please enter number 1: "))
number2=int(input("Please enter number 2: "))
if number1==0 or number2==0:
print("0")
else:
lcm(number1,number2)
You can implement it like this
def lcm(number1,number2):
if number1>number2:
largernumber= number1
else:
largernumber=number2
multiple=largernumber
while True:
if largernumber%number1==0 and largernumber%number2==0:
print("The LCM is", largernumber)
break
else:
largernumber=largernumber+multiple
try:
number1=int(input("Please enter number 1: "))
number2=int(input("Please enter number 2: "))
if number1==0 or number2==0:
print("0")
else:
lcm(number1,number2)
except:
print(1)
For the following problem:
Write a program that repeatedly prompts a user for integer numbers until the user enters done.
Once 'done' is entered, print out the largest and smallest of the numbers.
If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.
Input Cases:
Enter 7, 2, bob, 10, and 4 and match the output below.
My program is not correctly showing the ans. What is problem here?
while True:
inp = input("Enter number: ")
if inp == "done":
print("done")
break
try:
inp_data = int(inp)
except:
print("Invalid input")
if smallest is None:
smallest = inp_data
elif inp_data < smallest:
smallest = inp_data
elif inp_data > largest:
largest = inp_data
print("largest", largest)
print("smallest", smallest)
Output:
Invalid input,
Maximum is 10,
Minimum is 2.
You are missing out few statements while printing the output.
The following code worked for me.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
#print(num)
num = int(num)
if largest is None or largest < num:
largest = num
elif smallest is None or smallest > num :
smallest = num
except ValueError:
print("Invalid input")
continue
print("Maximum is", largest)
print("Minimum is", smallest)
Have verified and runs successfully.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
num = int(num)
except:
print("Invalid input")
continue
if largest==None or num > largest:
largest = num
elif smallest==None or smallest > num:
smallest = num
print("Maximum is", largest)
print("Minimum is", smallest)
Try this code and thank me later
largest = None
smallest = None
while True:
val = input("Enter a number: ")
if val == "done":
break
try:
val = int(val)
if largest is None or val > largest:
largest = val
elif smallest is None or smallest > val:
smallest = val
except:
print("Invalid input")
continue
print("Maximum is", largest)
print("Minimum is", smallest)
If you include elif statements, they won't be checked if the condition in the if statement is true, so if I had "elif smallest..." it would never be checked giving 'Minimus is none' as a result.
largest = None
smallest = None
while True:
enter_num = input('Enter a number ')
if enter_num == 'done':
break
try:
num = int(enter_num)
if largest is None or largest < num:
largest = num
if smallest is None or smallest > num:
smallest = num
except:
print('Invalid input')
continue
print('Maximum is', largest)
print('Minimum is', smallest)
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
#print(num)
num=int(num)
if largest is None or largest < num:
largest=num
elif smallest is None or smallest > num:
smallest=num
except:
print("Invalid input")
continue
print("Maximum is", largest)
print("Minimum is", smallest)
largest = 0
smallest = 100
while True:
num = input('Enter a number: ')
if num == 'done' :
break
try:
l1 = int(num)
except:
print('Invalid Input')
continue
#print(l1)
if l1 > largest:
l2 = l1
largest = l2
elif l1 < smallest:
l3 = l1
smallest = l3
print('Maximum', largest)
print('Minimum', smallest)
This is the only thing I could work out. Couldn't figure out how to keep
largest and smallest at the value of none
Fellow coders; most of the above-provided codes are right. The problem is the browser. I used chrome and got a mismatch. I then run the same code using Microsoft edge and finally received "Grade updated on server." So use a different browser. thank me later.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done": break
try:
num= int(num)
if largest is None or largest < num: largest = num
if smallest is None or smallest > num: smallest = num
except:
print("Invalid input")
continue
print("Maximum is", largest)
print("Minimum is", smallest)
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try :
n = int(num)
except :
print("Invalid input")
continue
if largest is None or largest < n:
largest = n
elif smallest is None or smallest > n:
smallest = n
print("Maximum is", largest)
print("Minimum is", smallest)
I want to loop this code indefinitely (until the user kills it) from the very beginning to the end, so I won't have to keep rerunning it. Is there anyway to make this possible? I would appreciate the help greatly.The program should restart itself after the user inputs "done" (and its printed all the details.)
print ("Input done when finished")
print ("Input thresholds")
maximumnum = int(input("Input maximum number: "))
minimumnum = int(input("Input minimum number: "))
minimum = None
maximum = None
while True:
inp =input("Enter a number: ")
if inp == "done":
break
try:
num = float(inp)
except:
print ("Invalid input")
continue
## ---- Additional Check ---- ##
if num > maximumnum:
print('Number greater the maximum allowed range')
break
if num < minimumnum:
print('Number smaller the maximum allowed range')
break
## -------------------------- ##
if minimum is None or num < minimum:
minimum = num
if maximum is None or num > maximum:
maximum = num
print ("Maximum:", maximum)
print ("Minimum:", minimum)
print ("Try again")
Why not just wrap the whole script in another while True? To stop, the user must kill the running process.
while True:
print ("Input done when finished")
print ("Input thresholds")
maximumnum = int(input("Input maximum number: "))
minimumnum = int(input("Input minimum number: "))
minimum = None
maximum = None
while True:
inp =input("Enter a number: ")
if inp == "done":
break
try:
num = float(inp)
except:
print ("Invalid input")
continue
## ---- Additional Check ---- ##
if num > maximumnum:
print('Number greater the maximum allowed range')
break
if num < minimumnum:
print('Number smaller the maximum allowed range')
break
## -------------------------- ##
if minimum is None or num < minimum:
minimum = num
if maximum is None or num > maximum:
maximum = num
print ("Maximum:", maximum)
print ("Minimum:", minimum)
print ("Try again")
I would wrap this on method and run that in infinite loop. Please try following:
def process_input(maximumnum, minimumnum):
minimum = None
maximum = None
while True:
inp =input("Enter a number: ")
if inp == "done":
break
try:
num = float(inp)
except:
print("Invalid input")
continue
## ---- Additional Check ---- ##
if num > maximumnum:
print('Number greater the maximum allowed range')
break
if num < minimumnum:
print('Number smaller the maximum allowed range')
break
## -------------------------- ##
if minimum is None or num < minimum:
minimum = num
if maximum is None or num > maximum:
maximum = num
return minimum, maximum
def main():
print("Input done when finished")
print("Input thresholds")
maximumnum = int(input("Input maximum number: "))
minimumnum = int(input("Input minimum number: "))
minimum, maximum = process_input(maximumnum, minimumnum)
print("Maximum:", maximum)
print("Minimum:", minimum)
print("Try again")
if __name__ == '__main__':
while True:
main()
Hope this helps.
I frequently use a paradigm such as this to accomplish a "loop until I say so"
sort of thing.
class UserKilledException(KeyboardInterrupt):
pass
try:
while True:
#do stuff
except UserKilledException:
#do cleanup here
Just have your code throw a UserKilledException whenever the user decides to close the application somehow. If it's a cli application then KeyboardInterrupt will do the trick.
I would like to check if my input is digit and in range(1,3) at the same time and repeat input till I got satisfying answer.
Right now I do this in this way, but the code is quite not clean and easy... Is there a better way to do this?
Maybe with while loop?
def get_main_menu_choice():
ask = True
while ask:
try:
number = int(input('Chose an option from menu: '))
while number not in range(1, 3):
number = int(input('Please pick a number from the list: '))
ask = False
except: # just catch the exceptions you know!
print('Enter a number from the list')
return number
Will be grateful for help.
I guess the most clean way of doing this would be to remove the double loops. But if you want both looping and error handling, you'll end up with somewhat convoluted code no matter what. I'd personally go for:
def get_main_menu_choice():
while True:
try:
number = int(input('Chose an option from menu: '))
if 0 < number < 3:
return number
except (ValueError, TypeError):
pass
def user_number():
# variable initial
number = 'Wrong'
range1 = range(0,10)
within_range = False
while number.isdigit() == False or within_range == False:
number = input("Please enter a number (0-10): ")
# Digit check
if number.isdigit() == False:
print("Sorry that is not a digit!")
# Range check
if number.isdigit() == True:
if int(number) in range1:
within_range = True
else:
within_range = False
return int(number)
print(user_number())
``
see if this works
def get_main_menu_choice():
while True:
try:
number = int(input("choose an option from the menu: "))
if number not in range(1,3):
number = int(input("please pick a number from list: "))
except IndexError:
number = int(input("Enter a number from the list"))
return number
If your integer number is between 1 and 2 (or it is in range(1,3)) it already means it is a digit!
while not (number in range(1, 3)):
which I would simplify to:
while number < 1 or number > 2:
or
while not 0 < number < 3:
A simplified version of your code has try-except around the int(input()) only:
def get_main_menu_choice():
number = 0
while number not in range(1, 3):
try:
number = int(input('Please pick a number from the list: '))
except: # just catch the exceptions you know!
continue # or print a message such as print("Bad choice. Try again...")
return number
If you need to do validation against non-numbers as well you'll have to add a few steps:
def get_main_menu_choice(choices):
while True:
try:
number = int(input('Chose an option from menu: '))
if number in choices:
return number
else:
raise ValueError
except (TypeError, ValueError):
print("Invalid choice. Valid choices: {}".format(str(choices)[1:-1]))
Then you can reuse it for any menu by passing a list of valid choices, e.g. get_main_menu_choice([1, 2]) or get_main_menu_choice(list(range(1, 3))).
I would write it like this:
def get_main_menu_choice(prompt=None, start=1, end=3):
"""Returns a menu option.
Args:
prompt (str): the prompt to display to the user
start (int): the first menu item
end (int): the last menu item
Returns:
int: the menu option selected
"""
prompt = prompt or 'Chose an option from menu: '
ask = True
while ask is True:
number = input(prompt)
ask = False if number.isdigit() and 1 <= int(number) <= 3 else True
return int(number)
I am struggling with my code - can sb help ? why it does not print "Invalid input" when i run it in Python and enter something else than the integer ?
Basically the program should run in endless loop until we enter "done". so even after except it should still prompt for entering a number.
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
try:
if num == "done" :
print "Maximum is", largest
print "Minimum is", smallest
exit
if largest is None:
largest = num
elif largest < num:
largest = num
if smallest is None:
smallest = num
elif smallest > num:
smallest = num
except int(num) == -1:
print "Invalid input"
continue
largest = None
smallest = None
try:
num = raw_input("Enter a number: ")
x = int(num, base = 10)
except:
print "Invalid input"
while num != "done":
try:
num = raw_input("Enter a number: ")
x = int(num, base = 10)
except:
print "Invalid input"
continue
if largest is None:
largest = num
elif largest < num:
largest = num
if smallest is None:
smallest = num
elif smallest > num:
smallest = num
print "Maximum is", largest
print "Minimum is", smallest
exit