input from user

前端 未结 4 1151
耶瑟儿~
耶瑟儿~ 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:37

    Yes, every input is string. But just try:

    a = int(a)
    b = int(b)
    

    before your code.

    But be aware of the fact, that user can pass any string he likes with raw_input. The safe method is try/except block.

    try:
        a = int(a)
        b = int(b)
    except ValueError:
        raise Exception("Please, insert a number") #or any other handling
    

    So it could be like:

    try:
        a = int(a)
        b = int(b)
    except ValueError:
        raise Exception("Please, insert a number") #or any other handling
    c=a+b
    d=a-b
    p=a*b
    print "sum =", c
    print "difference = ", d
    print "product = ", p  
    

    From the documentaion:

    The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

提交回复
热议问题