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 Python Basics (2015) Number Game App Number Game Introduction

Maximiliane Quel
PLUS
Maximiliane Quel
Courses Plus Student 55,489 Points

Is there are reason we are not setting the condition in the while statement?

Hi, in this and the previous videos we have been setting the condition of the while statement to True and then adding a break later in the code. Is that a common practice/preferred in python? Would it not be way more efficient use the condition in the while statement itself instead of using a second if statement inside? Or is this in some way sloppy:

import random

def guess(prompt_phrase):
  return int(input(prompt_phrase))

# generate a random number between 1 and 10
secret_number = random.randint(1,10)
# get a number guess from the player
user_guess = guess("I am thinking of a number between 1 and 10. Guess what it is? ")

# compare the guess to the secret number
# print hit or miss

while user_guess != secret_number:
  print("Sorry. That is not the number.")
  user_guess = guess("Guess again! ")

print("You guessed it. Well done.")

1 Answer

Steven Parker
Steven Parker
231,269 Points

It's actually a good practice to include the limit condition in the "while" statement, when that works for the conditions. You'll see it done more often than not in the more advanced courses. It can make the code more concise and easy to read, as you did here.

Good job. :+1: