该函数有两个参数:Prompt:str和Return类型:int,float,str

时间:2013-02-17 22:28:54

标签: python prompt

大家好,我需要一些关于这个问题的帮助

编写一个名为safe_input的函数(提示,类型) 就像Python输入函数一样, 除了它只接受指定类型的输入。

该函数有两个参数:

提示:str

输入:int,float,str

该功能将一直提示输入,直到输入指定类型为止 进入。该函数返回输入。如果输入被指定为数字(float或int),则返回的值将是正确的类型;也就是说,该函数将执行转换。

提示的默认值是空字符串。 该类型的默认值为string。

以下是我所拥有的:

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 个答案:

答案 0 :(得分:1)

为什么你有这一行:

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

在程序开始时。你应该有函数的定义,但最后你有。

解决方案:删除该伪造行并将该函数的定义移至程序顶部。

解释:当您运行该行时,它会向用户询问某些内容,并将该42分配给safe_input。然后您尝试使用作为一个函数,但是,嘿,42是一个整数,并且无法调用。

答案 1 :(得分: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

尽量不要使用类型等内置函数来表示变量名。他们会覆盖内置组件,以后会引起很多麻烦。

相关问题