Wrong Output. Largest and Smallest number is wrong? [duplicate] - python

This question already has answers here:
how to find the smallest integer in a list? [duplicate]
(2 answers)
Closed 1 year ago.
Need help with an assignment. I'm not sure why I'm getting the largest and smallest number wrong.
largest = None
smallest = None
while True:
num = input('Enter a number: ')
if num == 'done':
break
try:
y=float(num)
except:
print ('Invalid Input')
continue
if largest is None:
largest=num
elif num > largest:
largest=num
if smallest is None:
smallest=num
elif num < smallest:
smallest=num
print("Maximum is", largest)
print ("Minimum is", smallest)

num is a string, the type needs to be converted when comparing

You are converting float converted value and then storing it in y.
But you are comparing using num.
Try this:
largest = None
smallest = None
while True:
num = input('Enter a number: ')
try:
y=float(num)
except Exception as e:
print ('Invalid Input')
break
if not largest:
largest=y
elif y > largest:
largest=y
if not smallest:
smallest=y
elif y < smallest:
smallest=y
print("Maximum is", largest)
print ("Minimum is", smallest)
This will break from the loop once you enter anything that cannot be parsed as a number in python.
Also use this in python 3. If you're using python2.7, you need raw_input.
If you are using Python 3.x, raw_input has been renamed to input. Quoting the Python 3.0 release notes PEP3111,
raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input())

You are comparing strings, You have to change your cast in the try:
try:
num=float(num)
except:
print ('Invalid Input')

In your code, line 8, you define y = float(num). Then you just need to use y instead of num, like this:
largest = None
smallest = None
while True:
num = input('Enter a number: ')
if num == 'done':
break
try:
y=float(num)
except:
print ('Invalid Input')
continue
if largest is None:
largest=y
elif y > largest: # !!!
largest=y
if smallest is None:
smallest=y
elif y < smallest: # !!!
smallest=y
print("Maximum is", largest)
print ("Minimum is", smallest)

Related

How do I have a value that can be both a floating decimal point or a string in python?

so, I need one of my variables to be A possibility. like, it is a user input var & it can be both a floating decimal point or a string. And, so I want to do stuff with it, like >/</= but if the user says "done" I exit. So, let me show you:
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
float(num)
except:
"invalid input"
if num == "done":
break
if num > largest:
largest = num
if smallest == None:
smallest= num
if smallest > num:
smallest = num
print(num)
print("Maximum is", largest)
print("Minimum is", smallest)
I don't really understand what you're trying to do, but you can always perform the float conversion after you compare the user input against a string:
largest = float('inf')
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
num = float(num)
except:
print("invalid input")
if num > largest:
largest = num
if smallest == None:
smallest = num
if smallest > num:
smallest = num
print(num)
print("Maximum is", largest)
print("Minimum is", smallest)
Here's a sample play through:
Enter a number: 1.2
1.2
Enter a number: 3.4
3.4
Enter a number: 0
0.0
Enter a number: done
Maximum is inf
Minimum is 0.0
One suggestion for a code simplification I had, assuming you're on Python 3.8+, is to use the walrus := operator, which should allow you to omit the break condition:
while (num := input("Enter a number: ")) != 'done':
try: # same as before
...
First, read the number as a string, check if it's "done" and only after convert to a float:
while True:
num = input()
if num == "done":
break
num = float(num)
# ... do something with num ...
You don't need to have it for this example. The value you read from user input can be always a string and if this string is not "done", then it should be a float number, otherwise it is invalid. More specifically you don't need your input to be any float or string. You need it to be any float or "done". See the following snippet:
largest = None
smallest = None
while True:
text = input("Enter a number: ")
if text == "done":
break
else:
try:
num = float(text)
if smallest is None or num < smallest:
smallest = num
if largest is None or num > largest:
largest = nunm
except:
print("Invalid input")
print("Maximum is", largest)
print("Minimum is", smallest)

I'm stuck on an assignment on Coursera. My output is correct but it still gives me a "mismatch" error. Please, can anyone help me out?

[My solution screenshot][1]
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.
largest = None
smallest = None
while True:
num = input("Enter a number:")
if num == "done":
break
try:
no=int(num)
except:
print("Invalid input")
if largest is None or no > largest:
largest = no
if smallest is None or no < smallest:
smallest = no
print("Maximum is", largest)
print("Minimum is", smallest)
My output:
Invalid input
Maximum is 10
Minimum is 2
← Mismatch
Desired Output:
Invalid input
Maximum is 10
Minimum is 2
As you can see my output is same but it still gives me error.
Help me anyone.
[1]: https://i.stack.imgur.com/D6wCE.png
In Python, break statement doesn't require semicolon. Remove semicolon from break statement
Modify your code in below mentioned way, so that no need to check largest and smallest value for invalid input.
largest = None
smallest = None
while True:
try:
num = int(input("Enter the Integer"))
if num == "done":
break
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
except:
print("Invalid Input")
print("Maximum is ", largest)
print("Minimum is ", smallest)

how should i write this program on python?

