用python打印带变量的方程
我正试着打印带有变量的方程 我已经试着把所有的符号都用引号引起来了用python打印带变量的方程,python,python-2.7,Python,Python 2.7,我正试着打印带有变量的方程 我已经试着把所有的符号都用引号引起来了 import random import random def ask(): a = raw_input("do you want the equation to be easy, medium, or hard: ") b = int(raw_input("what is the number that you want to be the answer: ")) if(a == "easy"):
import random
import random
def ask():
a = raw_input("do you want the equation to be easy, medium, or hard: ")
b = int(raw_input("what is the number that you want to be the answer: "))
if(a == "easy"):
d = random.randint(1, 10)
e = random.randint(2, 5)
round(b)
print C = b - d + e - (e/2) + ((d - e) + e/2)
我想让它打印出包含所有变量和符号的方程式
当我输入这个时,我得到了一个语法错误请尝试先将您的公式输入str,然后打印字符串 以便在结果之前显示方程式。
然后打印结果您不能打印不带引号的字符串。将要打印的位完全用引号括起来,并按原样打印变量。例如: 打印'C=',b',-',d',+',e',-',e/2',+',d-e/2 好好玩玩,看看你的表现如何。如果d-e/2为负值,您需要考虑如何以不同的方式进行操作
此外,roundb将不起任何作用,它无法正常运行。以下是我认为您需要的完整解决方案。它接受单个方程式字符串作为输入,然后用输入变量填写该方程式,打印结果方程式,然后对其求值以提供结果:
import random
equation = "b - c + e - (e/2) + ((d- e) + e/2)"
b = 12
c = 24
d = random.randint(1, 10)
e = random.randint(2, 5)
# Expand the vlaues into the equation
equation = equation.replace('b', str(b)).replace('c', str(c)).replace('d', str(d)).replace('e', str(e))
# Print the equation
print "C = " + equation
# Evaluate the equation and print the result
C = eval(equation)
print "C = " + str(C)
样本结果:
C = 12 - 24 + 2 - (2/2) + ((6- 2) + 2/2)
C = -6
这段代码只是演示了可以做什么。您可以接受这些想法并对其进行概括,将变量名和值的映射扩展为任意表达式,而无需对变量名进行硬编码。例如,地图和方程式可能来自一个文件。可能的副本