简体   繁体   English

在python中用变量打印方程

[英]printing equation with variables in python

I am trying to print the equation with the variables我正在尝试用变量打印方程

I have already tried to put all symbols in quotes我已经尝试将所有符号放在引号中

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)

I wanted it to print out the equation with all the variables and symbols when i type this in i get a syntax error当我输入这个时,我希望它打印出包含所有变量和符号的方程,但出现语法错误

try to put your equation in str() first,then print string so that it will display equation before result.尝试先将方程放入 str() 中,然后打印字符串,以便在结果之前显示方程。 then print out results然后打印结果

You cannot print out strings not in quotes.您不能打印出不在引号中的字符串。 Put the bits you want to print out exactly as written in quotes, and print variables as is.将要打印的位完全按照引号中的写法放置,并按原样打印变量。 For example:例如:

print 'C =', b, '-', d, '+', e, '-', (e/2), '+', ((d - e/2)

Play around with that and see how you go.玩弄那个,看看你怎么走。 You'll want to think about how to do it differently if eg de/2 is negative.如果例如 de/2 为负数,您将需要考虑如何以不同的方式执行此操作。

Also round(b) will do nothing, it does not operate in-place. round(b)也不会做任何事情,它不会就地操作。

Here's what I think you want as a full solution.这是我认为您想要的完整解决方案。 It accepts a single equation string as an input It then fills out that equation with the input variables, prints the resulting equation, and then evaluates it to provide a result:它接受单个方程字符串作为输入,然后用输入变量填充该方程,打印结果方程,然后对其进行评估以提供结果:

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)

Sample result:示例结果:

C = 12 - 24 + 2  - (2/2) + ((6- 2) + 2/2)
C = -6

This code is just a demonstration of what can be done.这段代码只是演示了可以做什么。 You could take these ideas and generalize this to expand a map of variable names and values into an arbitrary expression without hard-coding the variable names.您可以采用这些想法并将其概括为将变量名称和值的映射扩展为任意表达式,而无需对变量名称进行硬编码。 The map and equation could come, for example, from a file.例如,地图和方程可以来自文件。

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

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