Python中的重新启动功能

问题描述 投票:0回答:1

我正在尝试制作一个重新启动功能,以便当您获得该功能的答案时,可以选择获取带有新数字的新答案或直接将其关闭。

我尝试使用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()
python restart
1个回答
0
投票

您应该将要重复的所有代码放入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()

© www.soinside.com 2019 - 2024. All rights reserved.