I have the next exercise:
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.
And this is the code i have developed so far but i still can't get it to work properly. I accept any corrections needed. Thank you.
largest = None
smallest = None
while True:
value = input('Enter a Number: ')
if smallest is None:
smallest = value
elif smallest < value:
smallest = value
if largest is None:
largest = value
elif largest > value:
largest = value
if value == 'done':
break
try:
fvalue = float(value)
except:
print('Invalid input')
continue
print(f'Maximun is', max(largest))
print(f'Minimun is', min(smallest))
Your code has several problems and some of those have been addressed in the comments.
The first thing your code should do is to check, if "done" was entered so that we can break the loop. Then you should try to convert the number to an integer (you used float) and display an error message if there was a ValueError. You have to convert the value before you do the comparison because otherwise the comparison will be lexicographically. Then you have to change the comparisons. You want to set a new number to smallest if smallest is bigger than the current value, not the other way round. And the last thing: Using max and min on a single value doesn't make sense.
This gives us:
largest = None
smallest = None
while True:
value = input('Enter a Number: ')
if value == 'done':
break
try:
value = int(value)
except ValueError:
print('Invalid input')
continue
if smallest is None or smallest > value:
smallest = value
if largest is None or largest < value:
largest = value
print(f'Maximum is', largest)
print(f'Minimum is', smallest)
I think you went in a wrong way when you've chosen to use a contraction like that with if/else
for that task it's better to use something like this
a = set()
while (inp := input('Enter a Number: ')) != 'done':
try:
if str(inp).isnumeric() != True:
raise
a.add(inp)
except Exception as ex:
print(f'your "{inp}" is not appropriate')
print(f'max == {max(a)}', f', min == {min(a)}')
set() stores unique values only
it's easy to get max an min from set() by built-in functions max() and min()
so we just need not to allow to our set anything but numbers - here it's done by while loop and try/except inside it
it's easy to read and to change cuz it's without redundancy
Related
the inputs are 7,2,bob,10, and 4. The output is supposed to be:Invalid input,Maximum is 10,Minimum is 2.
I initially had issues with 'None' not being able to be used with '<' until I used 'or'. Should you be kind enough to address this query, please talk to me like you would to a small pet or golden retriever. Thank you.
largest = None or 0
smallest = None or 0
while True:
num = input("Enter a number: ")
fval=float(num)
if fval is'bob':
print('invalid')
if largest is None:
fval>largest
largest=fval
if smallest is None:
smallest=fval
elif smallest<fval:
smallest=fval
if num == "done":
break
print(fval)
print("Maximum", largest, "Minimum",smallest)
You would get error if you convert string which is not float to float type.
Here you can use try except to try to convert and in case of error print invalid.
This code would solve your problem:
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num=="done":
break
try:
fval=float(num)
largest=fval if largest is None else max(largest,fval)
smallest=fval if smallest is None else min(smallest,fval)
except:
print('invalid')
print("Maximum", largest, "Minimum",smallest)
Error is very explanatory. In the second line inside the while loop, you are trying to turn the string "bob" to a floating point number.
fval = float("bob")
Python is unable to do this so it raises a ValueError.
One way to get around this is with try and except. This approach makes Python do something, and if that "something" raises an error, it jumps to the except part.
try:
float("bob")
except ValueError:
print("invalid")
You can then continue your code below this piece as intended.
This is a better way to handle this. Use a try to catch EVERY invalid input, not just "bob".
largest = 0
smallest = 9999999
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
fval = float(num)
largest = max(fval, largest)
smallest = min(fval, smallest)
except ValueError:
print('invalid')
print("Maximum", largest, "Minimum",smallest)
You have 2 problems. Firstly, you need to ensure that the input can be converted to a float. This can be done using a try catch block.
try:
fval=float(num)
except:
print("Cannot convert to float")
Secondly, it is easier to just set the first value as smallest/largest then do your checks. You can monitor the first value using a boolean flag (e.g. True/False variable named 'firstNumber')
firstNumber = True
while True:
num = input("Enter a number: ")
try:
fval=float(num)
if firstNumber:
firstNumber = False
smallest = largest = fval
elif fval<smallest:
smallest=fval
elif fval>largest:
largest=fval
print(fval)
except:
if num == "done":
break
else:
print('invalid')
print("Maximum", largest, "Minimum",smallest)
Note: There were a few bugs in your code as well.
Also, do you really need a float if your inputs are all integers?
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)
I am trying to learn Python through a course on Courser, and so far having a feeling I am not going to be able to.
I don't want an answer to the assignment, I want someone to push me in the right direction. Because Im stuck and the online tutors there are not being any help just repeating the obvious that is already stated in the assignment. The assignment is very simple, but I cant understand what I am missing.
Here is the assignment:
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 the numbers from the book for problem 5.1 and Match the desired output as shown.
Here is my code, i tried using the example codes we where show for getting the minimum and maximum, but the problem is in the examples we had they had lists, here I was told I dont need a list. But everytime the value of num changes with ever new input, how can i get the program to choose from certain numbers if they are not storing...or do you think i can enter lists in the raw_input?
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
largest = None
if largest is None:
largest = num
elif num > largest:
largest = num
smallest = None
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
print "Maximum is", largest
print "Minimum is", smallest
The numbers from the book are 4, 5, 7 and a word
Thank you everyone for your support, I understand what I have to do, not sure if I understand how I will get there, but Im going to sit and keep trying. Meanwhile I am getting issues with indentation
let's say I rewrote the code like this and want to add an if statement into the while loop
largest = None
smallest = None
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
should the if statement start with the same indent as the continue and then the inside of the if indented again?? Because Im getting errors when I do that
largest = None
smallest = None
while True:
inp = input("Enter a number: ")
if inp == "done" : break
try:
num = float(inp)
except:
print ("Invalid input")
continue
if smallest is None:
smallest=num
if num > largest :
largest=num
elif num < smallest :
smallest=num
def done(largest,smallest):
print("Maximum is", int(largest))
print("Minimum is", int(smallest))
done(largest,smallest)
this will surly work.
You're on the right track with your current implementation, but there is some issues in the order of your operations, and where the operations are taking place. Trace through your program step by step, and try to see why your None assignment may be causing some issues, among other small things.
You are being asked to keep a running max and running min, the same way you could keep a running total. You just update the running <whatever> inside the loop, then discard the user's most recent input. In the case of running total, the code would look like tot = tot + newinput and you could then discard newinput (or, more likely, reuse it) without recording it in a list or any other data structure.
Not every problem permits a "running" solution. For instance, if you wanted to give the user an undo feature, letting them back out some of the numbers they entered earlier, you would have to keep an exact history of all the numbers. But here, you can get by without keeping that data.
You should check for the largest and smallest numbers inside the loop. First check if its a number - if yes, carry on and see if it is bigger than your current largest variable value (start with 0). If yes, replace it. See, if its smaller than your smallest value (start with the first number that comes in, if you start with 0 or just a random number, you might not get lower that that. If you start with the first number, then it'll definitely be the smallest (after all the loops)), etc, etc. All of that should be done inside the loop and after the loop should be just the printing. And yes, you don't need to use lists.
Let me give you a hint here, every time your while loop takes in a input, it sets the values of largest and smallest to None. Where should you initialize them?
I sense that your confusion partly stems from how the user is expected to give the input. One could interpret the instructions in two ways.
The user writes 4 5 7 randomword [ENTER]
The user writes 4 [ENTER] 5 [ENTER] 7 [ENTER] randomword [ENTER]
If it was the first variant, then you might be expected to process the whole thing as a list and determine its parts
However, the fact that they told you "you will not need lists for this exercise" implies that they expect the second scenario. Which means you should design your while loop such that at each iteration it expects to receive a single input from the user, and do something with it (i.e. check if it's bigger / smaller than the last). Whereas the loop you have now, will simply always keep the last input entered, until "done" is encountered.
Once you're out of the while loop, all you need to do is present the variables that you've so carefully collected and kept updating inside the loop, and that's it.
I figured it out I think, and the thing that was killing my code was the continue statement if I am not wrong
here is what i got, and please leave comments if I got it wrong
largest = None
smallest = None
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
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
largest = None
smallest = None
while True:
inp = input("Enter a number: ")
if inp == "done" : break
try:
num = float(inp)
except:
print ("Invalid input")
continue
if smallest is None:
smallest=num
if num > largest :
largest=num
elif num < smallest :
smallest=num
def done(largest,smallest):
print("Maximum is", int(largest))
print("Minimum is", int(smallest))
done(largest,smallest)
maximum = -1
minimum = None
while True:
num = input('Enter the num: ')
if num == 'done':
break
try:
num1 = int(num)
except:
print('Invalid input')
continue
if minimum is None:
minimum = num1
if num1 > maximum:
maximum = num1
elif num1 < minimum:
minimum = num1
print('Maximum is', maximum)
print('Minimum is', minimum)
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:
largest=n
if n > largest:
largest=n
if smallest is None:
smallest=n
elif n < smallest:
smallest =n
print("Maximum is", largest)
print("Minimum is" , smallest)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
smallest = None
largest = None
while True :
number = raw_input('Enter a number from -10 to 9: ')
if largest < number :
largest = number
if smallest is None :
smallest = number
elif number < smallest :
smallest = number
if number == 'done': break
print 'Largest number is: ',largest
print 'Smallest number is ',smallest
I have no idea why my "smallest" is alright while "largest" outcome is always done. I think that "break" is somehow affecting it. Could You point out my mistake?
The problem is that you are first updating smallest and largest even if the user entered done. So first of all, you should check whether the input is 'done' and abort immediately before updating any of your numbers.
That being said, there are multiple other issues with your code:
if largest < number – You are updating largest if the number is smaller than the previously stored one, making it have the same logic as smallest. Of course, you will not end up with the largest number that way.
raw_input() returns a string, not a number. So if the user types for example 5, then what raw_input() returns is the string '5'. So every comparison you make is a string comparison (e.g. '2' < '5'). Because string comparisons are based on character codes, this will incidentally work for single-digit numbers but you should really convert the strings into proper numbers first.
You mention an allowed range of -10 to 9 but you never actually enforce that.
Something like this will work:
smallest = None
largest = None
while True:
number = raw_input('Enter a number from -10 to 9: ')
if number == 'done':
break
# convert into a number
try:
num = int(number)
except ValueError:
print('That was not a valid number')
continue # restart the loop
# validate the number range
if num < -10 or num > 9:
print('The number is out of the allowed range')
continue
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
print 'Largest number is:', largest
print 'Smallest number is:', smallest
If you encounter done, your loop should break immediately. But in your codes, you have put the break at the end. So before that, previous logic is being executed. And done as a string can be compared.
>>> None < 'done'
True
>>>
So your largest is set to done since largest < None in that case.
Quick Fix
We now moved the break on top, so this should fix the issue:
smallest = None
largest = None
while True :
number = raw_input('Enter a number from -10 to 9: ')
if number == 'done':
break
if largest < number :
largest = number
if smallest is None :
smallest = number
elif number < smallest :
smallest = number
print 'Largest number is: ',largest
print 'Smallest number is ',smallest
Handling Numbers
The raw_input returns string. But we want to compare numbers. So we should convert the inputs to int.
try:
num = int(number)
except ValueError:
print('Please enter a valid integer')
continue # skip the input and continue with the loop
I try to use python to prompt user to enter different number, and keep the largest one, and finish when user enter "done". but I find out it can not work with different digit of number. for example, 1st entry: 91, 2nd:94, it will run well. but 1st entry:91 and 2nd:100, it can not record 100 as the largest number. did somebody know what's going on? thank you so much!
code:
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done":
break
try: int (num)
except:
print "Please enter a numeric number"
if largest is None and smallest is None:
largest = num
smallest = num
#print "l", largest
#print "s", smallest
if num > largest:
largest = num
print largest, num
#if num < smallest:
# smallest = num
# print "s2", smallest
print num
print "Maximum is ", largest
#print "Minimum is ", smallest
you're doing ASCII comparisons, not numeric. you need to actually assign something like number = int(num) and use number for comparison.
The problem is you're not converting num to an integer, so it's using string comparison rather than numeric comparison. Change:
try: int (num)
to:
try:
num = int(num)
You've got a number of problems. Take a look at this, maybe you can incorporate it into your own code?
largest = 0
while True:
prompt = raw_input("Enter a number: ")
try:
num = int(prompt)
if num > largest:
largest = num
except:
if prompt == 'done':
break
print largest
raw_input returns a string. So when you compare num > largest you are using string (alphabetical) comparison. You want to compare numbers. The easiest way would be to simply rewrite the comparion to int(num) > int(largest).
try: int (num) ... already checks if the input is a number but it does not change the value of the variable.
Note: except without an exception type is generally not a good idea. You should explicitly write down the exception you want to catch: ValueError