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.)
Related
So the task is to:
"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'm still kind of new to Python but I can't seem to achieve this assignment on my own. I kind of want to avoid just copying someone else's code because the teacher of the module Charles Severence, says that's not a good idea. But I'm also getting tired of this assignment that probably does not reflect anything I would normally want to use python for as a programmer.
This is my code at the moment. It seems like no matter what I change there is always a new error:
Please help, suggest solutions and tell me the mistakes I'm making.
EDIT:
I have received comments about the indentation errors and I wanted to clarify that these were typos I caused when copying my code into this forum. Anyway, I have adjusted my code and it no longer has the problem of not accepting 'done' or not continuing the loop after an invalid input. Now, the difficulty I'm having is retrieving the maximum and minimum values with or without a list function. Also, at this point I'm so stuck I wouldn't mind receiving some direct answers with working code.
largest = None
smallest = None
number_list = []
while True:
num = input('Enter a number:')
if num == 'done' : break
try:
num = int(num)
number_list.append(num)
except:
print ('Invalid Input')
continue
def max(num):
for largest in number_list[num]:
if largest < num:
largest = num
return largest
def min(num):
for smallest in number_list[num]:
if smallest is None:
smallest = num
if smallest > num:
smallest = num
return smallest
print ('Maximum is',max(num))
print ('Minimum is',min(num))
While not giving away the complete code due to the reasons your teacher stated, there are quite a few things to look at there:
The values aren't currently being returned since input always returns a string, and you need integers to compare, so after you input, you should add a line that tries to convert the input to an integer variable, something like this:
num = input('Enter a number:')
if num != "done":
try:
num = int(num)
number_list.append(num)
except ValueError:
print("Must be a number or the word 'done'")
Note that I also checked for a number_list variable that should be defined as an empty list beforehand. Lists are great for the purpose of storing many numbers on a single variable and then checking it for the largest and smallest number with the max() and min() arguments.
I assume you haven't heard of lists yet.
The way I would solve it would be to use a list to store all the values and then applying the max(list) and min(list) built-in functions.
alln = list()
num=""
while num!='done':
num = input('Enter a number:')
try:
alln.append(float(num))
except:
print('invalid input')
print ('Maximum is',max(alln))
print ('Minimum is',min(alln))
Like this
Check this and this to understand the basics of lists and how to work with those two functions.
Now the problems with your code
1. You have several indentation errors.
for largest_num in [uval]:
if largest is not None or uval > largest:
^here, the 'if' should be inside the 'for' block and it wasn´t. You have this problem twice in your code
while True:
num = input('Enter a number:')
uval = float(num)
if num == str:
elif num == str('done'):
^here, all four need an extra space to be properly indented
2. Because of this
num = input('Enter a number:')
uval = float(num)
When you write "done", you get another error. Try doing this instead:
while True:
if num == 'done':
break
#check if it's not a number
else:
num = float(num)
#store the value as a float
That way you can avoid converting a string to a float, which is why you are getting the error
Other problems I found
Both prints have indentation errors. But assuming that's just a typo, the indentation itself will make the loop print every single time it runs because it's inside the 'for' block.
str('done') this doesn't work because str() will transform the argument to a string. Remember that 'done' is already considered a string by python, so you can just write num == 'done'
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)
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)
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.
I wanna write a program that repeatedly prompts a user for integer numbers until the user
enter 'done' and once 'done' is entered, print out the largest and smallest of the numbers
I programmed as below. but I can not figure out How to fix this programming
largest = None
smallest = None
inp = raw_input("Enter a number: ")
if inp == "done" : break
if len(inp)<1 : break
try:
num=float(inp)
except:
print "Invalid input"
continue
if num<smallest:
smallest=num
print smallest
if num>largest:
largest=num
print largest
print "Maximum is", largest
print "Minimum is", smallest
Your program is missing a loop. You need to put
while True:
on line 3.
You call break but you don't seem to be inside a loop.