PYTHON: Can't store value in variable, stays None - python

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))

Related

Why is my code not displaying the correct max when I type in "bob" in between other numbers?

largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
print(num)
if smallest is None :
smallest = num
elif num < smallest :
smallest = num
print(smallest, num)
if largest is None:
largest = num
elif num > largest:
largest = num
print(largest, num)
except:
print("Invalid input")
continue
print('Max', largest)
print("Minimum", smallest)
Asked to find the largest and smallest number from the input but if you type in a non number it mistakes that as the max value instead of calling it a "invalid input". Help?
It has to do with the fact that the value of "num" is being treated like a string. If you want to trigger an error exception refer to a revised version of your code with the attempted population of a numeric variable.
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
print(num)
x = int(num) # Add this in to force an error exception
if smallest is None :
smallest = num
elif num < smallest :
smallest = num
print("Smallest:", smallest, num)
if largest is None:
largest = num
elif num > largest:
largest = num
print("Largest:", largest, num)
except:
print("Invalid input")
continue
print('Max', largest)
print("Minimum", smallest)
That should provide the error condition you are after.
The problem is that you are trying to compare strings, instead of integers. When you compare strings, Python uses lexical order to compare them.
print("100" < "2") # Prints "True", because "1" is lower than "2" in lexical order
If you compare integers instead, then Python will use numerical order, which is what you expect here.
print(100 < 2) # Prints "False", because 100 is greater than 2
To fix this, you can convert your input to a integer before comparing it. This should be done after checking whether the input equals "done", because "done" cannot be converted to an integer.
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
print(num)
num = int(num)
if smallest is None :
smallest = num
elif num < smallest :
smallest = num
print(smallest, num)
if largest is None:
largest = num
elif num > largest:
largest = num
print(largest, num)
except:
print("Invalid input")
continue
print('Max', largest)
print("Minimum", smallest)
Also, if you want to allow fractional numbers like 1.2, then you can use float instead of int.
num = float(num)
You should specify the type of exception you're looking for, and limit the window the exception can occur in as much as possible, this helps with trying to debug situations like this:
largest = None
smallest = None
while (num := input("Enter a number: ")) != 'done':
try:
num = float(num)
except ValueError:
print("Invalid Input")
continue
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
if largest is None:
largest = num
elif num > largest:
largest = num
print('Max:', largest)
print("Minimum:", smallest)

I have a problem with arranging None and input data to find largest and smallest value using python

Edit: Here are the test values (7, 2, bob, 10, and 4) and desired output
Invalid input
Maximum is 10
Minimum is 2
for people who want them :)
Hello! So I got this problem where I have to take input from user and then when the type done the largest and smallest values come out. There was a small part where if you put wrong data it will tell you that but I got that "done" perfectly. But the part where I have to decide as largest and smallest is my issue. I setup Nonetype for each of the values but when i put it in the if statements it simply selects the first input as largest. I have attached my code below. Any modification could be of help. Thank you.
Largest = None
Smallest = None
while True :
num = input("Enter a number: ")
if num == "done" :
break
try :
fnum = int(num)
except :
print("Invalid input")
continue
if Largest is None:
Largest = fnum
elif Smallest is None:
Smallest = fnum
elif fnum > Largest:
fnum = Largest
elif fnum < Smallest:
fnum = Smallest
print("Maximum is",Largest)
print("Minimum is",Smallest)
Ideally, you can go with == (equals to) for the comparison between None
x = None
y = None
print(x is y)
print(x==y)
prints
True
True
Now, you have all the conditions as if and elif, so every time in the first iteration the Largest is assigned (because that is the first True condition) and in the second iteration Smallest is assigned (because that is the second True condition) and this logic may not be the case always.
What you can do is, set the largest and smallest at the same time, i.e have the same reference point before the comparison.
Finally, you are not updating the smallest and the largest but doing it reverse (as pointed out in the comments).
Stitching it all together,
Largest = None
Smallest = None
while True :
num = input("Enter a number: ")
if num == "done" :
break
try :
fnum = int(num)
except :
print("Invalid input")
continue
if Largest == None or Smallest == None:
Largest = fnum
Smallest = fnum
elif fnum > Largest:
Largest = fnum
elif fnum < Smallest:
Smallest = fnum
print("Maximum is",Largest)
print("Minimum is",Smallest)
If you want to keep the Largest and Smallest as None you could perform a conditional expression to assign the values. This would result the first value being assigned to both Largest and Smallest and then only to Smallest of Largest if the value is bigger or smaller.
This is not the most optimized way to do this but it gets the job done.
Largest = None
Smallest = None
while True :
num = input("Enter a number: ")
if num == "done" :
break
try :
fnum = int(num)
except :
print("Invalid input")
continue
Largest = fnum if Largest is None else fnum if fnum > Largest else Largest
Smallest = fnum if Smallest is None else fnum if fnum < Smallest else Smallest
print("Maximum is", Largest)
print("Minimum is", Smallest)
Output with single number.
Output with your numbers.
There is so many ways that you can do this. You should try using an array.
First, you create an array which will store all the numbers. If the user type "done", you store the maximun and the minimun number for the array in two variables. Really simple.
numbers = []
while True :
num = input("Enter a number: ")
if num == "done" :
break
try:
num = int(num)
numbers.append(num)
except:
print("Invalid input")
continue
Largest = max(numbers)
Smallest = min(numbers)
print("Maximum is", Largest)
print("Minimum is", Smallest)

