Search code examples
pythonwhile-loopnumbersrangedate-range

While loop and ranged numbers in python


Working on a code for school in which I need to modify it to only allow for an input range of 0 to 20o by the user. This is the code so far. Every time I try and place a while loop it doesn't work and I can still enter any value higher than 200. Any help would be appreciated.

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)

Solution

  • Like this?

    def limit_input(prompt):
        while True:
            value = int(input(prompt))
            if value < 200:
                return value
            print( "Please keep your value below 200.")
    
    bar1 = limit_input("What is the height of the first bar?")
    bar2 = limit_input("What is the height of the second bar?")
    bar3 = limit_input("What is the height of the third bar?")
    bar4 = limit_input("What is the height of the fourth bar?")
    

    An exercise left to the reader is to add a try/except ValueError clause to catch when the user types something other than a number.