繁体   English   中英

Python-为变量设置限制

[英]Python - Setting a limit on a variable

我刚刚开始学习python,谁能帮助我。 例如,如果我有一个名为“ 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()

我如何在不停止整个代码的情况下使'speed'变量停止在100?

而不是立即使用speed += value更改speed ,请执行以下操作:

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

这首先会在speed+value0之间产生一个较高的值,因此,如果它为负数,它将保持为0。然后将其发送到min()以找到它与100之间的较低值,因此,如果它大于100,它将将保持在100。

然后,您可以将检查更改为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.

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