Interactive input in python

后端 未结 2 1933
谎友^
谎友^ 2021-01-27 12:54

Here is the directions for what I need to do:

You are to write a complete program that obtains three pieces of data and then process them. The three pieces of informatio

2条回答
  •  时光说笑
    2021-01-27 13:10

    I like to add a bit of logic to ensure proper values when I do input. My standard way is like this:

    import ast
    def GetInput(user_message, var_type = str):
        while 1:
            # ask the user for an input
            str_input = input(user_message + ": ")
            # you dont need to cast a string!
            if var_type == str:
                return str_input
            else:
                input_type = type(ast.literal_eval(str_input))
            if var_type == input_type:
                return ast.literal_eval(str_input)
            else:
                print("Invalid type! Try again!")
    

    Then in your main you can do something like this!

    def main():
        my_bool = False
        my_str = ""
        my_num = 0
        my_bool = GetInput("Give me a Boolean", type(my_bool))
        my_str = GetInput("Give me a String", type(my_str))
        my_num = GetInput("Give me a Integer", type(my_num))
    
        if my_bool:
            print('"{}"'.format(my_str))
            print(my_str)
        else:
            print(my_num * 2)
    

提交回复
热议问题