Python Forum

Full Version: Ask again if wrong guess with While.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

I'm learning python and exercising the loop function with while.

I would like to make a code that ask me to input the name again if it's wrong.. with no limit of tries.

name = "Ed"
guess = input("what is the name")

while guess == name:
    print(guess, 'is the right name')
    break
if guess != name:
    print(input(guess))

Wall
You need to get the users input and check if the input is correct inside of the while loop and only break from the loop when it is correct.
Oh Thank you, i got it work now.
Is there another way to do it more simple than

name = "Ed"

while name:
    guess = input("what is the name")
    if guess != name:
     print(guess, 'is wrong')
    else: 
     print(guess, "is the right name")
     break
while name will always be True so you may as well just use while True.
Indentation should be 4 spaces.
You can use f strings.
if name is a constant use capital letters otherwise lowercase is ok.
NAME = "Ed"

while True:
    guess = input("what is the name")
    if guess != NAME:
        print(f"{guess} is wrong")
    else:
        print(f"{guess} is the right name")
        break
If you would like to check against a list of names:

#! /usr/bin/env python3.9

names = ['john', 'mary', 'bob', 'sue']

while True:
    name = input('What is the name: ').lower()
    if name not in names:
        print('That name is not in the list.')
        continue
    else:
        print('That name is in the list.')
        break
Output:
What is the name: charlie That name is not in the list. What is the name: bob That name is in the list.