Skip to content Skip to sidebar Skip to footer

Beginner Python Loop

New to python and having which is probably a basic issue when trying to get a loop to work. I have read some previous questions similar but couldn't find a solution that works. I

Solution 1:

You can use a while loop to repeat until the user enters a correct input. Use a break to exit from the loop.

myPets = ['Zophie', 'Pooka', 'Fat-tail']
whileTrue:
    print('Enter a pet name.')
    name = input()
    if name notin myPets:
        print('I do not have a pet named ' + name + ' try again')
    else:
        print(name + ' is my pet.')
        break

Solution 2:

For this task you should use a while loop like this :

myPets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a pet name.')
name = input()
while name notin myPets:
    print('Enter a valid pet name.')
    name = input()
print(name + ' is my pet.')

Each time the user enters something, the condition is evaluated. If your condition is correct, you'll keep asking for another input from the user until it matches your requirements.

Solution 3:

while is the keyword you need. use while loop It helps you repeat a set of statements while a condition is satisfied (i.e. until something new happens e.g entered name is one of your pets).

You can also pass your input message as an argument to the input() method.

myPets = ['Zophie', 'Pooka', 'Fat-tail']
name = input("Enter pet name")
while name notin myPets:
    print('I do not have a pet named ' + name + ' try again')
    name = input("Enter pet name")
print(name + ' is my pet.')

Solution 4:

here is what you are looking for:

myPets = ['Zophie', 'Pooka', 'Fat-tail']

done=Fasle
while not done:
    name=input("enter a pet name: ")
    if name in myPets:
       done=True
       print(name + ' is my pet.')
    else:
        print('I do not have a pet named ' + name + ' try again')

Solution 5:

You can use a simple while loop:

myPets = ['Zophie', 'Pooka', 'Fat-tail']
loop=0while loop==0:
    print('Enter a pet name.')
    name = input()
    if name notin myPets:
        print('I do not have a pet named ' + name + ' try again')

    else:
        print(name + ' is my pet.')
        loop=loop+1

Or:

Use a recursion loop (not recommended):

myPets = ['Zophie', 'Pooka', 'Fat-tail']
defask():
    print('enter pet name')
    name = input()
    if name notin myPets:
        print('I do not have a pet named ' + name + ' try again')
        ask()

    else:
        print(name + ' is my pet.')

ask()

Post a Comment for "Beginner Python Loop"