How do I avoid unwanted assignment in loops when using comparison operators?

This is my code which iterates and takes inputs as the number and when user input "done", it comes out of loop and print smallest and largest of the input numbers.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
a = int(num)
except:
print("Invalid input")
if largest is None:
largest = num
if smallest is None:
smallest = num
if smallest > num:
smallest = num
if largest < num:
largest = num
print(smallest, largest) #for dry run
print("Maximum is", largest)
print("Minimum is", smallest)
Now my problem is whenever I input a non-number such as bob, it gets assigned to largest and print maximum number as bob.
You are acknowledging that int(num) failed, but then using the value of num (rather than a) anyway. You could continue the loop instead. With correct indentation, your code should look something like
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
a = int(num)
except ValueError:
print("Invalid input")
continue
if largest is None:
largest = a
if smallest is None:
smallest = a
if smallest > a:
smallest = a
if largest < a:
largest = a
print(smallest, largest) #for dry run
print("Maximum is", largest)
print("Minimum is", smallest)

Intro to Python HW assignment

Instructions: 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:
num = int(num)
except:
print('Invalid input')
continue
if smallest is None or num < smallest :
smallest = num
elif largest is None or num > largest :
largest = num
print("Maximum is", largest)
print("Minimum is", smallest)
So after inputting 7, 2, bob, 10, and 4, and then entering done, the code will not print out the max and min numbers as I have coded in the last two lines. Where is my mistake?
Thanks
You can append the numbers to a list and use built-in methods to do that for you, min() and max(). For example:
my_list = []
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
num = int(num)
my_list.append(num)
except:
print('Invalid input')
continue
largest = max(my_list)
smallest = min(my_list)
print("Maximum is", largest)
print("Minimum is", smallest)
It will not work in a case where the largest integer is the first input. You could try to initialize the largest and smallest variable to the first input to solve it.
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 largest is None:
largest,smallest = num,num
elif num < smallest :
smallest = num
elif num > largest :
largest = num
print("Maximum is", largest)
print("Minimum is", smallest)

why the two variables not getting the new value?

I'm trying to assign a value to the two starting variables in the following code, and change them if necessary (first if and elif), but the smallest gets changed to the string "done" while the largest stays untouched. what am I missing ?
Thank you very much
largest = 0
smallest = 999
while True:
num = raw_input("Enter a number: ")
if largest > num:
largest = num
elif smallest < num:
smallest = num
try:
num = int(num)
except ValueError:
print "Invalid input"
if num == "done" : break
print "Maximum is", largest
print "Minimum is", smallest
Edited the code as per suggestions as follow:
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
try:
num = int(num)
if num > largest:
largest = num
elif smallest < num:
smallest = num
except ValueError:
print "Invalid input"
if num == "done" : break
print "Maximum is", largest
print "Minimum is", smallest
Now it runs correctly

Categories

Resources