Recent Posts

While loops


while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.

So we will write a while statement and it will repeatedly execute while it's true

Let's compare if and while statement




 while condition:
... if the condition is true  it will be repeatedly executed


i=1
while i < =7
    print(i)
     i=i+1
print("done")

There will always be an increment until it reaches 7
We stop the infinite loop at 6

Now to make everything more interesting we will put on the 3rd  line print( '*' * 1)







Guessing Game: How to write a loop to build a guessing game
We will try to guess a number and have 3 tries

secret_number = 7
i =  0   ( the numer of guess that has been made)
while i  <= 3



We have the problem that people don't know what i is and what 3 is either.So we refactor "i" with guess_Count, and clarify what is 3



Lines 1,2 and 3 now are more clear. Line 5 we convert to integer.Line 7 , we verify if that is true or not..We fail on purpose to show the results.



It still asking to make 2 more guesses. We need to stop the loop..we will use a break statement to stop it





We are going to let the user know they fail if they don't guess the right number



Here we realized that if guess== secret number (line 7)  is NOT true, use else statement to print that they failed the game. Now the loop terminated properly.



Car Game:


Help:  options  {start, stop, quits}

This game starts with the while condition until it quits: (!=)



We will do upper.case command in case somebody uses upper or lower case.And we need to put the commands start, stop and quit:





We don't want to put .lower in every sentence so we will do some modification


Now we need to print the options stop, start and quit or if somebody put something else, put that doesn't understand that command




It's giving the last error message because we instructed to read start, stop and help only commands

it has a loop ,so we need to add a break to stop the loop


we don't need 2 quits commands so we will end the first one because it  will stop the loop



While True means it will continue executing repeatedly until it breaks 



We got another situation, the car keeps saying it starts several times



so we are going to add some statement

the result is positive and it started yelling to driver that the car has started
While loops While loops Reviewed by ohhhvictor on May 06, 2019 Rating: 5

No comments:

Facebook

 photo imagen120.jpg
Theme images by 5ugarless. Powered by Blogger.