How to treat raw_input variables as integers [closed]

爷,独闯天下 提交于 2021-02-05 12:37:30

问题


# Mit Print kann ich das Programm den Wert einer Variablen ausgeben/anzeigen lassen

print 'Please choose a number'    
a = raw_input(int)    
print 'Please choose a different number'    
b = raw_input(int)    
print 'Please again choose a different number'    
c = raw_input(int)   
print (a**b)/c

Why is this not working? I always get the error

TypeError: unsupported operand type(s) ** /: 'str' and 'str'

I thought the sign for exponate is **, so why this does not work?


回答1:


In your code, a, b and c are strings rather than integers.

Change

a = raw_input(int)    

to

a = int(raw_input())

etc.




回答2:


raw_input returns a string as detailed on the Python docs.

To do what you are trying you would have to first convert the string to an int like below :

a = int(raw_input())



回答3:


Try this form for each input:

a = int(raw_input())    



回答4:


Try this:

#     print 'Please choose a number'    
a = raw_input('Please choose a number' )    
#     print 'Please choose a different number'    
b = raw_input('Please choose a different number' )    
#     print 'Please again choose a different number'    
c = raw_input('Please again choose a different number')   
print (float(a)**float(b))/float (c)



回答5:


raw_input returns a string not an integer, besides its first argument is the prompt that appears before what the user types.

To parse a string into an integer use

the_string = raw_input()
the_integer = int(the_string)

Alternatively, test whether the string can be parsed into an integer

the_integer = None
while the_integer is None:
    print 'Please choose a number'
    the_string = raw_input()
    try:
        the_integer = int(the_string)
    except ValueError:
       print 'That was not a valid number'


来源:https://stackoverflow.com/questions/19362725/how-to-treat-raw-input-variables-as-integers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!