Interactive input in python

后端 未结 2 1938
谎友^
谎友^ 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:13

    On stackoverflow, we're here to help people solve problems, not to do your homework, as your question very likely sounds… That said, here is what you want:

    def main():
        Boolean = input("Give me a Boolean: ")
        String = input("Give me a string: ")
        Number = int(input("Give me a number: "))
    
        if Boolean == "True":
            print('"{s}"\n{s}'.format(s=String))
        try:
            print('{}\n{}'.format(int(Number)))
        except ValueError as err:
            print('Error you did not give a number: {}'.format(err))
    
    if __name__ == "__main__":
        main()
    

    A few explanations:

    • Boolean is "True" checks whether the contained string is actually the word True, and returns True, False otherwise.
    • then the print(''.format()) builds the double string (separated by \n) using the string format.
    • finally, when converting the string Integer into an int using int(Integer), it will raise a ValueError exception that gets caught to display a nice message on error.

    the if __name__ == "__main__": part is to enable your code to be only executed when ran as a script, not when imported as a library. That's the pythonic way of defining the program's entry point.

提交回复
热议问题