Make input accept only positive numbers

Asked

Viewed 2,134 times

0

I’m doing a factor calculator program, which is already running right.

But I don’t know how to do the input of this program accept only positive numbers. I tried with isdigit:

n = int(input('Digite um numero para calcular seu fatorial ' ))
if not n.isdigit():
    print("Digite apenas numeros!")
c = n
f = 1
print('Calculando {}! = '.format(n), end='')
while c > 0:
    print('{}'.format(c),end='')
    print(' x ' if c > 1 else ' = ',end='')
    f *= c
    c -= 1
print('{}'.format(f))

But it returns me the following error:

Traceback (most recent call last):
  File "F:\Python\files\nap1\q2.py", line 18, in <module>
    if not n.isdigit():
AttributeError: 'int' object has no attribute 'isdigit'
  • None of this makes any sense. If you want a number and that it is positive, then just check if it is greater than or equal to 0. If you want to ensure that what was typed is a Python number is usually through exception capture. If the first line does not launch exception is because it consists of a valid number.

2 answers

0


Hello removes the initial INT conversion and does the conversion after validating.... so:

n = input('Digite um numero para calcular seu fatorial ' )
if not n.isdigit():
    print("Digite apenas numeros!")
else:
    c = int(n)
    f = 1
    print('Calculando {}! = '.format(n), end='')
    while c > 0:
        print('{}'.format(c),end='')
        print(' x ' if c > 1 else ' = ',end='')
        f *= c
        c -= 1
    print('{}'.format(f))

0

Let’s go in pieces:

  • int converts a string to a number, but if it cannot, launches a ValueError. So if the code came in if not n.isdigit():, it is because int(input(...)) worked and converted the string correctly to number. That is, at this point it no longer makes sense to test if it is actually a number.
  • isdigit is a string method, but you tried to use it with a number (because n is the return of int).

But even if you fix these problems, still the logic is wrong. Note that if it is not number, it enters the if, prints the message "Type only numbers!", but then it keeps running the rest of the code (i.e., it will try to calculate the factorial, regardless of n be a number or not). It makes no sense to try to perform the calculation if we already know that n is not a valid number.

Then you could switch to something like this:

try:
    n = int(input('Digite um numero para calcular seu fatorial: '))
    if n < 0:
        print('Número deve ser maior ou igual a zero')
    else:
        # aqui você calcula o fatorial de n
except ValueError:
    print('Você não digitou um número')

If no number is entered, int spear the ValueError and he falls on the block except.

If int work (that is, a number has been typed), you test if it is less than zero (and if it is, print the corresponding message).
If it is not (i.e., the number is greater than or equal to zero), it falls into the else (and within that else you enter the code to calculate the factor of n).


Another option is to keep asking the user to enter the number until it is valid (that is, until it is greater than or equal to zero). While not, you ask that you type again:

while True:
    try:
        n = int(input('Digite um numero para calcular seu fatorial: '))
        if n < 0:
            print('Número deve ser maior ou igual a zero')
        else:
            break # sai do loop
    except ValueError:
        print('Você não digitou um número')

# aqui (fora do while) você calcula o fatorial de n

The while True: creates a loop infinite, which is only interrupted when the number is greater than or equal to zero (the break within the else interrupting the while).

Then out of the while you place the factor calculation of n, because we already guarantee that at this point it is a number greater than or equal to zero.


The other answer uses isdigit to check if a number has been entered. In fact, for the simplest cases it works, but there are characters that return True but still give error when converting with int(). An example is the character ² (SUPERSCRIPT TWO) - note that it is a "2", only smaller and placed "up" (is used for example to write numbers squared - ex: 3² = 9). Here’s an example in Ideone.com.

Also, if you type something like 2 (with spaces before and after the 2), isdigit() returns False, but the conversion with int() works (see here). So probably for this case it’s best to try to use int() directly and capture the ValueError (or else use the method strip to remove these spaces).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.