0

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)
Yolanda Hui
  • 97
  • 1
  • 1
  • 8

3 Answers3

2

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
Rahul Agarwal
  • 4,034
  • 7
  • 27
  • 51
ThisIsMyName
  • 887
  • 7
  • 14
  • This works but it also allows suspicious inputs to go through, such as `3foo`, which might be valid or not depending on the OP's use cases. – Matias Cicero Oct 15 '18 at 12:41
1

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.

toti08
  • 2,448
  • 5
  • 24
  • 36
1

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)
blhsing
  • 91,368
  • 6
  • 71
  • 106