I write the code in python to count digits of a number but It doesn't work for some numbers

Question:

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?

Asked By: amirali

||

Answers:

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.)

Answered By: timgeb

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 final code is in a quick way :

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

print('number has ',num_digits,'digits') 
Answered By: Laurent B.

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.

Answered By: Leo Arad

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

Answered By: azro
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.