Python 基本输入困惑

标签 python python-3.x input integer

所以我正在尝试自学Python,但在完成这项任务时遇到了一些问题。我试图从键盘读入两个整数,但问题是它们可以在同一行或两个不同行上读入。

输入示例:

23 45

23
45

每个数字都应该放到它自己的变量中。 我很确定我应该使用剥离/分割功能,但是我还缺少什么?我真的不知道该怎么做...谢谢。

这是我正在处理的内容,但显然这个版本每行都取数字一。

def main():
  num1 = int(input())
  num2 = int(input())
  numSum = num1 + num2
  numProduct = num1 * num2
  print("sum = ",numSum)
  print("product = ",numProduct)
main()

最佳答案

输入在新行上终止(更准确地说,sys.stdin 在新行上刷新),因此您可以获得整行。要拆分它,请使用:

inputs = input("Enter something").split() # read input and split it
print inputs

应用到您的代码中,它看起来像这样:

# helper function to keep the code DRY
def get_numbers(message):
    try:
        # this is called list comprehension
        return [int(x) for x in input(message).split()]
    except:
        # input can produce errors such as casting non-ints
        print("Error while reading numbers")
        return []

def main():
     # 1: create the list - wait for at least two numbers
     nums = []
     while len(nums) < 2:
         nums.extend(get_numbers("Enter numbers please: "))
     # only keep two first numbers, this is called slicing
     nums = nums[:2]
     # summarize using the built-in standard 'sum' function
     numSum = sum(nums)
     numProduct = nums[0] * nums[1]
     print("sum = ",numSum)
     print("product = ",numProduct)

main()

此处使用的注释:

您可以使用list comprehension从可迭代对象构造列表。

您可以使用sum来自standard library functions总结列表。

您可以slice如果您只想要列表的一部分,则列出。

关于Python 基本输入困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27952021/

相关文章:

python - 从包含一个或多个标记的字符串构建字典

python - 如何在区域上方激活功能,在限制区域外保持事件状态

python - 在python中更改多进程的局部变量

python - Python 与 kivy 语言的 Canvas 中心

python - Pandas - DataFrame 将列或旋转列转换为新行

python - 内部类 - 继承和覆盖它们的属性

python - 如何使用 python3 循环读取文件 N 行并 POST 到服务器

c++ - 从输入文件中读取并存储在数组 C++ 中

javascript - 将 img src 插入输入 onClick

css - Bootstrap 2.0.2 - 输入追加空格