Try except bug check - python

I'm doing a certain online course and I've completed the assignment with this code, but I can still induce a bug with certain inputs, and I can't understand why. I've asked the course mentors (using pseudo code) and they say there's a problem with my try/except statement.
The program should prompt a user for a number, over and over again, returning an error if something non-numeric is entered, with the exception of the string 'done,' in which case it will return the maximum and minimum of all the numbers entered.
Here's the program:
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done': break
try:
float(num)
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)
If you enter the following values as input 1 2 3 pk 27 -37 done, the output is Max: 3, Min -37.
It's driving me crazy. I have do idea why this is happening.

You are casting the input to a float, but not retaining that for later checks.
So later on after the except block, Python is doing string comparisons and is comparing the string "3" to the string "27" and since '3' is 'larger' than '2' it considers "3" larger than "27", much like "b" is larger than "aaabbbbzzz".
To fix it change this:
float(num)
to this:
num = float(num)

Related

How to use max() and min() for two or three digit numbers from user input

I am trying to find the maximum and minimum values of a series of numbers inputted by the user. I get only a semantic error, where both the max and min values are the last number inputted by the user.
This is what I have tried:
largest = None
smallest = None
while True:
snum = input("Enter a number: ")
if snum != "done" :
try:
largest = max(snum)
smallest = min(snum)
except:
print("Invalid Input")
continue
else:
break
print("Maximum is",largest)
print("Minimum is",smallest)
I used the try and except block to error check the user input.
I checked other similar questions such as: How to show max the max and min from user input, but I did not really understand the answer given.
Your first problem is here:
inum = int(snum)
largest = max(snum)
smallest = min(snum)
You're converting the user value (which always comes in as a string) into an integer and storing it in inum. But then you're calling max and min on the original string value, not the number.
Your second problem is that you are only ever checking one number at a time - snum is always filled with the latest number, with other numbers being forgotten.
You need to store each inputted number in a list, and then call max and min on the list as a whole.
Here's a potential solution:
num_list = []
while True:
user = input("Enter a number: ")
if user == "done":
break
try:
inum = int(user)
num_list.append(inum)
except:
print("Invalid input!")
print("The largest number was", max(num_list))
print("The smallest number was", min(num_list))

Python: I am trying to call a function but the expected results won't come

This program prompts the user for numbers and when the user inputs 'done', it should give the largest value which was input and the smallest.
The function seems to work just fine for the largest variable. Which successfully takes the value of the first input. Later, the program keeps running, and it updates its value for the biggest value typed until done is pressed, so it will print it.
The Problem that I'm having is with the variable 'smallest'. Once the program runs, we type some numbers. When we insert ' done ', when the function is running, the Minimum (which relates to the variable smallest) will still have the value 'None'. So I'm having problems, through the function, to assign the smallest with the inputted values, so that it loses its None value.
If I run the function 'manually', i.e., I don't use this logic in a function, it'll work just fine and provide the results as expected.
inum = None
largest = None
smallest = None
def primeval(sizest) :
if sizest is None :
sizest = inum
while True:
num = input ('Enter an integer number: ')
if num == 'done' :
break
try:
inum = int(num)
except:
print ('Invalid input')
continue
primeval (largest)
primeval (smallest)
#if largest is None : #if done manually it'll work
# largest = inum
#if smallest is None :
# smallest = inum
#resume of the code, after the 'manual primeval'
if inum > largest :
largest = inum
if inum < smallest :
smallest = inum
print ('Maximum is', largest)
print ('Minimum is', smallest)
I would approach your problem differently:
numbers = []
while True:
user_input = input ('Enter an integer number (e for end!): ')
if user_input == 'e':
break
try:
number = int(user_input)
except:
print('Invalid input!')
continue
numbers.append(number)
if len(numbers):
print('Maximum is', max(numbers))
print('Minimum is', min(numbers))
You define a function that has no return value (return statement). In the function you want to work with the value inum, which you do not pass as parameter and which you do not define in the function. You shouldn't do that.
If you prefer a solution without a list:
smallest = None
largest = None
while True:
user_input = input ('Enter an integer number (e for end!): ')
if user_input == 'e':
break
try:
number = int(user_input)
except:
print('Invalid input!')
continue
if smallest is None or largest is None:
smallest = number
largest = number
else:
if number < smallest:
smallest = number
if number > largest:
largest = number
print('Maximum is', largest)
print('Minimum is', smallest)
In this case it makes sense to initialize the two values ​​for the first time with None.
you have to return a value:
def primeval(sizest,inum) :
if sizest is None:
sizest = inum
return sizest
and use it like this:
largest = primeval(largest,inum)

