在没有两个输入框的情况下,如何输入一个字符串形式的值,然后输入一个int值?
How can I input a value as a string and then input a int value without having two input boxes?
我正在编写代码,其中用户必须猜测一个数字并输入它,并且他们可以在其中键入 'quit'、'QUIT' 或 'Quit',它将结束程序。
我有一个 while 循环,一旦他们达到六次尝试的限制并且在其中有 input() ,他们可以猜出数字,该循环将结束程序。我知道在将 input() 转换为整数之前我需要测试字符串 'quit'、'QUIT' 或 'Quit',但我不知道如何在没有有一个检查字符串的 input() 和一个检查整数的 input() 。
有什么建议吗?
可能您正在寻找这样的东西(python 2.6/7):-
lucky_number = 5
tries = 6
while tries:
inp = raw_input("User input: ")
if inp.isdigit() and int(inp) == lucky_number:
return True
elif inp.lower() == 'quit':
break
tries -= 1
return False
由于您在输入后将其转换为 int
,因此我假设您使用的是 Python 3.
在主循环中尝试以下操作:
a = input()
if(a.isdigit()):
n = int(a)
#main code here
else:
#check for "quit" here as shown below
if(a.upper == 'QUIT'): #a.upper() will convert the string into capital letters
#You need to break from the main loop
break
如果您使用的是 Python 2.7 或更低版本,则将上述示例代码中的 input()
替换为 raw_input()
即可解决您的问题。
raw_input()
接受任何类型的输入,从而解决您的问题。
无论您输入什么,都是一个字符串,因此在尝试从中创建 int
对象之前,将其与 QUIT
进行比较并没有什么坏处。
tries = 0
while tries < 6:
value = raw_input("Enter a number, or 'quit' to quit: ") # input() in Python 3.x
if value.upper() == 'QUIT':
sys.exit()
try:
value = int(value)
except ValueError:
continue # Return to the top of the loop for another value
# Process the input integer...
我正在编写代码,其中用户必须猜测一个数字并输入它,并且他们可以在其中键入 'quit'、'QUIT' 或 'Quit',它将结束程序。
我有一个 while 循环,一旦他们达到六次尝试的限制并且在其中有 input() ,他们可以猜出数字,该循环将结束程序。我知道在将 input() 转换为整数之前我需要测试字符串 'quit'、'QUIT' 或 'Quit',但我不知道如何在没有有一个检查字符串的 input() 和一个检查整数的 input() 。
有什么建议吗?
可能您正在寻找这样的东西(python 2.6/7):-
lucky_number = 5
tries = 6
while tries:
inp = raw_input("User input: ")
if inp.isdigit() and int(inp) == lucky_number:
return True
elif inp.lower() == 'quit':
break
tries -= 1
return False
由于您在输入后将其转换为 int
,因此我假设您使用的是 Python 3.
在主循环中尝试以下操作:
a = input()
if(a.isdigit()):
n = int(a)
#main code here
else:
#check for "quit" here as shown below
if(a.upper == 'QUIT'): #a.upper() will convert the string into capital letters
#You need to break from the main loop
break
如果您使用的是 Python 2.7 或更低版本,则将上述示例代码中的 input()
替换为 raw_input()
即可解决您的问题。
raw_input()
接受任何类型的输入,从而解决您的问题。
无论您输入什么,都是一个字符串,因此在尝试从中创建 int
对象之前,将其与 QUIT
进行比较并没有什么坏处。
tries = 0
while tries < 6:
value = raw_input("Enter a number, or 'quit' to quit: ") # input() in Python 3.x
if value.upper() == 'QUIT':
sys.exit()
try:
value = int(value)
except ValueError:
continue # Return to the top of the loop for another value
# Process the input integer...