【发布时间】:2013-02-17 22:28:54
【问题描述】:
大家好,这个问题我需要帮助
编写一个名为safe_input(提示,类型)的函数 像 Python 输入函数一样工作, 除了它只接受指定类型的输入。
该函数有两个参数:
提示:str
类型:int、float、str
函数会一直提示输入,直到指定类型的正确输入 进入。该函数返回输入。如果输入指定为数字(float 或 int),则返回的值将是正确的类型;也就是说,该函数将执行转换。
提示的默认值是空字符串。 类型的默认值是字符串。
这是我所拥有的:
safe_input = input(str("Enter a String Type you want to check: "))
test = safe_input("this is a string")
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input("this is a string",int)
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input("this is a string",float)
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input(5)
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input(5,int)
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input(5,float)
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input(5.044)
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input(5.044, int)
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input(5.044, float)
print ('"{}" is a {}'.format(test,type(test)))
def safe_input (prompt, type=str):
if (type == int):
while (True):
try:
# check for integer or float
integer_check = int(prompt)
# If integer, numbers will be equal
if (prompt == integer_check):
return integer_check
else:
print("They are not equal!!")
return integer_check
except ValueError:
print ("Your entry, {}, is not of {}."
.format(prompt,type))
prompt = input("Please enter a variable of the type '{}': "
.format(type))
有人知道我在这里做错了什么吗?我和我的朋友已经为此工作了好几个小时。
更新:我收到如下错误:
File "C:\Users\Thomas\Desktop\ei8069_Lab9_Q4.py", line 28, in <module>
test = safe_input("this is a string")
TypeError: 'int' object is not callable
Traceback (most recent call last):
File "C:\Users\Thomas\Desktop\ei8069_Lab9_Q4.py", line 28, in <module>
test = safe_input("this is a string")
TypeError: 'float' object is not callable
【问题讨论】:
-
您的代码目前有什么问题? (它表现出什么不正确的行为?)
-
在您的第一行中,您将 safe_input 的值分配给用户输入的值,然后像调用函数一样调用它!先定义safe_input函数,input()调用应该在函数内部。