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

Can anyone explain how this condition in python loop works?

name = '' while not name: #(1) print('Enter your name:') name = input()

1 Answer

Hi,

It's a good idea to use Markdown to format your code, it makes it easier for people to read it quickly and then they're more likely to answer :)

Just use three backticks followed by the language name, then another three backticks to close when you're done. e.g.

```Python

Your code here

```

What you posted, then, looks like this:

name = '' 
while not name: 
        print('Enter your name:') 
        name = input()

name='' Firstly, name is set to be an empty string. In Python empty strings evaluate to False in control statements (like while and if)

while not name: This could be considered while (not (name)): first Python evaluates name, it's empty so it comes back false, then the not is considered. Not false is the same as true. A while loop will continue to execute while its condition is true (or truthy but let's not worry about that now). Our condition is true so we go into the loop.

print('Enter your name:') Prints 'Enter your name:` to the screen

name = input() The input function takes whatever you've typed in and returns it as a string, which is then stored in the name variable.

while not name: The while loop then evaluates its condition again. If the user just hit enter and didn't type anything this will be an empty string still, so name will evaluate to false and not name will evaluate to True. If the user has hit any any character key before enter though, even spacebar or a bracket or something, there will be data in the name string, so it name will be True (any data in a string is true) and not name will then equal false, and the loop will not loop again.

Cheers