[英]Python - Setting a limit on a variable
I've just started to learn python, can anyone help me. 我刚刚开始学习python,谁能帮助我。 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: 例如,如果我有一个名为“ speed”的变量,而我只希望它变为100而不是大于0,而不是小于0。但是我也希望代码仍然运行,因此可以将其设置为更低或更高。到目前为止的代码:
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? 我如何在不停止整个代码的情况下使'speed'变量停止在100?
Instead of immediately changing speed
with speed += value
, do the following: 而不是立即使用speed += value
更改speed
,请执行以下操作:
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. 这首先会在speed+value
和0
之间产生一个较高的值,因此,如果它为负数,它将保持为0。然后将其发送到min()
以找到它与100
之间的较低值,因此,如果它大于100,它将将保持在100。
You can then change the check to if speed == 100:
, since it won't go any higher. 然后,您可以将检查更改为if speed == 100:
因为它不会再提高了。
if speed >= 100:
speed=100
text.insert('end', 'You have reached the speed limit')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.