Python 如何使用tokens=user_input.split()在列表中输入值?
我正在学习Python入门课程,并完成一项关于列表和循环的作业。如对我的代码有任何帮助/指导,将不胜感激。这是我到目前为止编写的代码,返回时出现语法错误:Python 如何使用tokens=user_input.split()在列表中输入值?,python,list,python-3.x,Python,List,Python 3.x,我正在学习Python入门课程,并完成一项关于列表和循环的作业。如对我的代码有任何帮助/指导,将不胜感激。这是我到目前为止编写的代码,返回时出现语法错误: def print_scores(scores): for score in scores: print(str(score), end = " ") print("\n") scores = [1 2 3 4 5] while True: num = int(input('Input a score (-99 terminat
def print_scores(scores):
for score in scores:
print(str(score), end = " ")
print("\n")
scores = [1 2 3 4 5]
while True:
num = int(input('Input a score (-99 terminates)'))
print([score for score in re.split(r'1','2','3','4','5' if score)
if num == -99:
break
scores.append(num)
print_scores(scores)
以下是我的作业说明:
您将在一行中输入所有分数,用空格隔开,完成后,
按回车键。
如果您查看8.3.2,则在调用输入函数后,这一行如下所示。
令牌=用户\输入.split
split函数将值分成不同的值,并将其放入标记中。您可以在程序中使用相同的代码,但请注意,在接下来的几行中,它会将每个值附加到名为nums的列表中。
在我们的示例中,您将向分数列表中添加值。
同样,您将调用print_scores函数来打印您的列表,从而显示您的分数输入有效。这是代码
def print_scores(scores):
for score in scores:
print(str(score), end = " ")
print("\n")
scores = [1, 2, 3 ,4, 5]
while True:
num = int(input('Input a score (-99 terminates)'))
print([score for score in scores])
if num == -99:
break
scores.append(num)
print_scores(scores)
这段代码在python3中工作得非常好。如果要在python2中使用它,请替换语句printstrscore,end=
与
printstrscore语法错误,使用分数=[1,2,3,4,5]使用一个能够验证代码并正确格式化代码的编辑器可能会非常有用。