Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

while loop not working

Hey I copied the exact same code as the solution (see below) for the while loop. But In the solution, as soon as you answer No to 'Would you like to add another player? (Yes/No)', the loop breaks and goes to the new question about the goalkeeper. But my loop doesn't break even if I say No to the question 'Would you like to add another player? (Yes/No)'. Could you please tell me why there is a discrepancy and how do I fix this? My code:

players = []

add_player = input(print('Would you like to add a player to the list? (Yes/No)'))

while add_player.lower() == 'yes':

name = input(print('Enter the name of the player: '))

players.append(name)

another_player = input(print('Would you like to add another player? (Yes/No)'))

I don't really understand the question, but i think its because you dont have any 'if' statements in the while loop to test the 'yes or no' answer... maybe that helped?

10 Answers

This is because you while loop is testing for 'add_player' and not for 'another_player'

try this instead

players = []

add_player = input('Would you like to add a player to the list? (Yes/No) ')

while add_player .lower() == 'yes':

    name = input('Enter the name of the player: ')

    players.append(name)

    add_player = input('Would you like to add another player? (Yes/No) ')
# I noticed a few issues with your code.
# First, you don't need print inside input, if you want to display something to do user and also capture their response
# this is how you would do it with input
user_input = input('What is your name')

# when you used print inside input it was returning None + whatever the user typed in the input
# thus it was not meeting the 'yes' value for the while loop to work
# That was the main reason why your  code wasn't working properly
# also I noticed that you were repeating your code, to be more specific this line:

add_player = input(print('Would you like to add a player to the list? (Yes/No)'))
another_player = input(print('Would you like to add another player? (Yes/No)'))

# If you look at the variable names you would notice that they are different, and
# the problem comes when you reach 'another_player'. What will happen is it will get the user's
# input but no matter what the user type it will still be in our while loop.
# The reason for that is our while loop test's if add_player.lower is == 'yes' and since
# we are not prompted to change the value of add_player it will keep looping and it will never stop
# Yes, we create another_player which will hold our value 'Yes/No', but this variable another_player
# is never tested in our while loop, thus making it pointless.
# The code below would work great in this scenario.
# First we will use a function to add_player(), which allows us to call the function whenever we want
# and we won't have repeating code. Then we will take the outcome of this function and test to see
# if it's == 'yes', if so it will go through and add a new 'name' for player to the players array.
# if you look at our while loop now you would notice that we are calling our function
# which will run again, prompting us whether we want to add player to our players' array, if we say 'no'
# it will update the add_player to 'no' thus making our condition in while loop false and exiting the application

# Here is the improved code, read over it and see the changes that I made
players = []

# def is used to define a function
# the function's name is add_player(), it asks the user whether they want to add a player
# if yes, ask for a name to be added into the players' array
# if no, the loop will no longer be true and the program will stop
def add_player():
    add_player = input('Would you like to add a player to the list? (Yes/No): ')
    # this return add_player will return the result of whatever the user typed, in this case, Yes or No
    return add_player

# Here we use add_player() function to test if the returned result is 'yes'.
# Once it runs once it will keep looping until we say 'no' when asked to add player

while add_player().lower() == 'yes':

    name = input('Enter the name of the player: ')

    players.append(name)

    # Shows the players in the array
    print(players)

Thank you guys!

My apologies. I'm posting my question regarding the Number Guessing Project here because it doesn't provide an option to post it there. My question:

I am receiving an error from this code, saying: TypeError: '<' not supported between instances of 'NoneType' and 'int'.

Could you please direct me towards the correct path? Thanks a ton!

My code:

print('Welcome to the game! The highest score so far is {} trials.')

answer = print(int(input('Guess a number between 1 and 10: ')))

if answer == 5:

print('You got it!')

if answer < 5:

print("It's lower")

if answer > 5:

print("It's higher")
# Your problem is here
answer = print(int(input('Guess a number between 1 and 10: ')))

# You don't need the print() there,
# input() will automatically print whatever is inside the quotes, 'Guess a number between 1 and 10: '
# You get the TypeError because of print(), in this case, print() will return None
# because it's interfering with input(''). To fix it just remove print(), like this

