如何在Python中为用户输入创建列表?

时间:2019-12-30 13:33:38

标签: python string list

编码新手,所以我的知识非常有限。我想为用户输入的名称和姓氏创建一个列表。到目前为止,我已经尝试了一些方法,但是我在网上找到的所有示例仅适用于整数输入,而不适用于字符串输入。

enter image description here

1 个答案:

答案 0 :(得分:0)

此代码将循环播放,直到输入的名字或姓氏为空字符串为止,然后打印列表。


names = []
while True:
    this_f_name = input("First name:\n > ").strip()
    this_l_name = input("Last name:\n > ").strip()

    this_name = [this_f_name, this_l_name]

    if "" in this_name:
        break

    names.append(this_name)

print(names)

示例会话:

First name:
 > John
Last name:
 > Smith
First name:
 > Joe
Last name:
 > Smith
First name:
 > 
Last name:
 > 
[['John', 'Smith'], ['Joe', 'Smith']]
相关问题