简体   繁体   中英

Python - Setting a limit on a variable

I've just started to learn python, can anyone help me. For example if I had a variable called 'speed' and I only wanted it to go to 100 and not above, and not to go below 0. But I also want the code to still run so I could set it lower or higher, my code so far:

import tkinter as tk
speed = 80
def onKeyPress(event, value):
    global speed 
    text.delete("%s-1c" % 'insert', 'insert')
    text.insert('end', 'Current Speed: %s\n\n' % (speed, ))
    speed += value 
    print(speed)
    if speed >= 100:
        text.insert('end', 'You have reached the speed limit')


speed = 80

root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()

# Individual key bindings
root.bind('<KeyPress-w>', lambda e: onKeyPress(e, 1)) 
root.bind('<KeyPress-s>', lambda e: onKeyPress(e, -1)) #

root.mainloop()

How would I get the 'speed' variable to stop at 100 without stopping the whole of the code?

Instead of immediately changing speed with speed += value , do the following:

speed = min(max(speed+value, 0), 100)

This first produces the higher value between speed+value and 0 , so if it's negative, it will stay at 0. It then sends that to min() to find the lower value between it and 100 , so if it's higher than 100, it will stay at 100.

You can then change the check to if speed == 100: , since it won't go any higher.

if speed >= 100:
    speed=100
    text.insert('end', 'You have reached the speed limit')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM