Problem: input()
returns a string, and strings are compared lexicographically. So you should convert it into an integer, you can do this with int(..)
:
num1 = int(input("Enter a number: "))
num3 = int(input("Enter a number: "))
num4 = int(input("Enter a number: "))
if (num1 < num3) and (num1 < num4):
print(num1)
elif (num3 < num4) and (num3 < num1):
print(num3)
else:
print(num4)
But nevertheless this is not a good way to calculate the minimum. What will you do if you have to calculate the minimum of 50 integers? Construct a hug amount of checks? Computer scientist Edsger W. Dijkstra once said:
"Two or more? Use a for
!" - Edsger W. Dijkstra
So in case you have to do work multiple times, you better use a for
loop to handle that. The skeleton of such code fragment looks like:
for i in range(3):
# ...
pass
The body of the for
loop (here ...
) will be repeated three times. Now what work can we put into the for
loop? Of course we can query the user for input. So we can write:
for i in range(3):
number = int(input("Enter a number: "))
# ...
but now we still have to calculate the minimum. A way to handle this is by using an accumulator: a variable that is maintained through iteration, and updated accordingly. Here an accumulator can be the thus far obtained minimum. Since initially we have no minimum, we can initialize it with None
:
thus_far_minimum = None
for i in range(3):
number = int(input("Enter a number: "))
# ...
Now in case thus_far_minimum
is None
, we can assign the number
we have queried from the user. Furthermore in case thus_far_minimum
is no longer None
(so it is initialized), but number
is less than thus_far_minimum
, we can alter thus_far_minimum
such that it now has the minimum. For example:
thus_far_minimum = None
for i in range(3):
number = int(input("Enter a number: "))
if thus_far_minimum is None or number < thus_far_minimum:
thus_far_minimum = number
print(thus_far_minimum)
at the end we can print the thus_far_minimum
since it is the minimum over all the numbers we have seen.