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.
Related
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 new in Python and doing an online tutorial. I have an assignment that I can not accomplish. My problem is that when I run this code, the minimum variable stays the same to None and does not record the new value input.
maximum = None
minimum = None
while True:
try:
num2 = raw_input('Type here ')
if num2 == 'done':break
else:
num = int(num2)
if num <= minimum:
minimum = num
print minimum
elif num >= maximum:
maximum = num
print maximum
except:
print 'Invalid Entry'
print 'Maximum is %d' % maximum
print 'Minimum is %d' % minimum
import sys
maximum = None
minimum = sys.maxsize
while True:
try:
num2 = raw_input('Type here ')
if num2 == 'done':break
else:
num = int(num2)
minimum = min(minimum, num)
maximum = max(maximum, num)
except:
print 'Invalid Entry'
if maximum is None:
minimum = None
print 'Maximum is %d' % maximum
print 'Minimum is %d' % minimum
You are comparing None and int, Python does not know how to do that.
Instead, you should do:
maximum = float('-inf')
minimum = float('inf')
Any int would be greater than -infinity and lower than infinity, so things will work fine. Same thing can not be said about zeroes, so don't use those.
Also, look up min and max builtins.
Your problem is that your are checking if (some number) <= None You cannot compare numbers with None. Instead, minimum=float("inf") and maximum=float("-inf") would set minimum to infinity, and maximum to negative infinity. That way, the first number entered would be less than infinity, setting it to minimum, and greater than negative infinity (setting it to maximum). Note that elif maximum >= num would need to be changed to if maximum >= num (to handle the first entered number).
I was tasked with creating a program that takes all the inputted numbers and adds them together except the highest integer out of that list. I am suppose to use while and if then logic but I cannot figure out how to exclude the highest number. I also had to make the program break when the string "end" was put into the console. So far I have,
total = 0
while 1 >= 1 :
value = input("Enter the next number: ")
if value != "end":
num = float(value)
total += num
if value == 'end':
print("The sum of all values except for the maximum value is: ",total)
return total
break
I just have no idea how to make it disregard the highest inputted number. Thanks in advance! I am using python 3 fyi.
Is this what you're trying to do?
total = 0
maxValue = None
while True:
value = input("Enter the next number: ")
if value != "end":
num = float(value)
maxValue = num if maxValue and num > maxValue else num
total += num
else:
print("The sum of all values except for the maximum value is: ",total-maxValue )
# return outside a function is SyntaxError
break
Here you go in regards to keeping it close to your original. Using lists is great in python for this sort of thing.
list = []
while True:
num = input("Please enter value")
if num == "end":
list.remove(max(list))
return sum(list)
else:
list.append(int(num))
if you input 1,2 and 3 this would output 3 - it adds the 1 and 2 and discards the original 3.
You've said it's an assignment so if lists aren't allowed then you could use
max = 0
total = 0
while True:
num = input("Please enter value")
if str(num) == "end":
return total - max
if max < int(num):
max = int(num)
total += int(num)
the easiest way to achieve the result you want is to use python's builtin max function (that is if you don't care about performance, because this way you are actually iterating over the list 2 times instead of one).
a = [1, 2, 3, 4]
sum(a) - max(a)
This not exactly the same as you want it to do, but the result is going to be the same (Since instead of not adding the largest item you can just subtract it in the end).
This should work for you.
total = 0
highest = None
while True:
value = input("Enter the next number: ")
if value != 'end':
num = float(value)
if highest is None or num > highest:
highest = num
total += num
else:
break
print("The sum of all values except for the maximum value is: ",total-highest )
print(total-highest)
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 trying to write this program which asks for numbers and stores the smallest and largest in two variables which are both None at the beginning.
Somehow the largest number is stored as I want it but the smallest number never makes it.
Here's my code:
largest = None
smallest = None
while True:
inp = raw_input("Enter a number: ")
if inp == "done" : break
try :
num = int(inp)
except :
print "Invalid input"
continue
if num == None or num < smallest :
num = smallest
if num == None or num > largest :
num = largest
print "Maximum is", largest
print "Minimum is", smallest
As soon as I typed in some numbers and end the program with "done" the output looks like this:
Maximum is 56
Minimum is None
I checked the indentation a couple of times.
Don't you mean :
if smallest is None or num < smallest :
smallest = num
if largest is None or num > largest :
largest = num
instead of :
if num == None or num < smallest :
num = smallest
if num == None or num > largest :
num = largest
Because nothing is ever stored in smallest nor largest in the code you posted and as pointed by #MartijnPieters None is always smaller than numbers in python 2.
You can check this link : Is everything greater than None? for further information on that subject.
Also I'd prefer using explicit except such as except ValueError: in you case rather than something that catches everything.
Largest and smallest are never assigned to.
And in the spirit of writing pythonically, you can use min and max :)
largest = None
smallest = None
a=[]
while True:
inp = raw_input("Enter a number: ")
if inp == "done" : break
try :
num = int(inp)
a.append(num)
except :
print "Invalid input"
continue
smallest=a[0]
for x in a:
if x<smallest:
smallest=x
largest=max(a)
print "Maximum is", largest
print "Minimum is", smallest
You can replace the for loop with smallest=min(a)
#d6bels Answer is correct, but you need to add:
if smallest == None:
smallest = num
if largest == None:
largest = num
all code applied:
largest = None
smallest = None
a=[]
while True:
inp = raw_input("Enter a number: ")
if inp == "done": break
try:
num = int(inp)
a.append(num)
except:
print("Invalid input")#For the sake of 2.x-3.x compatability, format your
if smallest == None: #prints as a function
smallest = num
if largest == None:
largest = num
smallest=a[0]
for x in a:
if x<smallest:
smallest=x
largest=max(a)
print("Maximum is " + str(largest))
print("Minimum is " + str(smallest))