函数接收两个参数:提示:str 和返回类型:int、float、str

0 投票
2 回答
3654 浏览
提问于 2025-04-17 16:12

大家好,我需要一些帮助来解决这个问题。

写一个叫做 safe_input 的函数(参数是 prompt 和 type),它的功能和 Python 的 input 函数类似,但只接受指定类型的输入。

这个函数有两个参数:

prompt: 字符串

type: 整数、浮点数、字符串

这个函数会不断提示用户输入,直到输入的类型正确为止。函数会返回用户输入的内容。如果输入的类型是数字(浮点数或整数),返回的值会是正确的类型,也就是说,函数会自动进行类型转换。

默认的提示内容是空字符串。默认的类型是字符串。

这是我写的代码:

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

2 个回答

1

你为什么在程序开头有这一行:

safe_input = input(str("Enter a String Type you want to check: "))

你应该在开头定义这个函数,而不是把它放在最后。

解决办法:把那行多余的代码删掉,把函数的定义移到程序的最上面。

解释:当你运行那一行时,它会让用户输入一些东西,比如说输入了 42,这个值会被赋给 safe_input。然后你试图把它当作一个函数来用,但 42 是一个数字,不能被调用。

1

我来发表一下我的看法。

首先,仔细看看你的作业要求,你的方法其实并不是他们想要的那样。

而且你用了很多不必要的条件。你的函数可以简单得多,像这样:

def safe_input(prompt, type_=str):
    if(type_ not in (str, int, float)): 
        raise ValueError("Expected str, int or float.")  

    while True:
        test = input(prompt)    
        try:
            ret = type_(test)
        except ValueError:
            print("Invalid type, enter again.")                
        else:
            break    

    return ret

尽量不要把内置函数的名字,比如 type,作为变量名。这样会覆盖掉内置函数,之后可能会让你很头疼。

撰写回答