问题:Python 2.7获取用户输入并以不带引号的字符串形式进行操作
我想从用户那里获取一个字符串,然后对其进行操作。
testVar = input("Ask user for something.")
没有我让用户在引号中键入其响应的方法,testVar是否可以成为字符串?即“你好”与你好
如果用户输入Hello,则会出现以下错误:
NameError:名称“ Hello”未定义
I want to get a string from a user, and then to manipulate it.
testVar = input("Ask user for something.")
Is there a way for testVar to be a string without me having the user type his response in quotes? i.e. “Hello” vs. Hello
If the user types in Hello, I get the following error:
NameError: name ‘Hello’ is not defined
回答 0
使用raw_input()
代替input()
:
testVar = raw_input("Ask user for something.")
input()
实际上将输入评估为Python代码。我建议不要使用它。 raw_input()
返回用户输入的逐字字符串。
Use raw_input()
instead of input()
:
testVar = raw_input("Ask user for something.")
input()
actually evaluates the input as Python code. I suggest to never use it. raw_input()
returns the verbatim string entered by the user.
回答 1
该函数input
还将评估刚读取为python代码的数据,这并不是您真正想要的。
通用方法是将(来自的sys.stdin
)用户输入像其他文件一样对待。尝试
import sys
sys.stdin.readline()
如果您想使其简短,可以使用raw_input
与相同的方法,input
但忽略评估。
The function input
will also evaluate the data it just read as python code, which is not really what you want.
The generic approach would be to treat the user input (from sys.stdin
) like any other file. Try
import sys
sys.stdin.readline()
If you want to keep it short, you can use raw_input
which is the same as input
but omits the evaluation.
回答 2
我们可以raw_input()
在Python 2和input()
Python 3中使用该函数。默认情况下,输入函数采用字符串格式的输入。对于其他数据类型,您必须强制转换用户输入。
在Python 2中,我们使用raw_input()
函数。它等待用户键入一些输入并按下,return
然后我们需要通过将其强制转换为所需的数据类型来将值存储在变量中。使用类型转换时要小心
x = raw_input("Enter a number: ") #String input
x = int(raw_input("Enter a number: ")) #integer input
x = float(raw_input("Enter a float number: ")) #float input
x = eval(raw_input("Enter a float number: ")) #eval input
在Python 3中,我们使用input()函数返回用户输入值。
x = input("Enter a number: ") #String input
如果输入字符串,则为int,float,eval,它将作为字符串输入
x = int(input("Enter a number: ")) #integer input
如果输入用于int cast的字符串 ValueError: invalid literal for int() with base 10:
x = float(input("Enter a float number: ")) #float input
如果输入用于float转换的字符串 ValueError: could not convert string to float
x = eval(input("Enter a float number: ")) #eval input
如果输入用于eval cast的字符串,那么NameError: name ' ' is not defined
这些错误也适用于Python 2。
We can use the raw_input()
function in Python 2 and the input()
function in Python 3.
By default the input function takes an input in string format. For other data type you have to cast the user input.
In Python 2 we use the raw_input()
function. It waits for the user to type some input and press return
and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting
x = raw_input("Enter a number: ") #String input
x = int(raw_input("Enter a number: ")) #integer input
x = float(raw_input("Enter a float number: ")) #float input
x = eval(raw_input("Enter a float number: ")) #eval input
In Python 3 we use the input() function which returns a user input value.
x = input("Enter a number: ") #String input
If you enter a string, int, float, eval it will take as string input
x = int(input("Enter a number: ")) #integer input
If you enter a string for int cast ValueError: invalid literal for int() with base 10:
x = float(input("Enter a float number: ")) #float input
If you enter a string for float cast ValueError: could not convert string to float
x = eval(input("Enter a float number: ")) #eval input
If you enter a string for eval cast NameError: name ' ' is not defined
Those error also applicable for Python 2.
回答 3
如果您想在python 2.x中使用input而不是raw_input,那么这个技巧将派上用场
if hasattr(__builtins__, 'raw_input'):
input=raw_input
之后,
testVar = input("Ask user for something.")
会很好。
If you want to use input instead of raw_input in python 2.x,then this trick will come handy
if hasattr(__builtins__, 'raw_input'):
input=raw_input
After which,
testVar = input("Ask user for something.")
will work just fine.
回答 4
testVar = raw_input("Ask user for something.")
testVar = raw_input("Ask user for something.")
回答 5
我的修正工作代码:
import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)
correct= False
while(correct == False):
guess1= input("Which number is the highest? "+ str(list) + ": ")
if maxNum == guess1:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
if sqrtOne >= 2.0 and str(guess3) == "y":
print("Correct!")
correct = True
elif sqrtOne < 2.0 and str(guess3) == "n":
print("Correct!")
correct = True
else:
print("Incorrect, try again")
print("Thanks for playing!")
My Working code with fixes:
import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)
correct= False
while(correct == False):
guess1= input("Which number is the highest? "+ str(list) + ": ")
if maxNum == guess1:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
if sqrtOne >= 2.0 and str(guess3) == "y":
print("Correct!")
correct = True
elif sqrtOne < 2.0 and str(guess3) == "n":
print("Correct!")
correct = True
else:
print("Incorrect, try again")
print("Thanks for playing!")
回答 6
这是我的工作,以防万一我将来需要转移到python 3时失败。
def _input(msg):
return raw_input(msg)
This is my work around to fail safe in case if i will need to move to python 3 in future.
def _input(msg):
return raw_input(msg)
回答 7
该问题似乎在Python 3.4.2版中已解决。
testVar = input("Ask user for something.")
将正常工作。
The issue seems to be resolved in Python version 3.4.2.
testVar = input("Ask user for something.")
Will work fine.