I am trying to do this program that asks the user to input and you select the minimum and maximum of the numbers you put in the problem is it does find the maximum but the minimum shows up as None, any help on this? I just want to understand why None is lower than the numbers I type isn't None suppose to mean that the variable doesn't have any value until num is replaced by the user? thanks.
smallest = None
largest = None
while True:
num = raw_input('Enter the values: ')
if num == 'done' : break
if len(num) < 1 : break
try:
num = int(num)
except:
print 'Invalid input'
continue
if num is None or smallest > num :
smallest = num
if num is None or num > largest :
largest = num
print 'Maximum is',largest
print 'Minimum is',smallest
Python comparisons between different types aren't particularly meaningful. Instead of using None as your sentinel, use a large or small number:
smallest = 1e100
largest = -1e100
Related
I was trying to do a simple task, a script that figures out which of numbers inputed were largest of smallest. Here is the code:
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 is None :
smallest = num
elif:
smallest > num
smallest = num
if largest is None :
largest = num
elif :
largest < num
largest = num
print("Maximum", largest)
When I am trying to run the code, it tells me 'ParseError: bad input on line 15'
Could anybody help me?
The correct syntax for elif is the same as for normal if statements:
Instead of:
elif:
smallest > num
smallest = num
Do:
elif smallest > num:
smallest = num
Same for your other elif further down.
I had an assignment, where I let users choose random numbers, and this program would find the smallest and the largest between all these numbers, and if a number is not entered it would consider it an invalid input.
Here's the code I wrote:
largest = None
smallest = None
while True:
inp = raw_input("Enter a number: ")
if inp == 'done': break
if len(inp) < 1: break
try:
num = int(inp)
except:
print "Invalid input"
continue
if smallest is None:
smallest = num
elif inp < smallest:
smallest = num
if largest is None:
largest = num
elif inp > largest:
largest = num
print "Maximum is %r" % (largest)
print "Minimum is %r" % (smallest)
The question is, why is it not working ?
Here's some random numbers I tried and got something weird.
Here I executed the code in the first part and got weird answers, and I executed it again with different numbers and got it right.
You've mixed up < and > and you're comparing inp which is a string to smallest and largest instead of num.
Your indentation is wrong and you made a lot of misprints. Look at this code.
In if-then-else you have to compare num with smallest and largest but not inp.
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
print num
if smallest is None: smallest = num
elif num < smallest: smallest = num
if largest is None: largest = num
elif num > largest: largest = num
print "Maximum is %r" % (largest)
print "Minimum is %r" % (smallest)
I'm new to Python (or any coding really) and need to return max and min values from array entered by user. I can get it to return the max no problem, but min gives me <unknown> message back. Can anybody help me fix the code for my min return? Thanks.
Here is my code:
maximum = None
minimum = None
while True:
#enter the input
inp = raw_input("Enter a number:")
#handle the edge cases
if inp == "done" :
break
if len(inp) < 1 :
break
#only accept good input
try:
num = int(inp)
#print num
except:
print "Invalid input"
continue
#do the work
if num > maximum :
max = num
if num < minimum :
min = num
else:
num
print "Maximum is", max
print "Minimum is", min
Try to initialise minimum and maximum to a number and not None.
Compare as INT values , here you are doing as strings
You can take two approaches, here. First, you can explicitly check for None in your code. The second, as mentioned by #minatverma, is to initialize your min/max values to some "cannot be reached" values.
Option 1:
Replace this code ...
#do the work
if num > maximum :
max = num
if num < minimum :
min = num
else:
num
With this code:
#do the work
if minimum is None:
# First time, only
minimum = num
maximum = num
elif num > maximum:
maximum = num
elif num < minimum:
minimum = num
Option 2:
You will need to add the following line at the top of your code:
import math
Then, replace this code:
maximum = None
minimum = None
With this:
maximum = -math.inf
minimum = math.inf
The rest of your code can stay the same.
Try to put all entered numbers into a INT list (array) and then use built-in min() and max() functions...
from __future__ import print_function
nums = []
while True:
#enter the input
inp = input("Enter a number:")
#handle the edge cases
if inp == "done" or not len(inp):
break
#only accept good input
try:
nums.append(int(inp))
except ValueError:
print("Invalid input")
continue
print("Maximum is", max(nums))
print("Minimum is", min(nums))
So I submitted this for a Cousera course on basic python (I'm very very new to writing code). It worked. However, I found a bug in it (which I'm both glad I can see and heartbroken because it exists).
The problem is that if the smallest number in a string of numbers is the first number given it gets absorbed by the largest variable and not into the smallest variable. How would I prevent this from happening?
Thanks in advance!
Code below:
largest = -1
smallest = None
while True:
try:
num = raw_input('number\n')
float(num)
if num > largest:
largest = num
elif smallest is None:
smallest = num
elif smallest > num:
smallest = num
except:
if num =="Done":
print "Maximum is", largest
print "Minimum is", smallest
break
print "Invalid input"
Welcome to the world of programming!
Usually when I do min/max comparisons, I start with negative and positive infinity and not None/null or the first element of the list as that has given me headaches in the past.
This code seems to work fine to me.
largest = float("-inf")
smallest = float("inf")
while True:
try:
num = raw_input('number: ')
num = float(num) # I reassign num for good-measure
if num > largest:
largest = num
if num < smallest:
smallest = num
except:
if num == "Done":
print "Maximum is", largest
print "Minimum is", smallest
break
print "Invalid input"
Purely as an educational exercise, you could use some of python's features (generators) to make this code more generic.
This creates a generator called numbers which returns a sequence of input numbers, that is collected as a list in a and then you can use the builtin min(a), max(a) methods:
def numbers():
while True:
try:
num = input('number\n')
yield float(num)
except ValueError:
if num == "Done":
break
print "Invalid input"
a = list(numbers())
print "Maximum is", max(a)
print "Minimum is", min(a)
You should be able to solve this by setting smallest and largest to the first number input, and doing this before your while loop. That way, for every new number you see, you can update the values of smallest and largest depending on its relative magnitude. Something like this:
largest = -1
smallest = None
try:
num1 = raw_input('number\n')
smallest = num1
largest = num1
while True:
num = raw_input('number\n')
num = float(num)
if num > largest:
largest = num
elif smallest > num:
smallest = num
except:
if num =="Done":
print "Maximum is", largest
print "Minimum is", smallest
break
print "Invalid input"
I am very new to python, I write below few lines of code but not able to print smallest number from the input.
largest = 0
smallest = 0
while True:
num = raw_input("Enter a number:")
if num == "done" : break
try:
num = int(num)
except:
print "invalid"
continue
if num is smallest:
smallest = num
if num > largest:
largest = num
print "Minimum", smallest, "Maximum", largest
below is my output, it does print correct largest value (whatever i input) but smallest is always zero.
Enter a number:34
Enter a number:12000
Enter a number:dds
invalid
Enter a number:done
Minimum 0 Maximum 12000=====> see minimum is "0" should be 34?
That's the expected behaviour. In fact, your second statement reads:
smallest = 0
0 is less than 34, so smallest won't be updated.
A possible solution is initializing smallest and largest from the first element read:
largest = None
smallest = None
while True:
num = raw_input("Enter a number:")
if num == "done" : break
try:
num = int(num)
except:
print "invalid"
continue
if smallest is None: # or largest is None, it's the same
smallest = num
largest = num
if num < smallest:
smallest = num
if num > largest:
largest = num
print "Minimum", smallest, "Maximum", largest
Besides, you have what appears to be a typo or a misconception about the operator is. This:
if num is smallest:
smallest = num
Should be:
if num < smallest:
smallest = num