![]() ![]() Note that you use 41 as the second argument to range() to include 40 in the check. The first example checks if x is inside the 20 to 40 range or interval. > x = 30 > # Between 20 and 40 > x in range ( 20, 41 ) True > # Outside 20 and 40 > x not in range ( 20, 41 ) False In that case, you can use a flag variable to toggle actions in every iteration: Suppose you need to perform two different actions alternatively in a loop. Arguably, the most common use case of the not operator in a non-Boolean context is to invert the truth value of a given variable. In other words, you can use it outside of an if statement or a while loop. Since the not operator can also take regular objects as an operand, you can use it in non-Boolean contexts too. Using the not Operator in Non-Boolean Contexts ![]() That’s what you’ll do in the following section. Now that you know how to use not in Boolean contexts, it’s time to learn about using not in non-Boolean contexts. How was your experience with this little game? To learn more about game programming in Python, check out PyGame: A Primer on Game Programming in Python. Three attempts could be a nice option in this case. Go ahead and give it a try!Īs an exercise, you can restrict the number of attempts before the user loses the game. In every iteration, you check if the input matches secret and provide clues to the user according to the result. You use an infinite while loop to take the user’s input until they guess the secret number. > # Use "not" with numeric values > not 0 True > not 42 False > not 0.0 True > not 42.0 False > not complex ( 0, 0 ) True > not complex ( 42, 1 ) False > # Use "not" with strings > not "" True > not "Hello" False > # Use "not" with other data types > not True > not False > not ! You win!" ) break elif guess > secret : print ( "The secret number is lower than that." ) else : print ( "The secret number is greater than that." ) To get the most out of this tutorial, you should have some previous knowledge about Boolean logic, conditional statements, and while loops. You’ll also code a few practical examples that will allow you to better understand some of the primary use cases of the not operator and the best practices around its use.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |