我想从用户那里获取一个字符串,然后操纵它.
testVar = input("Ask user for something.")
Run Code Online (Sandbox Code Playgroud)
有没有一种方法让testVar成为一个字符串而没有我让用户在引号中键入他的响应?即"你好"与你好
如果用户输入Hello,我会收到以下错误:
NameError:未定义名称"Hello"
我通过使用int(raw_input(...))查询预期为int的用户输入
但是当用户没有输入整数时,即只是命中返回时,我得到一个ValueError.
def inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue):
rowPos = int(raw_input("Please enter the row, 0 indexed."))
colPos = int(raw_input("Please enter the column, 0 indexed."))
while True:
#Test if valid row col position and position does not have default value
if rangeRows.count(rowPos) == 1 and rangeCols.count(colPos) == 1 and inputMatrix[rowPos][colPos] == defaultValue:
inputMatrix[rowPos][colPos] = playerValue
break
else:
print "Either the RowCol Position doesn't exist or it is already filled in."
rowPos = int(raw_input("Please enter the row, 0 indexed."))
colPos = int(raw_input("Please …Run Code Online (Sandbox Code Playgroud) 目标是编写一个脚本,该脚本将复制文本文件并排除以#开头的任何行.
我的问题是我似乎得到一个索引错误,这取决于我的if ifif条件的顺序.非工作代码和工作代码之间的唯一区别(除了后缀"_bad"到非工作函数名称)是我首先测试""条件(工作)与首先测试"#"条件(不起作用)
基本文件由此脚本创建:
>>> testFileObj = open("test.dat","w")
>>> testFileObj.write("#line one\nline one\n#line two\nline two\n")
>>> testFileObj.close()
Run Code Online (Sandbox Code Playgroud)
有效的代码:
def copyAndWriteExcludingPoundSigns(origFile, origFileWithOutPounds):
origFileObj = open(origFile,"r")
modFileObj = open(origFileWithOutPounds,"w")
while True:
textObj = origFileObj.readline()
if textObj == "":
break
elif textObj[0] == "#":
continue
else:
modFileObj.write(textObj)
origFileObj.close()
modFileObj.close()
Run Code Online (Sandbox Code Playgroud)
代码不起作用:
def copyAndWriteExcludingPoundSigns_Bad(origFile, origFileWithOutPounds):
origFileObj = open(origFile,"r")
modFileObj = open(origFileWithOutPounds,"w")
while True:
textObj = origFileObj.readline()
if textObj[0] == "#":
continue
elif textObj == "":
break
else:
modFileObj.write(textObj)
origFileObj.close()
modFileObj.close()
Run Code Online (Sandbox Code Playgroud)
这给了我这个错误:
Traceback (most recent call last): …Run Code Online (Sandbox Code Playgroud) 我正在编写一个接受用户输入的函数:
def func(input):
Run Code Online (Sandbox Code Playgroud)
我输入了try和excepts来确保输入是我想要的类型.但是,当我输入testInput时,它会抛出NameError vs"testInput".
我理解为什么因为它认为testInput是一个变量名,而它知道"testInput"是一个字符串.
是否有一种智能的方法来捕获此错误?