answer = int(input('Guess a number between 1 and 10: '))

Hey, thanks a lot for responding. Also, do we have to use while loops and functions for this assignment?

It all depends on what you are trying to do. I can't see the Number Guessing Projec's description.

Okay. No problem. Basically my code is running just fine. All I am struggling with is how to add the number of guesses a person has entered. My code at the end should say 'It took you {} attempts to get to the correct answer'. The correct answer is 5. Could you please help me with that? Should I use list.append method or....? I would really appreciate your help! Thanks a ton!

answer = []

print('Welcome to the game!')

answer = int(input('Guess a number between 1 and 10: '))

while True:

if answer == 5:
    print('You got it!')
    break
#print('It took you {}  attempts to get to the correct answer'.format(len(answer)))

if answer < 5:
    answer = int(input("It's higher. Try Again: "))

if answer > 5:
    answer = int(input("It's lower. Try Again: "))

if answer > 10:
    print('The number is outside the range')

Hey I fixed the previous error so never mind. But I encountered another problem:

My code is running all fine. It's just that whenever I enter a number greater than 10, it doesn't show the msg 'which is in my last while loop that The number is outside the range. Try Again, even though my while loop clearly states to print this msg when a number greater than 10 is entered. Could you please help?

print('Welcome to the game!')

count=0

answer = int(input('Guess a number between 1 and 10: '))

while True:

if answer == 5:

    print('You got it!')

    count += 1

    print('It took you {} attempts to get to the correct answer.'.format(count))

    break

if answer < 5:
    count += 1
    answer = int(input("It's higher. Try Again: "))

if answer > 5:
    count += 1
    answer = int(input("It's lower. Try Again: "))

if answer > 10:
    count += 1
    answer = int(input('The number is outside the range. Try Again: '))
  • This is how I would do this project
import random

# This will keep track of how many times we guessed a number
guesses = 0
# Default value for answer
answer = 0

# Here we set a default start and end Number, this will allow you to scale your code better
# all you need to do is edit these 2 number to scale the guess numbers
startNumber = 1
endNumber = 10

# It's easier to call print(conditions[0]) rather than print("It's higher. Try Again: "), you can change it if you don't like it
conditions = ["It's higher. Try Again: ", "It's lower. Try Again: ", "The number is outside the range"]

print('Welcome to the game!')

# To make the game more exciting why not randomize the number
# this will hold our magical number which we would have to guess
magicNumber = random.randint(startNumber, endNumber)

# Basic function that allows us to test whether our guess number is lower or higher than the magic number
def numberGuesser():
    if answer > endNumber or answer < endNumber: print(conditions[2])

    if answer < magicNumber and answer >= startNumber: print(conditions[0])

    if answer > magicNumber and answer <= endNumber: print(conditions[1])

# This allows us to avoid creating an else statement on if statements
# it basically will exit out of the while loop when answer == magicNumber
while answer != magicNumber:
    # We should always account for users input. Since this is a number guesser, there shouldn't be any letters when
    # we are guessing the magic number therefore we should wrap our logic in try except to handle errors
    # If you look at the answer, it takes an int from the input but what will happen if the user enters a letter
    # it will throw a ValueError and it will break your code, but we don't want that to happen.. so try except is
    # the way to go
    try:
        # This updates how many times the user tried to guess the number
        guesses += 1

        # Here we take the user's input
        answer = int(input('Guess a number between {} and {}: '.format(startNumber, endNumber)))

        #And here we run our function which tests our answer against the magicNumber
        numberGuesser()
    # This is where we handle the ValueError
    # The following code will run only if the user enters a non numeric number
    except ValueError:

        print('\nPlease enter a number between {} and {}'.format(startNumber, endNumber))

# This will show only when the user guessed the magicNumber
print('You got it!\nIt took you {} attempts to get to the correct answer'.format(guesses))
  • I just updated the logic to the code I posted. Before it wouldn't print the "The number is outside the range", but now it will print it when the user enters a lower number than the startNumber or higher number than the endNumber.