这是我的计划:
import random
def main():
print('Generating 100 random numbers, this program will determine how many are even and how many are odd.')
for count in range(1):
even = 0
odd = 0
for count in range(100):
numbers = random.randint(1, 100)
print(numbers)
if numbers % 2 == 0:
even += 1
else:
odd += 1
print('Out of 100 random numbers,', even, 'are even and', odd, 'are odd.')
main()
基本上,它的作用是打印出100个随机数字并告诉我有多少是偶数,有多少是奇数。该程序运行完美,唯一的问题是我必须使用"返回真/假"赋值的布尔值表达式。
我知道如果我要这样做,我必须在程序中添加另一个定义函数,但我不知道该怎么做。
有谁知道如何将True / False布尔表达式合并到这个程序中?
答案 0 :(得分:2)
制作像
这样的辅助功能# Longer function, but satisfies the requirements of using True/False and return
def isEven(x):
if x % 2 == 0:
return True
else:
return False
然后您可以在main
函数
for count in range(100):
numbers = random.randint(1, 100)
print(numbers)
if isEven(numbers): # Notice we're using the helper function here
even += 1
else:
odd += 1
答案 1 :(得分:0)
def is_even(x):
return not x % 2
"""
An alternate way using explicit True/False
def is_even(x):
if not x % 2:
return True
return False
"""
def count_odds_evens():
for _ in xrange(100): # use range if using Python 3.x
num = random.randint(1, 100)
print(num)
if is_even(num):
even += 1
else:
odd += 1
return even, odd
if __name__ == '__main__':
evens, odds = count_odds_evens()
print('Out of 100 random numbers, {} are even and {} are odd.'.format(evens, odds))
稍微更惯用的版本。使用if __name__ == '__main__'
允许使用您在其他程序中创建的函数,而无需立即执行它们。
答案 2 :(得分:-2)
代码应如下所示:
import random
def main():
even,odd = 0,0
print('Generating 100 random numbers, this program will determine how many are even and how many are odd.')
for count in range(100):
numbers = random.randint(1, 100)
print(numbers)
if numbers % 2 == False:
even += 1
else:
odd += 1
"""
Alternative checking odd in if
if numbers % 2 == True:
odd += 1
else:
even += 1
"""
print('Out of 100 random numbers,', even, 'are even and', odd, 'are odd.')
main()