Home > Software design >  Expected type 'Sized', got 'int' instead
Expected type 'Sized', got 'int' instead

Time:05-01

(I'm pretty new to python) So I was trying to make a mini project to reverse all the numbers in a string. But first I had to check if what the user entered was a number or not. But even when what the user typed in was an integer, PyCharm skipped that if statement. Can any of you guys help me? code:

print('type a random number consisting of 10 digits')
l1 = 0


def loop1():
    global l1
    l1 = int(input())
    if l1 == int():
        if len(l1) != 10:
            print("The number you have entered does not consist of 10 digits. "
                  "Please enter a number consisting of 10 digits.")
            loop1()
    else:
       print("You have not entered a proper number. Please enter a proper number")
        loop1()


loop1()
l1 = list(l1)
print(l1[0: 10: 2])

CodePudding user response:

if l1 == int():

tests if l1 == 0:. To test if something is an integer, use isinstance(something, int). Does not work in your code, because your int(input()) would throw an exception if any non-integer is given as input.


You should avoid globals. Do not call your function recursively to make it "loop". When converting string to int you need to capture errors arising from inputting non-integers.

When checking the length of a inputted numbers string representation you need to convert then stringify again to avoid inputs like

"0000000000" --> 0 --> "0"  # length 1

This can be done like so:

def ask_for_int_of_length(text, lenght):
    """Aks for an integer, loop until got one that has a string representation
    that is 'length' long. Will accept negatives. Returns the numberstring"""
    print(text) # could use input(text) as well to repeat message
    while True:
        t =  input()
        try:
            n = int(t)
        except ValueError:
            print("Bad input - not an interger of length",lenght,". Try again.")
            continue
        
        if len(str(n)) != lenght:
            # avoid inputs of 0000000001 for number of 10 digits
            print("Bad input: ",n," is not an interger of length", 
                  lenght, ". Try again.")
            continue

        return t # return the string of the number            


number = ask_for_int_of_length("Gimme nummer of lenght 10", 10)

print(number[0: 10: 2])

Outputs:

Gimme nummer of lenght 10
apple
Bad input - not an interger of length 10 . Try again.
0000100000
Bad input:  100000  is not an interger of length 10 . Try again.
1234567890
13579

This can still work with numbers of 1 length less if you make them negative:

Gimme nummer of lenght 10
-123456789
-2468

To test how many digits a number has without converting it into a string, you can leverage math.log10(.)'s return if converted to int and added 1:

from math import log10

def numAbsDigits(integer):
    """Returns how many digits the absolute value has"""
    return int(log10(abs(integer))) 1 if integer else 1

for i in range(11):
    n = 10**i
    for d in range(-1,2):
        print (n d, "has", numAbsDigits(n d), "digits.")

Output:

0 has 1 digits.
1 has 1 digits.
2 has 1 digits.
9 has 1 digits.
10 has 2 digits.
11 has 2 digits.
99 has 2 digits.
100 has 3 digits.
101 has 3 digits.
999 has 3 digits.
1000 has 4 digits.
1001 has 4 digits.
9999 has 4 digits.
10000 has 5 digits.
10001 has 5 digits.
99999 has 5 digits.
100000 has 6 digits.
100001 has 6 digits.
999999 has 6 digits.
1000000 has 7 digits.
1000001 has 7 digits.
9999999 has 7 digits.
10000000 has 8 digits.
10000001 has 8 digits.
99999999 has 8 digits.
100000000 has 9 digits.
100000001 has 9 digits.
999999999 has 9 digits.
1000000000 has 10 digits.
1000000001 has 10 digits.
9999999999 has 10 digits.
10000000000 has 11 digits.
10000000001 has 11 digits.

CodePudding user response:

First thing if you do int(input()) if it will be an integer it will be converted to integer and if it is not it will straightaway exit with an error ValueError: invalid literal for int() with base 10, so what you want to do with if l1=int() is not needed instead you need a try except statement l1=input()

try:
    l1=int(l1)
except ValueError:
    print('input not an integer')

Even if you do an if statement if l1==int() it will not work you need to do if type(l1) == int: although you do not need it. Also quite mentioning that you can't do len(l1) as l1 is an integer and len doesn't work with an integer I advise you to instead make another variable string_l1=int(l1) in the same try except statement i just wrote

CodePudding user response:

Several mistakes to point out:

  • In order to do a loop use while loop

    while True:
        EatSausages()
    
  • In order to check if the input/variable/object of type int, python has a function isinstance

    isinstance(l1, int)
    
  • You already declared type of input to be an interger int(input()) Then you don't have to check if its of type int because it will return an error/exception if user inputs a string

  • You cannot len(type int)


Possible solution

In order to solve your problem of reverse all the numbers in a string

cont = ''

while cont != 'n': #Using a while loop to iterate this code again untill user types in n in end of program
    l1 = '' 
    
    while len(l1) != 10: #Again use a while loop to keep looping until user inputs correctly

        try: #Use try to catch if the user did not enter ints
            temp = int(input('type a random number consisting of 10 digits')) #asks for input of the digits and store it in digits

        except ValueError:
            print("You have not entered a proper number. Please enter a proper number")

        l1 = str(temp) #change back into string so we can measure the length

        if len(l1) < 10: #Check if l1 is 10 digits
            print("The number you have entered does not consist of 10 digits. \n"
                  "Please enter a number consisting of 10 digits.")
    print('Reversing...')

    print(l1[::-1])

    cont = input('Do you want to try again (y/n)')

References:

  1. https://www.w3schools.com/python/ref_func_isinstance.asp
  • Related