Write a program whose inputs are three integers, and whose output is the smallest of the three values.
If the input is:
JavaScriptx417
215
33
4
The output is:
3
This is the code I have come up with:
JavaScript
1
14
14
1
num1 = input()
2
num2 = input()
3
num3 = input()
4
5
if (num1 < num2):
6
if (num1 < num3):
7
smallest_num = num1
8
elif (num2 < num1):
9
if (num2 < num3):
10
smallest_num = num2
11
else:
12
smallest_num = num3
13
print(smallest_num)
14
This code works for that input, however if you input “29, 6, 17” it returned no output with an error
JavaScript
1
2
1
NameError: name 'smallest_num' is not defined".
2
I have dinked around quite a bit and tried adding smallest_num = min(num1, num2, num3)
however nothing has yielded a passing output.
Advertisement
Answer
The issue is that input()
returns a string. So when you compare your variables, you’re doing string comparisons instead of numerical comparisons. So, you need to convert your input to integers.
JavaScript
1
6
1
num1 = int(input("Enter num1: "))
2
num2 = int(input("Enter num2: "))
3
num3 = int(input("Enter num3: "))
4
5
print(min(num1, num2, num3))
6