在python中接受输入直到换行
我是python初学者。我尝试接受用户的输入,只要他/她愿意。仅按下回车键时,程序应停止接受输入 就是在python中接受输入直到换行,python,Python,我是python初学者。我尝试接受用户的输入,只要他/她愿意。仅按下回车键时,程序应停止接受输入 就是 25 65 69 32 #stop here since the enter key was pressed without any input 我想出了下面的代码来做这件事 a = [] while 1: b = input("->") if(len(b)>0): a.append(b) else: break
25
65
69
32
#stop here since the enter key was pressed without any input
我想出了下面的代码来做这件事
a = []
while 1:
b = input("->")
if(len(b)>0):
a.append(b)
else:
break
你的方法基本上是好的。你可以这样写:
a = []
prompt = "-> "
line = input(prompt)
while line:
a.append(int(line))
line = input(prompt)
print(a)
def read_input(prompt):
x = input(prompt)
while x:
yield x
x = input(prompt)
xs = list(map(int, read_input("-> ")))
print(xs)
NB:我没有包括任何错误处理
关于你的其他问题:
raw\u input()
在Python2.7中的工作方式应该类似int()
——将给定参数保留为整数。如果不能,它将失败并出现TypeError
input()
替换为raw\u input()
出于教育目的,您也可以用功能性风格编写,如下所示:
a = []
prompt = "-> "
line = input(prompt)
while line:
a.append(int(line))
line = input(prompt)
print(a)
def read_input(prompt):
x = input(prompt)
while x:
yield x
x = input(prompt)
xs = list(map(int, read_input("-> ")))
print(xs)
可能是我所知道的最巧妙的方式(不幸的是,没有错误处理,这就是为什么在生产中您不会经常看到它的原因): 这使用了iter的两个参数调用签名,它调用第一个参数(
input
),直到返回第二个参数(此处为空字符串)
你的方式还不算太糟,尽管在变化中更常见
a = []
while True:
b = input("->")
if not b:
break
a.append(b)
事实上,使用break
和continue
是极少数情况下,许多人在使用一行if
时使用的一种
a = []
while True:
b = input("->")
if not b: break
a.append(b)
尽管这是官方不赞成的(tm)。在if语句周围不需要括号,但使用
int('string')
将字符串更改为整数请注意Python中的空格。我意识到您的代码示例混合了制表符和公共空间。使用大量函数并不会产生任何“功能性”或“功能性风格”(从功能范例的意义上讲)。使用迭代而不是递归的函数编程是非常。。。有趣的是,它仍然是“功能性”的,因为它使用函数包装功能和迭代结果。包装产生副作用的input()
函数。它当然不是严格意义上的纯函数,但是:)还要记住,内置的iter
采用了一个哨兵参数,并与生成器做相同的事情。所以它可以归结为[int(x)for x in iter(lambda:input('->'),'')
。是的。但这可能有点太过分了吧?:)我指的是一艘邮轮?:)