0

In order to count digits of a number I write this code in python:

a=int(input('number: '))
count=0
while a!=0:
    a=a//10
    count=count+1

print('number has ',count,'digits') 

It works well for inputs like 13,1900,3222,.... But It give an error for numbers like: 3^21, 2^3,3*4,...

It say:

ValueError: invalid literal for int() with base 10: '3**21'

3**21 is integer input So why it gives this erroer,and How Should I fix this?

azro
  • 53,056
  • 7
  • 34
  • 70
amirali
  • 115
  • 3

4 Answers4

0

Neither '3^21' nor '3**21' are integers. They are strings with Python expressions that would evaluate to integers if the Python interpreter evaluated them.

>>> 3^21
22
>>> 3**21
10460353203

The int builtin only accepts strings such as '100', '22' or '10460353203'.

(int also has a base argument that defaults to 2 and allows you to issue commands like int('AA', 16), but it still does not allow you do pass the kind of string-expressions you are trying to pass.)

timgeb
  • 76,762
  • 20
  • 123
  • 145
0

You must eval() the expression first if you want an integer

eval('3**21')
# 10460353203

and to simply count digits (like digits number is string length) :

num_digits = len(str(eval('3**21')))

print(num_digits)
# 11

So your code could be :

a=input('number: ')
num_digits = len(str(eval(a)))

print('number has ',num_digits,'digits') 
Laurent B.
  • 1,653
  • 1
  • 7
  • 16
0

You can try

a=input('number: ') # entered 3**21
if a.isalnum():
    a = int(a)
else:
    exec("a = {}".format(a))
count=0
while a!=0:
    a=a//10
    count=count+1

print('number has ',count,'digits')

Output

number has  11 digits

This code will cast a to int only if a contained only digits else it will execute python command to store the expiration that entered to expiration and not int.

Leo Arad
  • 4,452
  • 2
  • 6
  • 17
0

The int() constructor accepts string representation of ints, which 2**5 is not, this is an math operation, you may use eval to compute that. I've add an additionnal variable value to keep track of the initial value and print it at then end

value = eval(input('number: '))
a = value
count = 0
while a!=0:
    a = a//10
    count += 1    
print(value, 'has', count, 'digits') 

⚠️ CAREFULL eval is dangerous

azro
  • 53,056
  • 7
  • 34
  • 70