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)
Related
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.
#Guess the num
import random
def is_valid_num(num):
if num.isdigit() and 1 <= int(num) <= 100:
return True
else:
return False
def main():
number = random.randint(1,100)
guessed_number = False
guess = input('enter a num')
#guess = (input('enter a num'))
num_of_guesses = 0
while not guessed_number:
if not is_valid_num(guess):
#return False
guess = input('i count only digits enter 1<num<100')
continue
else:
num_of_guesses += 1
#break
guess = int(guess)
if guess < number:
print ('entered number is low')
elif guess > number:
print ('entered number is high')
else:
print ('you got in',num_of_guesses, 'guesses')
guessed_number = True
main()
Expected Out
if random number is system is 51 and we pressed 50 it will print too low, then continue this process lets say we gave input 51
output will you got in 2 guesses
isdigit() is a string method, it doesn't work on int inputs.
change this :
guess = int(input('enter a num'))
to this:
guess = input('enter a num')
your code after editing:
#Guess the num
import random
def is_valid_num(num):
if num.isdigit() and 1 <= int(num) <= 100:
return True
else:
return False
def main():
number = random.randint(1,100)
guessed_number = False
guess = input('enter a num')
#guess = (input('enter a num'))
num_of_guesses = 0
while not guessed_number:
if not is_valid_num(guess):
#return False
guess = input('i count only digits enter 1<num<100')
continue
else:
num_of_guesses += 1
break
guess = int(guess)
if guess < number:
print ('entered number is low')
elif guess > number:
print ('entered number is high')
else:
print ('you got in',num_of_guesses, 'guesses')
guessed_number = True
main()
#Thanks Issac Full code is below
#Guess the num
import random
def is_valid_num(num):
if num.isdigit() and 1 <= int(num) <= 100:
return True
else:
return False
def main():
number = random.randint(1,100)
guessed_number = False
guess = input('enter a num')
#guess = (input('enter a num'))
num_of_guesses = 0
while not guessed_number:
if not is_valid_num(guess):
#return False
guess = input('i count only digits enter 1<num<100')
continue
else:
num_of_guesses += 1
#break
guess = int(guess)
if guess < number:
guess = (input('entered number is low try again'))
elif guess > number:
guess = (input('entered number is high try again'))
else:
print ('you got in',num_of_guesses, 'guesses')
guessed_number = True
main()
Output is below
>>enter a num55
entered number is high try again55
entered number is high try again45
entered number is high try again88
entered number is high try again30
entered number is high try again10
entered number is low try again20
entered number is low try again25
entered number is high try again22
entered number is low try again23
you got in 10 guesses
I am having a touch of difficulty in getting my values to display using recursive methods. I am wanting to type in 10 numbers and, depending on the choice, will return the largest number, the smallest number, and the sum of the numbers. I am getting two errors: One is that the (len) cannot return an int and if I put in a value in the individual function, it will continue to loop until the program reaches it's parsing limit (999). I am not sure how to proceed and get the values I want and it seems to be a main issue with the values I put in. Any suggestions would be appreciated!
def displayMenu():
print('Enter 1 to find the largest number: ')
print('Enter 2 to find the smallest number: ')
print('Enter 3 to sum the list of numbers: ')
print('Enter 4 to exit: ')
choice = int(input('Please enter your choice: '))
while choice <= 0 or choice >= 5:
print('Enter 1 to find the largest number: ')
print('Enter 2 to find the smallest number: ')
print('Enter 3 to sum the list of numbers: ')
print('Enter 4 to exit: ')
choice = int(input('Please enter your choice: '))
else:
return choice
def main():
MIN = 1
MAX = 100
num_MAX = 10
user_num = []
number_list = []
for i in range(num_MAX):
user_num = int(input('Please enter a number at this time: '))
while user_num < 1 or user_num > 100:
user_num = int(input('Please re-enter numbers between 1 and 100:' ))
number_list.append(user_num)
choice = displayMenu()
while choice != 4:
if choice == 1:
largest = find_largest(user_num)
print('The largest number is: ', largest)
elif choice == 2:
smallest = find_smallest(user_num)
print('The smallest number is: ', smallest)
elif choice == 3:
summy = find_sum(user_num)
print('The sum of the numbers entered is: ', summy)
choice = displayMenu()
def find_largest(user_num):
n = len(user_num)
if n == 1:
return user_num[0]
else:
temp = find_largest(user_num[0:n - 1])
if user_num[n - 1] > temp:
return user_num[n - 1]
else:
return temp
def find_smallest(user_num):
n = len(user_num)
if n == 1:
return user_num [0]
else:
temp = find_smallest(user_num[0:n - 1])
if user_num[n - 1] < temp:
return user_num[n - 1]
else:
return temp
def find_sum(user_num):
user_num = [1,2,3,4]
n = len(user_num)
if len(user_num) == 1:
return user_num [0]
else:
return user_num[n - 1] + sum[0:n - 1]
main()
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 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