input from user

前端 未结 4 1112
耶瑟儿~
耶瑟儿~ 2021-01-23 04:45

It\'s a very basic doubt in Python in getting user input, does Python takes any input as string and to use it for calculation we have to change it to integer or what? In the fol

4条回答
  •  無奈伤痛
    2021-01-23 05:36

    Yes, you are correct thinking you need to change the input from string to integer.

    Replace a = raw_input("Enter the first no: ") with a = int(raw_input("Enter the first no: ")).

    Note that this will raise a ValueError if the input given is not an integer. See this for how to handle exceptions like this (or use isnumeric() for checking if a string is a number).

    Also, beware that you although you might find that replacing raw_input with input might work, it is a bad and unsafe method because in Python 2.x it evaluates the input (although in Python 3.x raw_input is replaced with input).

    Example code could therefore be:

    try:
        a = int(raw_input("Enter the first no: "))
        b = int(raw_input("Enter the second no: "))
    except ValueError:
        a = default_value1
        b = default_value2
        print "Invalid input"
    
    c = a+b
    d = a-b
    p = a*b
    print "sum = ", c
    print "difference = ", d
    print "product = ", p  
    

提交回复
热议问题