我刚刚开始学习代码,并且正在编写一个简单的程序。 我正在尝试找出如何找到一个数字在其中的步骤的范围。例如,我的范围是0到101,步长是10。 假设数字是33,所以它所处的步幅范围是30到40。
如何找到这些较低和较高的值,或者该如何使用?
我对此有一个解决方案,但它很混乱,我想找到一种更好的方法来避免重复代码。在这里
import random
number = random.randint(1, 100)
def help():
if number in range(0, 11):
print ("It's between 0 and 10")
if number in range(10, 21):
print ("It's between 10 and 20")
if number in range(20, 31):
print ("It's between 20 and 30")
if number in range(30, 41):
print ("It's between 30 and 40")
if number in range(40, 51):
print ("It's between 40 and 50")
if number in range(50, 61):
print ("It's between 50 and 60")
if number in range(60, 71):
print ("It's between 60 and 70")
if number in range(70, 81):
print ("It's between 70 and 80")
if number in range(80, 91):
print ("It's between 80 and 90")
if number in range(90, 101):
print ("It's between 90 and 100")
print (number)
help()
所以我基本上需要使这段代码自动化,以便我只需要传递值即可获得相同的输出。
答案 0 :(得分:1)
使用这样的打印:
print ("It's between "+str(number//10*10) +" and "+str((number//10+1)*10))
答案 1 :(得分:-2)
import random
number = random.randint(1, 100)
def help():
n=0
while True:
if number<n:
print("It's between ",n-10,n)
break
n+=10
print (number)
help()