gpt4 book ai didi

python - 如何在 python3.3 中使 range() 只有偶数?

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:24 24 4
gpt4 key购买 nike

我是 python 的新手,我想知道是否有一种方法可以编辑 range(100) 以便去掉所有奇数?我正在尝试制作一个简单的“游戏”,您可以在其中想到一个数字,它会告诉您进行一些简单的数学运算,然后告诉您剩下的数字是多少,目前它运行良好,除非它返回一个奇数最后剩下 .5(这不是主要问题,但我宁愿删除它以使其更简单一些)。这是我目前拥有的:

import random, time

numList = range(100)

def getRandomNumber(numList):
numIndex = random.randint(0, len(numList) - 1)
return numList[numIndex]

def restartProg():
print('Do you want to restart? (Y/N)')
return input().lower().startswith('y')

secretNumber = getRandomNumber(numList)
secretNumber = str(secretNumber)
answer = int(secretNumber)/2
answer = str(answer)

while True:
print()
print('Think of a number between 1 and 100.')
time.sleep(3)
print()
print('Now double that number.')
time.sleep(3)
print()
print('Add ' + secretNumber + ' to it.')
time.sleep(6)
print()
print('Now divide it by 2.')
time.sleep(6)
print()
print('And finally, take away the first number you thought of.')
time.sleep(5)
print()
print('Got it?')
time.sleep(5)
print()
print('The number you are left with is... ' + answer + ', right?')
print()
print()
time.sleep(2)

gameDone = True

if gameDone:
if restartProg():
secretNumber = getRandomNumber(numList)
secretNumber = str(secretNumber)
answer = int(secretNumber)/2
answer = str(answer)
gameDone = False
else:
break

最佳答案

使用 range 的三参数形式-- 第三个参数是步长:

range(0, 100, 2)

关于python - 如何在 python3.3 中使 range() 只有偶数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20020077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com