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"
Related
The purpose of this program is to have a user input numbers until they enter done, at which point the program outputs the maximum & minimum numbers. If the user enters something that is not a number, the program says "invalid input" and skips to the next time the loop runs. I have a try/except as well. This program is written in Python 3. when I run without the continue at the bottom, my screen freezes & I have to restart. With it, I get a pop-up saying SyntaxError: bad input on line 25.
largest = 0
largest = float(largest)
smallest = 0
smallest = float(smallest)
num = input('Enter a number: ')
num = float(num)
while True:
if num == "done":
break
try:
float(num)
except:
print('Invalid Input')
continue
if num > largest:
largest = num
if smallest == 0:
smallest= num
if smallest > num:
smallest = num
print(num)
continue
print("Maximum is", largest)
print("Minimum is", smallest)
Your input is outside of your loop so it only asks once and since it doesn't ever change its value to "done", it loops forever.
largest = 0
largest = float(largest)
smallest = 0
smallest = float(smallest)
# num = input("Enter a number: ")
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
num = float(num)
float(num)
except:
print("Invalid Input")
continue
if num > largest:
largest = num
if smallest == 0:
smallest = num
if smallest > num:
smallest = num
print(num)
continue
print("Maximum is", largest)
print("Minimum is", smallest)
It is a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered it prints out the largest and smallest of the numbers.
Custom Inputs are given as follow:
7
2
11
flip
10
4
done
Output:
Invalid Input
Maximum is 10
Minimum is 4
Expected Output:
Invalid Input
Maximum is 11
Minimum is 2
a=list()
while True:
sval=input()
if sval == "done":
break
try:
value=int(sval)
a.append(value)
except:
print("Invlid")
continue
def sml():
val=a[0]
for i in range(len(a)):
if a[i]<val:
smalles=a[i]
print("Minimum is",smalles)
def lge():
val=a[0]
for i in range(len(a)):
if a[i]>val:
larges=a[i]
print("Maximum is",larges)
lge()
sml()
Instead of finding the maximum and minimum value after appending to the array, you can find it before. This will reduce the cost of iterating the array each and every time to find the maximum and minimum.
a=list()
max_, min_ = float('-inf'), float('inf')
while True:
sval=input()
if sval == "done":
break
try:
value = int(sval)
if value > max_:
max_ = value
elif value < min_:
min_ = value
a.append(value)
except:
print("Invalid")
continue
print("Maximum is", max_)
print("Minimum is", min_)
Problems with your code
Why your functions are in while loop
Every time while finding small and large you are comparing with first value only
Solution
Below is smallest possible changed answer from your code.
a=list()
while True:
sval=input()
if sval == "done":
break
try:
value=int(sval)
a.append(value)
except:
print("Invlid")
continue
def sml():
smalles=a[0]
for i in range(len(a)):
if a[i]<smalles:
smalles=a[i]
print("Minimum is",smalles)
def lge():
larges=a[0]
for i in range(len(a)):
if a[i]>larges:
larges=a[i]
print("Maximum is",larges)
lge()
sml()
In these loops:
val=a[0]
for i in range(len(a)):
if a[i]>val:
larges=a[i]
you have two values, val and largest, when you really only want one (largest). The idea of finding a maximum value is that you want to be comparing against the largest value you've found so far, and constantly updating it each time you find a larger value.
A much shorter way of writing this code would be:
a = []
while True:
val = input()
if val == "done":
break
try:
a.append(int(val))
except ValueError:
print("Invalid")
print(max(a))
print(min(a))
Or, if you weren't allowed to use the max and min functions, you could simply maintain largest and smallest as you go, instead of keeping an array at all:
largest = None
smallest = None
while True:
val = input()
if val == "done":
break
try:
num = int(val)
except ValueError:
print("Invalid")
continue
if (largest, smallest) == (None, None):
largest, smallest = num, num
if largest < num:
largest = num
if smallest > num:
smallest = num
print(largest)
print(smallest)
In every iteration you are comparing with first element of list i.e val (val = a[0])
and not updating the val .
Modify
code
a=list()
while True:
sval=input()
if sval == "done":
break
try:
value=int(sval)
a.append(value)
print("Appended")
except:
print("Invlid")
continue
def sml():
print(a)
smalles=a[0]
for i in range(len(a)):
if smalles > a[i]:
print(a[i] , end=" ")
smalles=a[i]
print()
print("Minimum is",smalles)
def lge():
larges=a[0]
for i in range(len(a)):
if a[i]>larges:
larges=a[i]
print("Maximum is",larges)
lge()
sml()
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 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