Convert strings to int or float in Python 3?

后端 未结 5 945
无人及你
无人及你 2020-12-11 16:13
 integer = input(\"Number: \")
 rslt = int(integer)+2
 print(\'2 + \' + integer + \' = \' + rslt)
 double = input(\"Point Number: \")
 print(\'2.5 + \' +double+\' =          


        
5条回答
  •  轮回少年
    2020-12-11 16:54

    In Python 3.x - input is the equivalent of Python 2.x's raw_input...

    You should be using string formatting for this - and perform some error checking:

    try:
        integer = int(input('something: '))
        print('2 + {} = {}'.format(integer, integer + 2))
    except ValueError as e:
        print("ooops - you didn't enter something I could make an int of...")
    

    Another option - that looks a bit convoluted is to allow the interpreter to take its best guess at the value, then raise something that isn't int or float:

    from ast import literal_eval
    
    try:
        value = literal_eval(input('test: '))
        if not isinstance(value, (int, float)):
            raise ValueError
        print value + 2
    except ValueError as e:
        print('oooops - not int or float')
    

    This allows a bit more flexibility if you wanted complex numbers or lists or tuples as input for instance...

提交回复
热议问题