【发布时间】:2021-04-20 17:59:14
【问题描述】:
正在为学校编写代码,我需要将其修改为仅允许用户输入 0 到 20o 的范围。这是到目前为止的代码。每次我尝试放置一个 while 循环时,它都不起作用,我仍然可以输入任何高于 200 的值。任何帮助将不胜感激。
import turtle #allows access to a collection of Python functions that make it possible to draw
Jane = turtle.Turtle() #creates a "turtle" to do our drawing for us; we will call the turtle Jane
# the next four lines get input from the user so we know how tall to make the bars in the graph
bar1 = int(input("What is the height of the first bar?" ))
bar2 = int(input("What is the height of the second bar?" ))
bar3 = int(input("What is the height of the third bar?" ))
bar4 = int(input("What is the height of the fourth bar? "))
#the turtle always starts out facing left; the next line rotates it so it faces up
Jane.left(90)
#next we will create a function that will draw one bar of the bar graph
#the function requires us to pass the height of the bar into it
def bar(height):
#Jane will make a line that is as long as the height that the user inputted
Jane.forward(height)
#now we will turn Jane to the left to make the top of the bar
Jane.left(90)
#now Jane needs to more forward to draw the top of the bar
Jane.forward(20)
#now Jane needs to turn left
Jane.left(90)
#now Jane needs to draw a line that is as long as the height
Jane.forward(height)
#now Jane needs to rotate 180 degrees to be ready for the next bar
Jane.right(180)
#now we will call the function four times--one for each bar. Notice that
#we will go in the order 4-3-2-1, since the bars will be drawn from right to left
bar(bar4)
bar(bar3)
bar(bar2)
bar(bar1)
【问题讨论】:
-
这里没有任何东西试图限制范围。你需要限制所有的输入吗?如果是这样,那么显而易见的答案是创建一个函数,可能称为
limited_input,它接受一个提示字符串作为参数。它可以执行while循环并继续执行提示,直到值在范围内。 -
哪里不能放while循环,要在哪里放while循环?
标签: python while-loop numbers range date-range