invalid literal for int() with base 10: '' when provided blank input - python-2.7

I have below code gives me ValueError when input is left blank
U = find_lastuid() # Return variable from other function
uidnum = int(raw_input("What is uid number? (default is: %s)" % U))
if not uidnum:
print("defualt uid is used: %s" % uidnum)
else:
print("UID is %s" % uidnum)
uidnum = int(raw_input("What is uid number? (default is: %s)" % U))
ValueError: invalid literal for int() with base 10: ''
Can someone tell what is wrong with this code?
I can see similar code works in REPL
>>> id = 234
>>> a = raw_input("Enter id")
Enter id
>>> if not id:
... print(id is blank)
... else:
... print(id)
...
234

This is because you cannot convert an empty string to an int, what you could do, however is use a try and except block to handle this:
try:
uidnum = int(raw_input("Enter uid:"))
except ValueError:
print("Please enter a number!")

Related

user_input() = input("Please enter a number: ") ^ SyntaxError: cannot assign to function call

Ask the user to enter a number and check if the input is 'POSITIVE', 'ZERO', 'NEGATIVE'
def is_positive():
# input() returns str
user_input() = input("Please enter a number: ")
# cast input into int -> int()
n = int(user_input)
# check conditions
if n > 0:
print("POSITIVE")
elif n == 0:
print("ZERO")
else:
print("NEGATIVE")
Close just change the user input variable name to have no parentheses like so. The parentheses are meant for when you are calling a function which is why an error was raised.
user_input = input("Please enter a number: ")

ValueError: invalid literal for int() with base 10: '12,652'

I am trying to get no of reviews count of a particular product
The code is:
total_reviews = soup.find("div", {"class": "feature"}).findNext(
"span", {"id": "acrCustomerReviewText"}).string
x = ''
for number in total_reviews:
if number == ' ':
break
else:
x = x + number
num_reviews =int(x)
Replace the comma with an empty string using str.replace():
num_reviews = int(x.replace(",", ""))

I have found most of everything I need and have a "mostly" working game

I having issues with the def check guess. It's the format my teacher specifically gave. You guys are great. Thanks for the help!!!! Sorry for the format this is my first time on this site.
# # Global variables
wrong_guesses = []
target_phrase = ""
current_phrase = ""
def clear_display():
for i in range(20):
print "\n"
def string_with_dashes(str):
global target_phrase
new_phrase = ""
for i in str:
if i.isalpha():
new_phrase += "-"
else:
new_phrase += i
return new_phrase
def check_guess(letter):
global current_phrase
replacement_list = [""]
for i in range(len(target_phrase)):
if target_phrase[i] == letter:
replacement_list[i] = target_phrase[i]
current_phrase = replacement_list
return current_phrase
else:
wrong_guesses.append(letter)
return False
def process_input():
user_letter = raw_input("Guess a letter: ").upper()
if user_letter in wrong_guesses:
print "You already guessed that letter"
user_letter = raw_input("Guess again : ")
else:
return check_guess(user_letter)
def one_turn():
global wrong_guesses
print "=================================================="
print current_phrase
print "Wrong guesses:", ' '.join(wrong_guesses)
print "Guesses remaining:", (8 - len(wrong_guesses))
display_robot(8 - len(wrong_guesses))
print "String to guess:", current_phrase
print "=================================================="
process_input()
print "\n\n"
def setup_phrase():
global target_phrase, current_phrase
target_phrase = raw_input("Dear friend, enter a phrase for the user to guess: ").upper()
current_phrase = string_with_dashes(target_phrase)
setup_phrase()
clear_display()
while True:
one_turn()
if len(wrong_guesses) > 7:
print "GAME OVER! You Lose"
breack
if current_phrase == target_phrase:
print "You WIN!!"
break
(why won't stackoverflow let me fix your code?)
I'm not sure exactly what you are trying to do, but it sounds like you want to create a string where the guessed letters replace blanks as they are guessed? Try something like this:
hidden_phrase = "abracadabra"
current_list = ["."]*len(hidden_phrase)
def check_guess(letter):
for i in range(len(hidden_phrase)):
if hidden_phrase[i] == letter:
current_list [i] = hidden_phrase[i]
print("before", "".join(current_list ))
check_guess("a")
print("guess1", "".join(current_list))
check_guess("z")
print("guess2", "".join(current_list))
check_guess("b")
print("guess3", "".join(current_list))
Output:
before ...........
guess1 a..a.a.a..a
guess2 a..a.a.a..a
guess3 ab.a.a.ab.a
In Python strings are immutable, and can't be updated, so it seems easier to me to keep the 'replacement' word (with blanks, which I represent with .) as a list, and join it back together for display.
The two global variables don't need to be explicitly specified as global, because the variable is not assigned to in the function, only accessed.
If you prefer to have a string current_phrase and update that, of course that's possible too:
hidden_phrase = "abracadabra"
current_phrase = "."*len(hidden_phrase )
def check_guess(letter):
global current_phrase
i = -1
while True:
i = hidden_phrase.find(letter, i+1)
if i<0:
break
current_phrase = current_phrase[0:i]+letter + current_phrase[i+1:]
print("before", current_phrase)
check_guess("a")
print("guess1", current_phrase)
check_guess("z")
print("guess2", current_phrase)
check_guess("b")
print("guess3", current_phrase)
This time you need the global again to prevent current_phrase = ... from creating a local variable.
My previous answer was to the first, more general, version of your question. Several things were wrong with your check_guess(). Here's a fixed version:
def check_guess(letter):
global current_phrase
replacement_list = list(current_phrase)
found=False
for i in range(len(target_phrase)):
if target_phrase[i] == letter:
replacement_list[i] = target_phrase[i]
found = True
if found:
current_phrase = "".join(replacement_list)
else:
wrong_guesses.append(letter)
Comments to show problems with your version:
def check_guess(letter):
global current_phrase
replacement_list = [""] # list has only 1 element, can't assign above index zero
for i in range(len(target_phrase)):
if target_phrase[i] == letter:
replacement_list[i] = target_phrase[i]
current_phrase = replacement_list # assigning a list to what was previously a string
return current_phrase # returns before checking 2nd character
else:
wrong_guesses.append(letter) # only the first character has been checked
return False # returns False or current_phrase, inconsistent
Also near the end you wrote breack instead of break, it's a shame that Python doesn't check these things by default, waiting instead for you to hit that line.

Python 2.7, unexpected EOF while parsing

I am a newbie to Python and I was trying my hand at the following problem: I want to add numbers entered by the user. Here is my program
add = 0
num = input('Enter a number:')
add = add + num
while num != ' ' :
num = input('Next number:')
add = add + num
print add
I want to terminate the program when a blank is entered. So I know the problem is with line 4. What would be the correct syntax?
Thanks in advance for your help
In python 2.7 user input should be processed using raw_input
This is because input is semantically equivalent to:
eval(raw_input(prompt))
which, when given an empty string, will cause the following line of code:
eval('')
will return an EOF error while parsing, since empty is not a valid object to parse.
Since raw_string doesnt parse the string into an int you'll also have to use int() to convert it when you do the addition.
You also need to change to while statement:
add = 0
num = raw_input('Enter a number:')
# you cant do a + here what if the user hits enter right away.
if num:
add = int(num)
while num: # enter will result in a null string not a space
num = raw_input('Next number:')
if num:
add = add + int(num)
print add
Try following and read a bit.
>>> help(input)
>>> help(raw_input)
>>> s=raw_input()
<return right here>
>>> s
''
>>> s=raw_input()
<one space followed by return here>
>>> s
' '
>>>

python: checking for errors in the users input

I would like
to check if a string can be a float before I attempt to convert it to a float. This way, if the
string is not float, we can print an error message and exit instead of crashing the
program.
so when the user inputs something, I wanna see if its a float so it will print "true" if its not then it will print"false" rather than crashing. I don't want to use built in functions for this. I need to make my own function for this.
I tried :
import types
def isFloat():
x = raw_input("Enter: ")
if(x) == float:
print("true")
if(x) == str:
print("false")
isFloat()
I don't know if its true or not but it wont work it wont print anything either
The recommended thing to do here is to try it:
try:
f = float(x)
print("true")
except ValueError:
# handle error here
print("false")
This underscores the Python philosophy "It's better to ask for forgiveness than for permission".
The only reliable way to figure out whether a string represents a float is to try to convert it. You could check first and convert then, but why should you? You'd do it twice, without need.
Consider this code:
def read_float():
"""
return a floating-point number, or None
"""
while True:
s = raw_input('Enter a float: ').strip()
if not s:
return None
try:
return float(s)
except ValueError:
print 'Not a valid number: %r' % s
num = read_float()
while num is not None:
... do something ...
print 'Try again?'
num = read_float()