简体   繁体   English

如何根据用户从键盘输入的内容定义公式? (蟒蛇)

[英]How to define a formula based on user's input from keyboard? (Python)

It's my very first question so I hope I'll put it right. 这是我的第一个问题,所以我希望我将它纠正。

I'm doing some predefined exercises in Python and one request is to define the following formula: 我正在用Python做一些预定义的练习,一个请求是定义以​​下公式:

{6*[2+(a-1)%b]*2a} with user's input from the keyboard. {6 * [2+(a-1)%b] * 2a}由用户从键盘输入。

If I am to pick the "a" and "b" my self, the formula is working, however, when ask input from user ( raw_input ) I'm getting an error and I can't figure out why. 如果我选择自己的“ a”和“ b”,则该公式有效,但是,当从用户( raw_input )询问输入时,我遇到错误,无法弄清原因。

The code I tried looks like this: 我尝试的代码如下所示:

a = raw_input("enter the first number")
b = raw_input("enter the second number")

print (6*(2+(a-1)%b)*2**a)

And the error message is this: 错误消息是这样的:

Traceback (most recent call last):
  File "python", line 4, in <module>
TypeError: unsupported operand type(s) for -: 'unicode' and 'int'

Thank you in advance for your help, Victor Victor多谢您的帮助

In python2, which you sadly chose to use, the function raw_input returns a string. 在您不幸选择使用的python2中,函数raw_input返回一个字符串。 You must convert it into a number: 您必须将其转换为数字:

a = float(raw_input("enter the first number"))
b = float(raw_input("enter the second number"))

And 2**a probably should be 2*a , unless you raise 2 to power a . 2**a可能应该是2*a ,除非您提高2来为a赋幂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM