在下面的程序中,如果我按下回车键,我会得到:
Traceback (most recent call last):
File "C:/Users/Claude/Desktop/practice.py", line 11, in <module>
guess = int(input("Your guess: "))
ValueError: invalid literal for int() with base 10: ''*
在寻找方法来检测&#34;输入&#34;时,我找不到答案。钥匙被压了。有人可以帮忙吗?
from random import randint
# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
guesses_left = 6
while (guesses_left > 0):
guess = int(input("Your guess: "))
if (guess == random_number):
print ("You win!")
ans = input("Do you want to play again?:")
if (ans == 'y' or ans == 'Y'):
guesses_left = 5
guess = int(input("Your guess: "))
else:
break
#elif (guess == ""):
# print ("Please enter a number between 1 and 10")
elif(guess != random_number):
guesses_left -= 1
else:
print ("You lose!")
答案 0 :(得分:3)
当您在input
提示符下按Enter键时,您基本上输入了一个空字符串。所以你会尝试将一个空字符串转换为一个不起作用的数字。相反,您应该首先查看字符串并查看它是否为空,在这种情况下用户只需按Enter键,否则尝试转换它:
guess = input("Your guess: ")
if not guess:
print("You didn't enter anything. So let's abort.")
break
try:
# try converting it to a number
guess = int(guess)
except ValueError:
# ValueError is raised when that didn't work
print("That wasn't a number!")
else:
# otherwise we now have a number which we can use
if guess == random_number:
print('You win')
# …
答案 1 :(得分:0)
因为Your guess
!
int(x)函数将数字或字符串x转换为整数,如果没有给出参数,则返回0。如果x是数字,则它可以是普通整数,长整数或浮点数。如果x是浮点,则转换将截断为零。如果参数超出整数范围,则函数返回一个long对象。 如果x不是数字或者给定了base,那么x必须是一个字符串或Unicode对象,表示以radix为基数的整数文字。 !
如果你有python 2.x,你可以使用raw_input()
函数来获取用户的一般输入。
答案 2 :(得分:0)
我通过使用ord()获得“输入”代码来解决我的问题。 打印(ord(key.char)) 13 如果ord(key.char)== 13: 打印(“ Enter Pressed”) 其他: 打印(“按下任何其他键”)