简体   繁体   中英

ValueError: invalid literal for int() with base 10: 'string'

I'm trying to write a code in which 2 digits are checked if they are digits or not. Everything works fine when input are digits. Problem occurs when one digit is treated as str. Then I got an error: ValueError: invalid literal for int() with base 10: 'any str typed in keyboard'

Here is my code:

def dividingResult(x, y):
    result = x/y
    return result

def checkDigit1(x):
    if x.isdigit():
        return x
    else:
        print('It is not a digit')
        programStart()

def checkDigit2(y):
    if y.isdigit():
        return y
    else:
        print('It is not a digit')
        programStart()

def programStart():
    print("type digit 1")
    digit1 = input()

    checkDigit1(digit1)

    print("type digit 2")
    digit2 = input()

    checkDigit2(digit2)

    print(dividingResult(int(digit1), int(digit2)))

programStart()

The problem is here print(dividingResult(int(digit1), int(digit2))) .

You are only checking for digits inside the functions checkDigit1 and checkDigit2 and the above line is not inside them. You are not setting any condition for that.

Here is the whole code;

def dividingResult(x, y):
    result = x/y
    return result

def checkDigits(x, y):
    if x.isdigit() and y.isdigit():
        return x, y
    else:
        print('These are not digits')
        programStart()
        return False


def programStart():
    print("type digit 1")
    digit1 = input()

    print("type digit 2")
    digit2 = input()

    checkDigits(digit1, digit2)
    if checkDigits:
        print(dividingResult(int(digit1), int(digit2)))
programStart()

Please comment if you want explanation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM