The assignment So heres the problem, i have a to write a program thats takes input from user until he writes "done". When that happens, i should take the biggest and smallest value and print them out.
The problem When i write "done" it tells me that i cant compare an str to a int, and also, it doesnt store every value i wrote in my input() function.
The code
while True:
number = input("Enter number:")
if number == "done":
break
largest = None
for value in number:
if value > largest or largest is None:
largest = value
print("after:", largest)
smallest = None
for value in number:
if value < smallest or smallest is None:
smallest = value
print("after",smallest)
CodePudding user response:
you overwrite number
at each loop cycle. Use a container to hold the numbers:
numbers = []
while True:
number = input("Enter number:")
if number == "done":
break
else:
numbers.append(int(number))
print(numbers)
output:
Enter number:1
Enter number:2
Enter number:3
Enter number:done
[1, 2, 3]
NB. I also assume you want to use integers, so I provided the conversion (this will fail if you enter anything else than an integers). Also, as your task is simple (min/max) and doesn't need to know the further numbers in advance, I would recommend to compute those min/max in the while loop. This will be more efficient than reading again 2 times the list (see below).
numbers = [] # not needed if you don't want the list as output
smallest = float('inf')
largest = float('-inf')
while True:
number = input("Enter number:")
if number == "done":
break
else:
number = int(number)
numbers.append(number) # not needed if you don't want the list as output
if number > largest:
largest = number
if number < smallest:
smallest = number
print(numbers, smallest, largest)
output:
Enter number:1
Enter number:3
Enter number:2
Enter number:done
[1, 3, 2] 1 3
CodePudding user response:
I would suggest using min/max, like this:
numbers = []
while True:
ans = input("give me a number: ")
if not ans or ans == "done":
break
try:
ans = int(ans) # we dont want to add this if it's not really a number
numbers.append(ans)
except:
print("please give me an integer!")
print(numbers,min(numbers),max(numbers))