首页 > 解决方案 > python中的重启函数

问题描述

我正在尝试重新启动功能,以便当您获得该功能的答案时,您可以选择使用新数字获得新答案或关闭它。

我尝试使用 def main(),然后最后再次使用 main(),但它不起作用。

所以我在回答打印之后用我的yeslist 做了一个重启功能。,但是因为我不知道要填写什么,所以if restart in yeslist我无法重新启动。那么我该如何管理呢?

   #import required modula
#import math
#from math import sin, pi
import math

#list for answers 
yeslist = ["yes", "y", "yeah" , "oke"]
#function to calculate x**3
def f(x):
    u = x**3
    return(u)
    #return math.sqrt(x) #function 
     #Function



#function for taking positive integer only
def positiveinput(message):
    while True:
        try:
            u= int(input(message))
            if u<= -1:
                raise ValueError
            #return the value of u
            elif u>=0:
                return u
            break
        except ValueError:
            print("oops!! That was no valid number. Try again... ")

a = positiveinput("What is the lowerlimit?:") #2

b = positiveinput("What is the upperlimit?:") #6

n = positiveinput("How many division intervals do you want?:")


#formula to calculate dx
dx = float ((b-a)/n)
xi = a;
Sum = 0;
for i in range(n):
    xi = xi+dx
    Sum = Sum + f(xi)
    #to get only the answer instead of (n * answers)
    if i==n-1:
        print("The surface under the line is %.2f"%(Sum*dx))

        restart= input ("do you want to start again")
        if restart in yeslist :
            input()
        else:
            exit()

标签: pythonrestart

解决方案


你应该把所有你想重复的代码放在一个while循环中。

#import required modula
#import math
#from math import sin, pi
import math

#list for answers 
yeslist = ["yes", "y", "yeah" , "oke"]
#function to calculate x**3
def f(x):
    u = x**3
    return(u)
    #return math.sqrt(x) #function 
     #Function



#function for taking positive integer only
def positiveinput(message):
    while True:
        try:
            u= int(input(message))
            if u<= -1:
                raise ValueError
            #return the value of u
            elif u>=0:
                return u
            break
        except ValueError:
            print("oops!! That was no valid number. Try again... ")

restart = "yes"
while restart in yeslist:
    a = positiveinput("What is the lowerlimit?:") #2

    b = positiveinput("What is the upperlimit?:") #6

    n = positiveinput("How many division intervals do you want?:")


    #formula to calculate dx
    dx = float ((b-a)/n)
    xi = a;
    Sum = 0;
    for i in range(n):
        xi = xi+dx
        Sum = Sum + f(xi)
        #to get only the answer instead of (n * answers)
        if i==n-1:
            print("The surface under the line is %.2f"%(Sum*dx))

            restart = input("do you want to start again")

exit()


推荐阅读