rauf543
rauf543

Reputation: 47

How to take information from input out of a while loop?

My explaining is horrible so Ill put an example what I mean

s=5
while s >= 3:
    name= input("What is the name of your dog")
    s = s-1

this isnt the best piece of code but lets say I wanted to ask the user for a piece of information and they will input 3 different times so how can I take all those 3 value out of the while loop so that they dont get overwriten? If Im not bieng clear please tell me I will try to explain myself better

Upvotes: 2

Views: 79

Answers (4)

Roy
Roy

Reputation: 3287

You'll need to use a list where you can append the names to.

names = list()
s=5
while s >= 3:
    names.append(input("What is the name of your dog"))
    s = s-1

print names[0]
print names[1]
print names[2]

Upvotes: 0

Szabolcs Dombi
Szabolcs Dombi

Reputation: 5783

using generators:

names = [input("What is the name of your dog") for i in range(3)]
print(names)

using list:

names = []

s = 5
while s >= 3:
    name = input("What is the name of your dog")
    names.append(name)
    s = s - 1

using yield:

def names():
    s = 5
    while s >= 3:
        yield input("What is the name of your dog")
        s = s - 1

for name in names():
    print(name)

# or

print(list(names()))

A different solution for your task:

names = input('write all the names: ').split()
print(names)

Upvotes: 1

Rakesh Kumar
Rakesh Kumar

Reputation: 4430

Use List

s=5
name = []
while s >= 3:
    name.append(input("What is the name of your dog"))
    s -= 1

Upvotes: 0

Dartmouth
Dartmouth

Reputation: 1089

You can create a list before the while loop begins, and append an entry every time the loop runs:

s=5
names = []
while s >= 3:
    name= input("What is the name of your dog")
    names.append(name)
    s = s-1

Upvotes: 1

Related Questions