首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >不使用sys模块计算最小输入数

不使用sys模块计算最小输入数
EN

Stack Overflow用户
提问于 2022-10-24 03:39:22
回答 2查看 44关注 0票数 1

用Python编写一个程序,从用户读取整数输入(数据)序列,然后输出以下结果:

所有输入的总数,最小的输入,最大的输入,偶数输入的数目,奇数输入的数目,所有输入的平均值。

您不知道用户需要输入多少个数字,所以每次您都必须询问她是否有其他数字要添加到序列中。

到目前为止,这是我的代码,但是我想知道是否有一种不用sys模块的方法

代码语言:javascript
运行
复制
import sys

# declare a variable largest which has smallest integer value
# -sys.maxsize gives the smallest integer value,you can also use any smallest value 
largest = -sys.maxsize
# declare a variable smallest, that is assigned with maximum integer value
smallest = sys.maxsize
# declare variables total to store the sum of all numbers
total = 0
# option variable is to store the user option  Y or N
option = 'y'
# declare variables to count odd, even and totalCount
evenCount = 0
oddCount = 0
totalCount = 0
print("This program will calculate statistics for your integer data.")

# run the loop when the user enters y or Y
while option == 'y' or option == 'Y':
    # take input of number
    number = int(input("Please type a number: "))
    # add the number to total
    total = total + number
    # increase totalCount
    totalCount = totalCount + 1
    # calculate smallest
    if number < smallest:
        smallest = number
        # calculate largest
    if number > largest:
        largest = number
    # calculate count of even and odd numbers
    if number % 2 == 0:
        evenCount = evenCount + 1
    else:
        oddCount = oddCount + 1
    option = input("Do you have another number to enter? ")

# calculate average
average = total / totalCount
# print the output
print("\nThe total of your numbers is:", total)
print("The smallest of your numbers is:", smallest)
print("The largest nof yout numbers is:", largest)
print("The number of even numbers is:", evenCount)
print("The number of odd numbers is:", oddCount)
print("The average of your numbers is:", average)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-10-24 03:47:01

答案是“能做得到吗?”在编程方面,几乎总是“是的”。

在这种情况下,您可以测试是否处于第一个循环迭代,并相应地设置smallestlargest

例如。

代码语言:javascript
运行
复制
option = 'y'
first_loop = True

while option.lower() == 'y':
  x = int(input("Please type a number: "))
  if first_loop:
    smallest = x
    first_loop = False
  elif x < smallest:
    smallest = x
  option = input("Do you have another number to enter? ")

print(f"Smallest number entered is {smallest}")

您还可以将输入数字收集到列表中。

代码语言:javascript
运行
复制
option = 'y'
inputs = []

while option.lower() == 'y':
  x = int(input("Please type a number: "))
  inputs.append(x)
  option = input("Do you have another number to enter? ")

现在,如果您有inputs中的所有输入数字,那么计算最小值和最大值的值就是min(inputs)max(inputs)

票数 0
EN

Stack Overflow用户

发布于 2022-10-24 03:46:57

有趣的方法,当我遇到这样的问题时,我会使用float('inf')float('-inf')。可以很容易地运用到你的方法中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74176488

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档