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

rauf543
  • 47
  • 6

4 Answers4

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
Dartmouth
  • 1,069
  • 2
  • 15
  • 22
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)
Szabolcs Dombi
  • 5,493
  • 3
  • 39
  • 71
  • 1
    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 – Chris_Rands Aug 10 '16 at 10:15
  • 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]{http://puu.sh/qwdu3.png) 'code' – rauf543 Aug 10 '16 at 10:51
  • you can access the last element with `lst[-1]` where `lst` is the name of your variable. read the [tutorial](https://docs.python.org/3/tutorial/). – Szabolcs Dombi Aug 10 '16 at 16:43
  • the second `while` should be an `if` i guess – Szabolcs Dombi Aug 10 '16 at 16:52
0

Use List

s=5
name = []
while s >= 3:
    name.append(input("What is the name of your dog"))
    s -= 1
Rakesh Kumar
  • 4,319
  • 2
  • 17
  • 30
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]
Roy
  • 3,027
  • 4
  • 29
  • 43