Intro to Python HW assignment - python

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)

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)

Mismatch Error in Python even with perfect Output

I got this as my 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 7, 2, bob, 10, and 4 and match the output below.
Desired Output-
Invalid input
Maximum is 10
Minimum is 2
I wrote the following code for the same-
largest = None
smallest = None
count=0
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
fval=float(num)
count=count+1
if(fval == None):
largest=None
smallest=None
if(largest<fval):
largest=int(fval)
if(count==1):
smallest=fval
else:
if(int(fval) < smallest):
smallest=int(fval)
except:
print("Invalid input")
continue
print("Maximum is", largest)
print("Minumum is", smallest)
It is working fine too. I am able to fetch the smallest and largest entries. But, at the end, the editor is not accepting this code. Any possible error in the code logic?
Thanks for help in advance.
I believe there is a mismatch between your version of python and the version that the code judge runs to evaluate your code.
What's the difference? None can be compared to integers (actually, almost everything is comparable in python2). Look at this:
Python 2.x
In [211]: None < 123456
Out[211]: True
Python 3.x
In [152]: None < 123456
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-152-cf9ae210e7ad> in <module>()
----> 1 None < 123456
TypeError: unorderable types: NoneType() < int()
> <ipython-input-152-cf9ae210e7ad>(1)<module>()
----> 1 None < 123456
How does that matter to you? Well, for the first iteration, this line of code:
if(largest < fval):
Will compare fval with largest, which has an initial value of None.
Just another note, be wary about input in python2 vs python3. The two behave differently. The former will throw a NameError when you type a string.
I would recommend initialising your largest and smallest to valid values, like this:
largest = float('-inf')
smallest = float('inf')
I will use isinstance to check if the input is a integer and I will store all the elements in a listto, at the end of my program, call min and max.
Here's a code that works:
import ast
inputs = []
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
# Check if the input is a number
if num.isnumeric():
# If so, convert the string to a number
number = ast.literal_eval(num)
# If it's an int, store it in the list
if isinstance(number, int):
inputs.append(number)
else:
# If not, raise and exception
raise ValueError("Not an integer!")
except ValueError as ve:
print(ve)
# Show the desired output
print("Maximum is", max(inputs))
print("Minumum is", min(inputs))
Some advises:
Only put code in the try-block that you actually expect to raise the exception.
Do not do Pokemon Exception handling (Gotta catch 'em all). Only handle exceptions you actually expect.
Why do you (try to) convert the user input to float if you are requsted to check for integers?
float(num) will never be None, so checking for it does not make any sense.
Finally, I'd come up with:
if __name__ == '__main__':
minimum = maximum = None
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
try:
integer = int(user_input)
except ValueError:
print('Invalid input')
else:
if minimum is None or integer < minimum:
minimum = integer
if maximum is None or integer > maximum:
maximum = integer
print('Maximum is', maximum)
print('Minimum is', minimum)
The below code i wrote working fine in all the terminals, try this one it will work.
largest = None
smallest = None
cnt = 0
while True:
num = input("Enter a number: ")
if num == "done" : break
elif(num == ""):
print("InValid num")
break
try :
val = int(num)
#print(val)
#break
except ValueError:
val = -1
print("Invalid input")
continue
if cnt == 0 :
largest = val
smallest = val
elif val > largest :
largest = val
elif val < smallest :
smallest = val
cnt = cnt + 1
print("Maximum is",largest)
print("Minimum is",smallest)
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
n = int(num)
if smallest is None or n < smallest:
smallest = n
if largest is None or n > largest:
largest = n
except ValueError:
# num cannot be converted to an int
print ("Invalid input")
print("Maximum is", largest)
print("Minimum is", smallest)
largest = None
smallest = None
while True:
try:
num = raw_input("Enter a number: ")
if num == "done":
break
if largest is None:
largest = int(num)
if int(num) > largest:
largest = int(num)
if smallest is None:
smallest = int(num)
if int(num) < smallest:
smallest = int(num)
except:
print ("Invalid input")
print("Maximum is", largest)
print("Minimum is", smallest)
largest = 0
smallest = 999999
inval = "notdone"
x = 0
while True :
inval = input("Enter a number: ")
if (inval == "done") :
break
else :
try:
x = int(inval)
if (x > largest) :
largest = x
if (x < smallest) :
smallest = x
except :
print("Invalid input")
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)

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