I have the following code that takes an input number, multiplies the first digit by 3 and then prints out the first digit. When I input 023, it gives me 6 instead of 0. Why is that?
a=int(input())
b=str(a)
c=int(b[0])*3
print(c)
I have the following code that takes an input number, multiplies the first digit by 3 and then prints out the first digit. When I input 023, it gives me 6 instead of 0. Why is that?
a=int(input())
b=str(a)
c=int(b[0])*3
print(c)
You are doing:
a=int(input())
So if input() = '023', int('023') will be 23. So a=23
b=str(a) => b='23'
int(b[0]) => c=2*3=6
You should do:
a=input()
then
c=int(a[0])*3
If you want to keep all the digits you're entering you shouldn't convert your input into an int
:
a=input('Enter a number: ')
c=int(a[0])*3
print(c)
If you enter 023
this returns 0
.
You can use a while
loop to keep asking the user for digit-only input until the user enters one, and you should use the list()
constructor to convert the digits to a list:
while True:
a = input('Enter digits: ')
if a.isdigit():
break
print('Please enter only digits.')
b=list(a)
c=int(b[0])*3
print(c)