can you please tell me why do i get error for this?
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.
largest = None
smallest = None
while True:
try:
num=input("Enter a number: ")
if num == 'done':
break
num=int(num)
if largest == None or largest<num:
largest = num
elif smallest == None or smallest > num:
smallest = num
except ValueError:
print ("Invalid input")
break
print ("Maximum number is", int(largest))
print ("Minimum number is", int(smallest))
You may be using Python 2 instead of Python 3 - please check this. If you are using Python 2, you should be using raw_input() instead of input().
Change elif to if:
if largest == None or largest<num:
largest = num
if smallest == None or smallest > num:
smallest = num
That will guarantee both largest and smallest are both integers (unless the first input is done or another invalid value).
You need to check if largest or smallest is None.
Append the user input to a list inside the while loop, and then slice it in the final print statements:
largest = None
smallest = None
nums = []
while True:
try:
num = input("Enter a number: ")
if num == 'done':
break
num = int(num)
nums.append(num)
except ValueError:
print("Invalid input")
break
print("Maximum number is", max(nums))
print("Minimum number is", min(nums))
Example run:
Enter a number: 22
Enter a number: 2
Enter a number: done
Maximum number is 22
Minimum number is 2
Posting the output and/or the error would be very helpful to help you.
You have to change elif into if and remove the break clause inside the except in order to keep asking for numbers even after an invalid input.
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == 'done':
break
num=int(num)
if largest == None or largest < num:
largest = num
if smallest == None or smallest > num:
smallest = num
except ValueError:
print ("Invalid input")
print ("Maximum number is", int(largest))
print ("Minimum number is", int(smallest))

question include exception handling with finding of largest and smallest no. this is a assignment problem of coursera platform

question:
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 it.
Input:
7 ,2 , bob, 10, 4, done.
Desired output:
Invalid input
Maximum is 10
Minimum is 2
Actual output:
Invalid input
Invalid input
Maximum is 10
Minimum is 2
Code:
largest=-1
smallest=None
while True:
num =input("Enter a number: ")
try:
if num == "done" :
break
elif smallest is None:
smallest=int(num)
elif int(num)<smallest:
smallest=int(num)
elif int(num)>largest:
largest=int(num)
else:
raise ValueError()
except ValueError:
print("Invalid input")
print("Maximum is",largest)
print("Minimum is",smallest)
I think there's a more Pythonic way of doing this. Try this:
inputList = []
while True:
num = input("Enter a number:")
try:
num = int(num)
inputList.append(num)
except:
if num == "done":
break
else:
print ("Invalid input. Ignoring...")
print ("Maximum is:",max(inputList))
print ("Minimum is:",min(inputList))
Edit: This code works with Python3. For Python2, you might want to use raw_input() instead of input()
You are already capturing the ValueError in Exception,
So inside, try, you are raising ValueError there you leave the scope for this error.
When you accept input, and it accepts 4 as input, which is neither larger than largest (i.e. 10) nor smaller than the smallest (i.e. 2). So it lands in else part and raises ValueError (as per your code). Hence prints Invalid input twice in your case. So this part is unnecessary as well as makes your solution bogus.
Again, from efficiency point of view -
1 - You are checking smallest == None for every input, which takes O(1) time and is unnecessary if you take it any integer
Here is the solution you are looking for :-
largest=None
smallest=None
while True:
try:
num = input("Enter a number: ")
num = int(num)
if smallest is None:
smallest = num
if largest is None:
largest = num
if num < smallest:
smallest = num
elif num > largest:
largest = num
except ValueError:
if num == 'done':
break
else:
print("Invalid input")
continue
print("Maximum is",largest)
print("Minimum is",smallest)

Basic Python Loop: Max and Min from User Input

I'm trying to create an program in python for a class and I can't figure out why I can't get the expected output.
The program is to take user input values until a 'done' is entered, and then print the max and min of these values. It also has some error checking for valid input (number and not text).
largest = None
smallest = None
while True:
inp = raw_input("Enter a number: ")
if inp == "done" :
break
try:
num=float(inp)
except:
print "Invalid input"
continue
if inp>largest:
largest=inp
if inp<smallest:
smallest=inp
print "Maximum is ", largest
print "Minimum is ", smallest
The loop breaks properly if 'done' is inserted. It doesn't fail if a text string is entered, but also doesn't print "Invalid input". I'm not asking for someone to solve my homework program, but to provide me with an explanation as to why I never get largest or smallest to be anything other than their original assignment of "None".
Thanks in advance.
largest = None
smallest = None
num = None
while True:
inp = raw_input("Enter a number: ")
if inp == "done" :
break
try:
num=float(inp)
except:
print ("Invalid input")
continue
if largest is None:
largest = num
smallest = num
if num>largest:
largest=num
if num<smallest:
smallest=num
print ("Maximum is ", largest)
print ("Minimum is ", smallest)
if smallest is None or smallest< inp:
smallest=inp
if largest is None or largest > inp:
largest=inp
You need to do something with your comparison operators bro. Right now you're checking if smallest is smaller than input (and vice versa for largest). The result: you're switching max and min. Should've been like this:
if smallest is None or inp < smallest:
smallest = inp
if largest is None or inp > largest:
largest = inp
It doesn't report the proper max or min because you use inp (the string) in your comparisons instead of num (the float).
This is the final code I used. With help from all of you that responded! Thanks to all for their time.
largest = None
smallest = None
while True:
inp = raw_input("Enter a number: ")
if inp == "done" :
break
try:
num=float(inp)
except:
print ("Invalid input")
continue
if smallest is None or smallest< inp:
smallest=inp
if largest is None or largest > inp:
largest=inp
print ("Maximum is ", largest)
print ("Minimum is ", smallest)
Don't use None as your initialization, use floats.
largest =float("-inf") # negative infinity
smallest = float("inf") # infinity
while True:
inp = raw_input("Enter a number: ")
if inp == "done" :
break
try:
num = float(inp)
largest = max(largest, num)
smallest = min(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:
num = int(num)
except:
print("Invalid input")
continue
if smallest == None or num < smallest:
smallest = num
if largest == None or num > largest:
largest = num
print("Maximum is", largest)
print("Minimum is", smallest)
It works, kinda
python27 test.py
Enter a number: 10
Enter a number: 20
Enter a number: 40
Enter a number: done
Maximum is 40
Minimum is None
You will never get a min because a float is never less than None.

Categories