python - 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()
解决方案
你应该把所有你想重复的代码放在一个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()
推荐阅读
- python - Python 代码仅在 Linux 集群中存在内存问题/在 Windows 桌面 PC 中正常
- javascript - 控制台记录十进制步数以在 javascript 中编号
- scip - 有没有办法静态编译libscip?
- angular - 在另一个组件中使用 @output 值
- tensorflow - GNN keras:ConcatOp:输入的尺寸应该匹配
- selenium - 如果我们无权使用任何外部包生成报告,我们也不能使用 testng 生成的 html 报告,如何生成报告
- python - 如何只添加在线会员telethon?
- bash - 如何在 makefile 先决条件中使用大括号扩展?
- javascript - Angular从子组件调用父组件函数,从sessionStorage实时更新变量
- css - 导航栏菜单中的列表项是否可以有不同的对齐方式?