Getting an "invalid literal for int with base 10" in Python

时间:2016-02-12 20:38:34

标签: python string int python-3.4 literals

function spinalCase(str) {
    var noCamel = str.replace(/([A-Z])/g, ' $1');
    var newStr = noCamel.replace(/\s|_/g, "-");
    return newStr.toLowerCase();
}

spinalCase("makeThisSpinal"); //returns make-this-spinal
spinalCase("Make This Spinal"); //returns -make--this--spinal

Why am I getting the "invalid literal for int" when I type in exit? I tried converting the input variable to int, I tried with an else statement, I tried making 2 variables, one for string one for int, and none of them worked.

3 个答案:

答案 0 :(得分:0)

Assuming that the incorrect indentation in the question is just a copy-paste mistake... try this:

git push

Here's what happens:

x = input('enter x > ')
print('x == "exit": {}'.format(x == "exit"))
print('x is "exit": {}'.format(x is "exit"))

Or maybe:

enter x > exit
x == "exit": True
x is "exit": False

The x is "exit": True operator compares object identity but you are trying to compare the contents of two strings.

答案 1 :(得分:0)

I believe the issue is from the line: remote()

Is evaluating to if num is "exit" and further down the script when Python tries to convert the literal string False to an int, it will fail.

Try replacing exit with is

The problem is that == compares two objects to see if they are the same, whereas what want to is to see if the tow objects' values are the same. Check this stack overflow thread for more info.

答案 2 :(得分:0)

Note that you cannot give a string with non-numeric characters to ConfigManagerProcess mockConfigManagerProcess = mock(ConfigManagerProcess.class); when(mockConfigManagerProcess.isApplet()).thenReturn(true);.

Now int() is supposed to be a num, and it could be anything from user input. Also note that when you want to evaluate two values, use str instead of ==. is is supposed to be used as judging if two things are the same object.

If you want to use if-else, try this:

is

Here, if num == "exit": print("Number of tries: {}".format(counter)) print("Number of correct guesses: {}".format(ccounter)) break elif not num or not all(char.isdigit() for char in num): print("You are not giving a number.") else: if int(num) == gld: print("Congratulations, your guessed number {} was right!".format(num)) counter += 1 ccounter += 1 elif int(num) < gld: print("Pick a higher number!") counter += 1 else: print("Pick a lower number!") counter += 1 is checking for every character in all(char.isdigit() for char in num) to see if they are all numbers. We should be aware that anything could appear in user's input. Only numbers can be converted to num.

We have another solution which is more clear and simple. You may need to read some documents on int in Python.

try...except...