如何使True循环在python中运行?

时间:2019-01-17 10:38:02

标签: python python-2.7

我想编写一个程序(姓名,字符串,年龄和身高是至少2位用户的数字)(姓名,年龄,身高)。因此,我尝试使用一会儿True循环,但仅在一个条目(名称,年龄,身高)之后就中断了。这是因为列表中的项目数是树。我如何制作一个元组,以便所有名称,年龄和身高的项目数都可以算作一个?还是有什么简单的方法?

data=[]

while True:

   name = raw_input("Please enter your name: ")
   age = int(raw_input("Please enter your age: "))
   height = int(raw_input("Please enter your height: "))

   data.append(name)
   data.append(age)
   data.append(height)

   if len(data) <2:
     print "you need to enter at least 2 users"
   else:
       break   
   print data

2 个答案:

答案 0 :(得分:1)

尝试

data=[]

while len(data) < 2:

   name = raw_input("Please enter your name: ")
   age = int(raw_input("Please enter your age: "))
   height = int(raw_input("Please enter your height: "))

   data.append({
      'name': name,
      'age': age,
      'height': height,
  })

print data

这是因为您放置了name而不是用户信息(名称,年龄,身高)的决定。

答案 1 :(得分:0)

您可以使用range

例如:

data=[]

for _ in range(2):
    name = raw_input("Please enter your name: ")
    age = int(raw_input("Please enter your age: "))
    height = int(raw_input("Please enter your height: "))
    data.append((name, age, height))
print(data)

或:使用while循环。

data=[]

while True:
    name = raw_input("Please enter your name: ")
    age = int(raw_input("Please enter your age: "))
    height = int(raw_input("Please enter your height: "))
    data.append((name, age, height))

    if len(data) == 2:
        break

print(data)