Python code returning error depending on IDE

I am doing a course and the code is one of the excercises.
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. Enter 7, 2, bob, 10, and 4 and match the output below.
I believe I have found correct code to pass the assignment - it does work fine in Pycharm, however when I try to submit it on the web IDE it returns different value. Could someone explain why this is happening?
I am using Pycharm and tried it also on www.py4e.com website (where returns different output).
largest = None
smallest = None
while True:
num = input("Enter number:")
if num == 'done':
break
try:
num = int(num)
except:
print("Invalid input")
if smallest is None or num < smallest:
smallest = num
if largest is None or largest > num:
largest = num
print("Maximum", largest)
print("Minimum", smallest)
In Pycharm it returns:
Maximum is 10
Minimum is 2
At www.py4e.com it returns:
Maximum is 2
Minimum is 2
Change the condition for the largest number and also, place if statements inside try block as below or else it will break before taking another input.
largest = None
smallest = None
while True:
num = input("Enter number:")
if num == 'done':
break
try:
num = int(num)
if smallest is None or num < smallest:
smallest = num
if largest is None or largest < num:
largest = num
except:
print("Invalid input")
print("Maximum", largest)
print("Minimum", smallest)

How to handle try/exception block in python?

largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done" :
break
if num>largest:
largest=num
if smallest is None:
smallest=num
elif num<smallest:
smallest=num
try :
n=float(num)
except:
print "Invalid input"
continue
print num
print "Maximum", largest
print "Manimum", smallest
Combining question text and comments, I assume that you wonder why the program does output erroneous input as largest. The answer to this is that you should move the try block checking your input right before the update of largest and smallest. Also it might be helpful to not use another variable n for the result of the conversion, but try num = float(num) after checking num for "done".
(As this is obviously homework, I will not post the "solution", but leave it with the hints.)

print out max and min numbers of the input

I'm asked to write a program which takes in a bunch of numbers and print out the maximum and minimum number of them, below is my code:
maximum = None
minimum = None
while True:
num = raw_input("Enter a number: ")
if num == 'done':
break;
try:
num = int(num)
if num >= maximum:
maximum = num
if num <= minimum:
minimum = num
except:
print "Please Enter A Number!"
continue
print "Max = ",maximum, "Min = ",minimum
The thing is when I run this program the Min always equals to its initial value None, but it will work if I change the second if statement into else. What's wrong with the current one?
If the indentation is correct in the question (and not some copy paste mistake, that is the issue, the minimum = num line needs to be indented towards the right. Also, you need to take care of maximum and minimum being None that would throw error when used in comparison to int in Python 3.x , and would not work correctly for minimum in Python 2.x since no int would be smaller than None.
maximum = None
minimum = None
while True:
num = raw_input("Enter a number: ")
if num == 'done':
break;
try:
num = int(num)
if maximum is None:
maximum = num
minimum = num
if num >= maximum:
maximum = num
if num <= minimum:
minimum = num
except:
print "Please Enter A Number!"
continue
print "Max = ",maximum, "Min = ",minimum
Here is how I would do it:
track = []
while True:
num = raw_input("Enter a number: ")
if num == 'done':
break
try:
num = int(num)
except ValueError:
print "Please Enter A Number!"
continue
track.append(num)
print "Max = ", max(track), "Min = ", min(track)
Well the problem here is with your use of None here as the default value. It happens to work for the maximum because all numbers are greater than None. However, that way the minimum condition will never come true.
There are a few ways to fix this. The obvious and non-pythonic way is to set the minimum to float('inf'). This is kinda obviously infinity. The "better" way would be to change the condition to:
if num <= minimum or minimum==None:
which will automatically set the min on the first pass.
P.S.: I'm guessing you're doing this for algo-practice, because min() and max() functions are built-in.

Categories

Resources