简体   繁体   中英

How to make while True loop running in python?

I want to write a program to have the (name, age, height) where name is string, age and height are numbers for at least 2 users. So I have tried to use a while True loop but it breaks after just one entry (name, age, height). This is because number of items in the list is tree. How could I make a tuple so that the number of items would count as one for all the name, age and height? or is there any easy way?

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

Try

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

It is because you put name instead of dict of user information (name, age, height).

You can use range

Ex:

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)

Or: using a while loop.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM