I'm trying to find the smallest and largest numbers, but the output of the program is incorrect. The smallest is the largest in the output and the largest is always 1 smaller than the largest. I entered 2, 4, 6, 8, heres the output:
Enter a number: 2
Enter a number: 4
Enter a number: 6
Enter a number: 8
Enter a number: done
('largest is', 7)
('smallest is', 8)
And here's the code:
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
try:
halo = int(num)
except:
print("invalid input")
continue
for largest in range(halo):
if largest is None:
largest = halo
elif largest > halo:
largest = halo
for smallest in range(halo):
if smallest is None:
smallest = halo
elif smallest<halo:
smallest = halo
print "largest is",largest
print "smallest is",smallest
You are always assigning a value to largest
and smallest
because you use them as targets in a for
loop:
for largest in range(halo):
In the above, largest
will be assigned 0
, then 1
, then 2
all the way up to the last number for halo
.
Next, you have your <
and >
comparisons the wrong way around; you are only updating largest
if halo
is smaller . Invert your tests.
You don't need any loops at all here, your while True
loop is your looping construct. Just test halo
directly against largest
and smallest
:
try:
halo = int(num)
except:
print("invalid input")
continue
if largest is None or halo > largest:
largest = halo
if smallest is None or halo < smallest:
smallest = halo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.