python 如何打印偶整数和奇整数的计算结果?

jxct1oxe  于 2022-12-02  发布在  Python
关注(0)|答案(1)|浏览(175)

程序说明如下:您的程式应该根据下列需求,计算随机产生的整数清单中有多少个值是奇数,有多少个是偶数:
从用户处获取要生成的值的数目沿着值的范围。计算奇数值和偶数值的总数后,显示结果并允许用户继续生成和计算新的值集,直到用户选择退出。
程序运行示例:
输入所需的值数目:100输入值范围的上限,从1到:50奇数值:48.7%平均值:51.3%是否要生成一组新值?(Y/N)Y输入所需的值数:20输入值范围的上限,从1到:100奇数值:40.0%平均值:60.0%是否要生成一组新值?(Y/N)N
我能够让它打印前两个提示,但后来似乎是无限加载。

import random
#if play is True when game starts
play = True
while play:
#Prompt user with Enter number of values needed:

    num_values = int(input())
    print("Enter number of values needed:", num_values)
# get user input of how many values to generate for i in range(0, num_values)

    for i in range(0,num_values):
        #Prompt user with Enter high end of value range from 1 to:

        high_end = int(input())
        print("Enter high end of value range from 1 to:", high_end)

        #Get range of values from 1 to user_input list1 = random.randrange(1,user_input)

       list1 = random.randrange(1, high_end)
    def even():
        even_count=0
        if (list1 % 2) == 0:#finds odd numbers
            even_count += 1 #keeps count of even  numbers
        return even_count 

    def odd():
        odd_count=0
        if (list1 % 2) != 0:#finds odd numbers
            odd_count += 1 #keeps count of even  numbers
        return odd_count 
    even_total = even_count / num_values
    odd_total = odd_count / num_values
    print("Odd values:", odd_total)`your text`
    print("Even values:", even_total)


letter = str(input())
print("Do you want to generate a new set of values? (Y/N)", play)
    if letter != 'Y':
        play = False

这是我目前的代码,我被要求至少有两个函数。我不确定为什么我的even_values/odd_values没有正确处理。

j91ykkif

j91ykkif1#

1.该范围由两个值组成,不必从1开始。
1.任务是创建一个列表。创建一个list1变量,并在循环中为每个数字指定一个范围
1.你不调用你写的函数

import random
 play = True
 while play:
     print("Enter number of values needed: ", end = "")
     num_values = int(input())
     print("Enter start of value range from 1 to: ", end = "")
     start = int(input())
     print("Enter end of value range from 1 to: ", end = "")
     end = int(input())
     list1 = []
     for i in range(0,num_values):
         list1.append(random.randint(start, end))
     print(list1)

     def even():
         even_count = 0
         for i in list1:
             if i % 2 == 0:
                even_count += 1
         return even_count

     def odd():
         odd_count = 0
         for i in list1:
             if i % 2 != 0:
                 odd_count += 1
         return odd_count

     even_total = (even() / num_values) * 100
     odd_total = odd() / num_values
     print(f"Odd values:{odd_total}%")
     print(f"Even values:{even_total}%")

     print("Do you want to generate a new set of values? (Y/N)")
     letter = str(input())
     if letter != 'Y':
         play = False

相关问题