Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python while loop

# the below game will help you see how you can use while in Python

# we can use the random number generator 
from random import randint

# docstring: https://peps.python.org/pep-0257/
logo = '''
❓❓❓ WELCOME TO GUESS THE NUMBER ❓❓❓
'''
# display logo
print(logo)

# randomly generate a number
answer_num = randint(1, 100)
print(answer_num)
 
# number of turns, start at 0
num_of_turns = 0

# game difficulty
game_level = input('Choose game difficulty - type "easy" or "hard": ').lower()

# check what the user chose
# user chose easy - num_of_turns will be assigned the value of 5
if game_level == 'easy':
    num_of_turns = 5
# user chose easy - num_of_turns will be assigned the value of 3
elif game_level == 'hard':
    num_of_turns = 3
# user typed something random - num_of_turns is not updated, stays 0
else:
    print('invalid entry.')
    

# continue guess (flag): this will make it possible for us to get out of the loop
continue_guess = True

while continue_guess == True:
    
    if num_of_turns < 1:
        print('goodbye!')
        continue_guess = False
    else: 
        #  user guess 
        guess_number = int(input('guess a number between 1 and 100: '))
        
        if guess_number > answer_num:
            num_of_turns -= 1
            print(f'guess too high! | {num_of_turns} turns remaining.')
        elif guess_number < answer_num:
            num_of_turns -= 1
            print(f'guess too low! | {num_of_turns} turns remaining.')
        elif guess_number == answer_num:
          	# user won, get out of the loop
            print(f'You guessed it right! | correct guess: {guess_number}')
            # update your flag from True to False to get out of the loop
            continue_guess = False
        else:
          	# user typed something random, get out of the loop
            print('invalid entry!')
            continue_guess = False
            
Source by www.programiz.com #
 
PREVIOUS NEXT
Tagged: #python #loop
ADD COMMENT
Topic
Name
8+1 =