why the two variables not getting the new value? - python

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

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)

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)

Coursera Python: Programming for everybody assignment 5.2

I have been taking Coursera's course, Programming for Everybody with Python. But one of the assignment 5.2 on week 7 got my attention.
The objective is to make the user enter some numbers and enter done, when he entered all the numbers he wanted. After that, the output should be the biggest number and smallest number he entered.
Here is the problem. If I enter a negative number it is not displayed. Let's say I enter: 32, 55,10, -2 76. The output should be 76 and -2. But what really happens is that 76 and 10 are printed out.
Do you guys have any idea why this happens?
Here is the code.
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
print (num)
num = int(num)
for number in range(num):
if largest is None or largest < num:
largest = num
continue
elif smallest is None or smallest > num:
smallest = num
except ValueError:
print("Please, enter only numbers.")
print ("Maximum", largest)
print ("Minimum", smallest)
Well,the issue is that why are you iterating over an int if it isnt a list?
You can rather do it with out a loop:
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
print (num)
num = int(num)
if largest is None or largest < num:
largest = num
elif smallest is None or smallest > num:
smallest = num
except ValueError:
print("Please, enter only numbers.")
print ("Maximum", largest)
print ("Minimum", smallest)
output:
Enter a number: 12
12
Enter a number: 56
56
Enter a number: 34
34
Enter a number: -2
-2
Enter a number: 17
17
Enter a number: done
Maximum 56
Minimum -2
Well, this was my answer. Try this. Let me know what you don't understand.
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done" :
break
num = int(num)
if largest is None or num > largest:
largest = num
elif smallest is None or num < smallest:
smallest = num
except ValueError:
print("Invalid input")
print("Maximum is", largest)
print("Minimum is", smallest)
This code will work for your assignment
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
# print (num)
num = int(num)
for number in range(num):
if largest is None or largest < num:
largest = num
continue
elif smallest is None or smallest > num:
smallest = num
except ValueError:
print("Invalid input")
print ("Maximum is", largest)
print ("Minimum is", smallest)

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

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

Categories

Resources