大家好,我在这个问题上需要一些帮助
编写一个名为 safe_input(prompt, type) 的函数,它的工作方式类似于 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