2

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

2
  • Use a list to store the input Commented Aug 10, 2016 at 10:07
  • Wrap this in a function and "yield" each time in while loop Commented Aug 10, 2016 at 10:07

4 Answers 4

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a bunch for the quick response
1

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)

4 Comments

Given the poster is clearly a beginner, I do wonder if introducing them to generators is the best idea. For such a small loop, memory usage will not be an issue, so list creation seems just fine
Sorry another quick question Following on from my last question I was wondering If its possible to have a print change the value of what its printing on the list by itself for example since I dont know how to format here is a screenshot of the code [link]{puu.sh/qwdu3.png) 'code'
you can access the last element with lst[-1] where lst is the name of your variable. read the tutorial.
the second while should be an if i guess
0

Use List

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

Comments

0

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]

2 Comments

it gives me raw_input is not defined
@rauf543 ah, I'm just using an old version of python. input should be fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.