Wednesday, 15 July 2015

python - The function takes two arguments: Prompt: str and Return types: int, float, str -



python - The function takes two arguments: Prompt: str and Return types: int, float, str -

hello need help question

write function named safe_input (prompt, type) works python input function, except accepts specified type of input.

the function takes 2 arguments:

prompt: str

type: int, float, str

the function maintain prompting input until right input of specified type entered. function returns input. if input specified number (float or int), value returned of right type; is,the function perform conversion.

the default prompt empty string. default type string.

heres have: safe_input = input(str("enter string type want check: ")) test = safe_input("this string") print ('"{}" {}'.format(test,type(test))) test = safe_input("this string",int) print ('"{}" {}'.format(test,type(test))) test = safe_input("this string",float) print ('"{}" {}'.format(test,type(test))) test = safe_input(5) print ('"{}" {}'.format(test,type(test))) test = safe_input(5,int) print ('"{}" {}'.format(test,type(test))) test = safe_input(5,float) print ('"{}" {}'.format(test,type(test))) test = safe_input(5.044) print ('"{}" {}'.format(test,type(test))) test = safe_input(5.044, int) print ('"{}" {}'.format(test,type(test))) test = safe_input(5.044, float) print ('"{}" {}'.format(test,type(test))) def safe_input (prompt, type=str): if (type == int): while (true): try: # check integer or float integer_check = int(prompt) # if integer, numbers equal if (prompt == integer_check): homecoming integer_check else: print("they not equal!!") homecoming integer_check except valueerror: print ("your entry, {}, not of {}." .format(prompt,type)) prompt = input("please come in variable of type '{}': " .format(type))

does have thought doing wrong here? friend , been working on hours.

update: errors such as: file "c:\users\thomas\desktop\ei8069_lab9_q4.py", line 28, in <module> test = safe_input("this string") typeerror: 'int' object not callable traceback (most recent phone call last): file "c:\users\thomas\desktop\ei8069_lab9_q4.py", line 28, in <module> test = safe_input("this string") typeerror: 'float' object not callable

just 2 cents.

first, read assignment more carefully, method isn't want.

and using lot of unnecessary conditions. function much more simplier, this:

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, come in again.") else: break homecoming ret

try not utilize builtin functions type variable names. override builtins , can cause lot of headache later on.

python prompt

No comments:

Post a Comment