【问题标题】:Python Basic Input ConfusionPython基本输入混淆
【发布时间】:2015-03-13 04:08:35
【问题描述】:

所以我正在尝试自学 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()

【问题讨论】:

  • 请发布您在问题中使用的代码。如果我们不知道您在做什么,我们就无法判断您错过了什么......
  • 检查第一个输入是否有空格,如果没有空格则获取第二个输入

标签: python python-3.x input integer


【解决方案1】:

输入在新行上终止(更准确地说,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 从可迭代对象构造列表。

您可以使用standard library functions 中的sum 来汇总列表。

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

【讨论】:

  • 看起来 OP 正在使用 python 3。
  • 我可以只使用 input 而不是 raw_input 吗?我不认为 python 3 有 raw_input。我还使用 int() 将输入转换为整数。
  • raw_input 在 Python 2 中是 input 在 Python 3 中。
  • @ncerice 修正了我的答案。祝你好运。
  • @ReutSharabani 非常感谢 Reut。看起来我要学习的 Python 比我想象的要多得多:)
【解决方案2】:

这里我修改了你的代码。

def main(): num1 = int(input("Enter first number : ")) num2 = int(input("\nEnter second number : ")) if(num1<=0 or num2<=0): print("Enter valid number") else: numSum = num1 + num2 numProduct = num1 * num2 print("sum of the given numbers is = ",numSum) print("product of the given numbers is = ",numProduct) main()

如果您输入无效号码,它会打印消息输入有效号码。

【讨论】:

  • 您要求使用输入而不是 raw_input。所以答案是你只能使用输入而不是 raw_input。因为 raw_input 用于输入字符串值,而 input 仅用于输入整数值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2012-12-24
相关资源
最近更新 更多