我在启动while循环时遇到困难,试图生成一个程序,该程序将根据用户输入的数字生成饼图或条形图。 while循环是如何编写的,因此它不会永远循环?我知道我可以使用for循环来获得有限序列,但我没有太多的经验。任何指导都会有所帮助!
来自SimpleGraphics import *
打印("图表菜单:1.Pie Chart,2.Bar Chart")
chart = int(输入("为饼图输入1或为条形图输入2:")
如果图表== 1:
title = input("Enter the title of the chart: ")
numSec = int(input("Enter the number of sectors: "))
tSum = int(input("Enter the total sum of all sector values: "))
gsize = int(input("Ehter the grid size (Between 10 and 400): "))
yLabel = input("Enter the label for the Y-Axis:")
while循环
- 每个部门的名称
- 每个部门的价值
- 绘制饼图
如果图表== 2:
title = input("Enter the title of the chart: ")
numCat = int(input("Enter the number of categories: "))
grid = int(input("Ehter the grid size (Between 10 and 400): "))
while循环
- 每个类别的名称
- 该类别的价值
- 绘制条形图
答案 0 :(得分:1)
您必须为用户提供中断while
循环的选项。尝试这样的事情:
while True:
reply = int(input("Chart Menu: 1.Pie Chart, 2.Bar Chart, 3.Exit"))
if reply == 3:
break
elif reply == 1:
# do stuff for pie chart
elif reply == 2:
# do stuff for bar chart
else:
print("Sorry, I don't understand you. Try again, please.")
print("Bye!")
此处while True
是一个无限循环,但break
语句要求Python立即退出循环(在此示例中转到行print("Bye!")
)。
参见例如here有关Python中while
循环的更多详细信息。