Skip to main content

Command Palette

Search for a command to run...

#8 - Python While loops

By Ifeanyi Omeata

Updated
2 min read
#8 - Python While loops
I

Hi, I am a Software Developer of 3-4 years specialising in React, Javascript, Node, NextJS, Express, Python, Django, Fast API, SQL and a few other technology stack, with a good background in Networking and Cloud Infrastructure. I am working to become a DevOps Solutions Engineer and happily married to my long time girlfriend.


Topics:


1. While loops
2. While loops - Guess Game


1. While loops


>>Return to Menu

i=0
while i < 5:
    i+=1
    print(f"{i}."+ "*"*i + "Loops are awesome" + "*"*i)

image.png


2. While loops - Guess Game


>>Return to Menu

print('Guessing game') 
# Guess the correct number in 3 guesses. If you don’t get it right after 3 guesses you lose the game. 
# Give user input box: 1. To capture guesses, 
# print(and input boxes) 1. If user wins 2. If user loses
# Tip:( remember you won’t see  print statements durng execution, so If you want to see prints during while loop, then print to the input box.
#Modification 1: number 1-100, tell user if guess is too high/low ,and let them have 5-10 guesses.
# Tip:( remember you won’t see  print statements during execution, so If you want to see prints during whle loop, print to the input box (This is specific to this platform)
# Three Loop Questions:
#1. What do I want to repeat?
#  -> guesses
#2. What do I want to change each time?
#  -> guess number and number of guesses
#3. How long should we repeat?
#  -> until user loses, runs out of guesses, or wins

num = 76
guess = 0
guess_limit=5
guess_number = 0
guess = int(input(f'Guess a number 1-100: '))
guess_number +=1
while guess_number < guess_limit:

    if guess != num:
        guess_number +=1
        if guess > num:
            guess = int(input(f'{guess} Too high - Guess again 1-100: '))
        else:
            guess = int(input(f'{guess} too low - Guess again 1-100: '))
    if guess == num:
        print(f'You Win! You Guessed it: {guess}')
        break

if guess != num:
    print(f'Sorry you lose! It was {num}')

#End


Hope you enjoyed this! :) Follow me for more contents...


Get in Touch:
www.ifeanyiomeata.com
contact@ifeanyiomeata.com

Youtube: https://www.youtube.com/c/IfeanyiOmeata
Linkedin: https://www.linkedin.com/in/omeatai/
Twitter: https://twitter.com/iomeata
Github: https://github.com/omeatai/
Stackoverflow: https://stackoverflow.com/users/2689166/omeatai
Hashnode: https://hashnode.com/@omeatai
Medium: https://medium.com/@omeatai
© 2022

LEARN PYTHON/DJANGO

Part 29 of 37

Learn Python and Django the easy way!..... PYTHON | DJANGO | FASTAPI

Up next

#7 - Python If, Else, Elif

By Ifeanyi Omeata