Jr. Essential Multimeadia Round 3 (2018-2019)

WHILE LOOP

my_name = 0
while my_name < 10:
    print "My name is Vutha."

I just wrote a while loop in python code to the computer to print “My name is Vutha” forever. While loop is one of the python code loop using to loop or perform the action until the condition is false. The structure of while loop looks like this:

...
while [condition]:
[action]
...

In my example, my_name = 0 is the variable. while my_name < 10:, while is the loop and my_name < 10: is the condition in a comparison between the value of my_name and an integer 10. Last print “My name is Vutha.” is the action. The computer reads the first line code and sees that my_name has the value equal to 0. The computer takes that value into the while loop and compares it with 10. 0 is less than 10, so the computer continues to read the next line which is the action in the while loop and the action has the value to print “My name is Vutha.” so the computer print:

My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.

FOREVER! It happens like that because of the value of my_name always has the value of 0 forever never change and the computer sees that 0 < 10 is always true never false. If we want the computer to print a certain amount of “My name is Vutha.” , we just need to have a new line of code that looks like this:

my_name = 0
while my_name < 10:
    print "My name is Vutha."
    my_name += 1

The computer reads the same everything until the last line of code in the while loop it updates the value of my_name + 1. Every time, the computer reads the code in the while loop, it updates the value of  my_name + 1 and when it updates the value until 10 it will not print  “My name is Vutha.” because 10 is not less than 10 so the condition is false. It should print the code like this:

My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.
My name is Vutha.

10 TIMES ONLY!

This code is also used while loop. It is a game. Try your best to understand the code!

print "*Please pick a number between 1 and 10. You have only 3 guesses. Try your best to win the game!"

random_number = randint(1, 10)

guesses = 0
while guesses < 3:
    guesses += 1
    number = input("Put a number: ")
    if random_number == number:
        print number, "is correct. You WIN!!! :)"
        break
    else:
        if guesses == 3:
            continue
        print number, "is incorrect. Please, try agian! :("
else:
    print number, "is incorrect. You lose. Game over. Better Luck Nextime! :-"

Leave a Reply

Your email address will not be published. Required fields are marked *