Write a program in python that reads an 8-digit integer

1

Write a program that reads an 8-digit integer. The output of your program should be the result of the sum of all digits of the integer entered. If the number entered does not have 8 digits, the program should write 'NAO SEI' (without accents and quotation marks).

IMPORTANT: You should resolve this issue by using Repetition Layout. Otherwise, the grade will be zero.

Exemplo 1:

Entrada:

123

Saída:

NAO SEI



Exemplo 2:

Entrada:

34576890

Saída:

42

Personally I made the following code but my grade continues 5 out of 10 and I think the problem is in this part of the:

 if n<=1:
    print("NAO SEI")

Since the program does not have 8 digits, the program should write 'NAO SEI'

n=int(input("valor de n:"))

soma=0

while n>0:

resto=n%10

n=(n-resto)//10

soma=soma+resto

print(soma)

if n<=1:

print("NAO SEI")
    
asked by anonymous 05.04.2018 / 23:25

1 answer

3

The best way to resolve this is:

numero = input('Número: ')

if len(numero) == 8:
    print(sum(map(int, numero)))
else:
    print('NAO SEI')

That could even be reduced to:

numero = input('Número: ')

print(sum(map(int, numero)) if len(numero) == 8 else 'NAO SEI')

Without compromising the readability and semantics of the code. But as you explicitly ask to use repetition loops, which is probably to train such a structure, you can solve it as follows:

algarismos = input('Número: ')

if len(algarismos) == 8:
    numero = int(algarismos)
    soma = 0
    while numero > 0:
        soma += numero % 10
        numero = numero//10
    print(soma)
else:
    print('NAO SEI')

See working at Repl.it

Basically the only difference to your code, regardless of the indentation errors in the question, is that I checked the number of numbers in the number while it was still a string , in return of input .

The question to be raised is: should the number "01234567" be considered as 8 digits or 7? If it is 8, the treatment with string is the simplest, but if it is 7, the number must be an even numeric type, so it would be ideal to check if it is within the% :

numero = int(input('Número: '))

if 10000000 <= numero <= 99999999:
    soma = 0
    while numero > 0:
        soma += numero % 10
        numero = numero//10
    print(soma)
else:
    print('NAO SEI')

See working at Repl.it

    
06.04.2018 / 00:15