Python While Condition Definition:
In while loop the target code execution takes place until the condition used is TRUE.
Example:
i = 1
while i <= 10:
===>print(i)
===>i += 1
print("Loop completed")
Result:
1
2
3
4
5
6
7
8
9
10
Loop completed
Building a guessing game in Python:
Scope: specify a secrete word. User keep guessing until the secrete word is right
Code:
secret_word = "elephant"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != secret_word and not(out_of_guesses):
===>if guess_count < guess_limit:
======>guess = input("Enter guess: ")
======>guess_count += 1
===>else:
======>out_of_guesses = True
if out_of_guesses:
===>print("Out of Guesses, You Lost the game!")
else:
===>print("You win!")
Result 1:
Enter guess: camel
Enter guess: monkey
Enter guess: rabbit
Out of Guesses, You Lost the game!
Result 2:
Enter guess: lion
Enter guess: tiger
Enter guess: elephant
You win!