如何提高我在《Think Python》中的第7.4题 eval 和循环的代码

0 投票
5 回答
3478 浏览
提问于 2025-04-17 22:05

任务:

写一个叫做 eval_loop 的函数,这个函数会不断地提示用户输入,然后把用户输入的内容用 eval() 来计算,并把结果打印出来。

这个过程会一直进行,直到用户输入 'done',然后函数会返回最后一次计算的结果。

我的代码:

import math

def eval_loop(m,n,i):
    n = raw_input('I am the calculator and please type: ')
    m = raw_input('enter done if you would like to quit! ')
    i = 0   
    while (m!='done' and i>=0):
        print eval(n)
        eval_loop(m,n,i)
        i += 1
        break;

eval_loop('','1+2',0)

我的代码无法返回最后一次计算的结果!

5 个回答

0

这段代码是用来做某个特定功能的,可能涉及到一些编程的基本概念。它可能包含了变量、函数或者其他编程元素,帮助我们实现想要的效果。

如果你对代码的具体内容有疑问,可以逐行分析,看看每一部分是干什么的。通常,代码的每一行都有它的目的,理解这些目的可以帮助你更好地掌握编程的基本知识。

记住,编程就像是给计算机下指令,代码就是这些指令的集合。通过学习和实践,你会慢慢变得更加熟练。

import math

b = []
def eval_loop():
    a = input('Enter something to eval:')
    if a != 'done':
        print(eval(a))
        b.append(eval(a))
        eval_loop()        
    elif a == 'done':
        print(*b)
eval_loop()
0

这个方法会先对用户输入的内容进行评估,然后把这个输入保存到一个叫b的新变量里。当用户输入“done”这个词时,它会打印出刚刚创建的变量b,正好符合练习的要求。

def eval_loop():
    while True:
        a = input("enter a:\n")
        if a == "done":
            print(eval(b)) # if "done" is entered, this line will print variable "b" (see comment below)
            break
        print(eval(a))
        b = a # this adds the last evaluated to a new variable "b"
eval_loop()
1

这是我写的代码。开始的时候我用的是if和else条件语句,这样可以帮助我理解代码的执行流程。然后我又用while循环重新写了一遍。

    import math
    #using the eval function
    """eval("") takes a string as a variable and evaluates it
    Using (If,else) Conditionals"""

    def eval_(n):
        m=int(n)
        print("\nInput n = ",m)
        x=eval('\nmath.pow(m,2)')
        print("\nEvaluated value is = ", x)
    def run():
        n= input("\nEnter the value of n = ") 
        if n=='done' or n=='Done':
            print("\nexiting program")
            return
        else:
             eval_(n)
        run() # recalling the function to create a loop
    run()

现在我用while循环来做同样的事情。

    "using eval("") function using while loop"

    def eval_1():
        while True:
            n=input("\nenter the value of n = ") #takes a str as input
            if n=="done" or n=="Done": #using string to break the loop
                break
            m=int(n) # Since we're using eval to peform a math function.
            print("\n\nInput n = ",m) 
            x=eval('\nmath.pow(m,2)') #Using m to perform the math
            print("\nEvaluated value is " ,x)        
    eval_1()
1
import math
def eval_loop():
    while True:
        x=input('Enter the expression to evaluate: ')
        if x=='done':
            break
        else:
            y=eval(x)
            print(y)
    print(y)

eval_loop()

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

1

三条评论:

  1. 使用递归的方法会让你最终达到系统的递归限制,所以用循环可能是更好的选择(而且这也是你被要求使用的方法!);
  2. 如果你想要eval的结果,记得要把它赋值给一个变量;
  3. 我不太明白你代码里的i是干什么用的,但看起来对其他部分没有什么帮助。

考虑到这些,简单的概述如下:

def eval_loop():
    result = None
    while True:
        ui = raw_input("Enter a command (or 'done' to quit): ")
        if ui.lower() == "done":
            break
        result = eval(ui)
        print result
    return result

为了让函数更稳健,可以考虑把eval放在try里,这样可以合理处理可能出现的错误。

撰写回答