How to use a while loop to make code continue? - python-3.x

Sorry, I tried researching about while loops and the examples that I found didn't help me very much. I am having a hard time understanding the concept outside of peoples examples. I am new to python and most tutorials use a while loop in a different scenario. So here is my code:
# This is a guess the number game.
import random
# Ask the user what their name is
print ('Hello. What is your name?')
name = input ()
# Ask the user if they would like to play a game.
# If user confirms, game continues
# If user denies, game ends
print ('Hi ' + name + ' It is nice to meet you.')
print ('Would you like to play a game with me?')
answer = input()
confirm = ['Yes', 'yes',' Y', 'y', 'Yea', 'yea', 'Yeah', 'yeah', 'Yup', 'yup']
deny = ['No', 'no', 'N', 'n', 'Nope', 'nope', 'Nah', 'nah']
if answer in confirm:
print ('Great! Let\'s get started!')
elif answer in deny:
print ('I am sorry to hear that. Maybe next time? Goodbye') + exit()
print ('I am thinking of a number between 1 and 20.')
print ('Can you guess what the number is?')
secretNumber = random.randint (1, 20)
print('DEBUG: The secret number is ' + str(secretNumber)) # DEBUG
for guessesTaken in range (1, 7):
print ('Take a guess.')
guess = int(input())
if guess < secretNumber:
print ('Your guess is to low.')
elif guess > secretNumber:
print ('Your guess is to high!')
else:
break # This condition is for the correct guess!
if guess == secretNumber:
print ('Good job, ' + name + '! You guessed the number in ' + str(guessesTaken) + ' guesses.')
else:
print ('Wrong. The number I was thinking of was ' + str(secretNumber))
print ('Would you like to play again?')
play_again = input()
if play_again in confirm:
print('# Put code to make game restart')
elif play_again in deny:
print ('Thanks for playing!')
exit()
I would like to use a while loop (because I think thats what I need, please enlighten me if not) at the "if play_again in confirm:" statement to make it return back to the "I am thinking of a number between 1 and 20" line. That way a user can continue to play the game if they choose.
Thankyou in advance. I am also using newest Python.

Your code with while loop added:
# This is a guess the number game.
import random
# Ask the user what their name is
print ('Hello. What is your name?')
name = input ()
# Ask the user if they would like to play a game.
# If user confirms, game continues
# If user denies, game ends
print ('Hi ' + name + ' It is nice to meet you.')
print ('Would you like to play a game with me?')
answer = input()
confirm = ['Yes', 'yes',' Y', 'y', 'Yea', 'yea', 'Yeah', 'yeah', 'Yup', 'yup']
deny = ['No', 'no', 'N', 'n', 'Nope', 'nope', 'Nah', 'nah']
if answer in confirm:
print ('Great! Let\'s get started!')
elif answer in deny:
print ('I am sorry to hear that. Maybe next time? Goodbye') + exit()
while True:
print ('I am thinking of a number between 1 and 20.')
print ('Can you guess what the number is?')
secretNumber = random.randint (1, 20)
print('DEBUG: The secret number is ' + str(secretNumber)) # DEBUG
for guessesTaken in range (1, 7):
print ('Take a guess.')
guess = int(input())
if guess < secretNumber:
print ('Your guess is to low.')
elif guess > secretNumber:
print ('Your guess is to high!')
else:
break # This condition is for the correct guess!
if guess == secretNumber:
print ('Good job, ' + name + '! You guessed the number in ' + str(guessesTaken) + ' guesses.')
else:
print ('Wrong. The number I was thinking of was ' + str(secretNumber))
print ('Would you like to play again?')
play_again = input()
if play_again in confirm:
#print('# Put code to make game restart')
continue
elif play_again in deny:
print ('Thanks for playing!')
break
exit()

Here is a simplified version of what you are trying to do, using a while loop.
import random as rand
target = rand.randint(1,100)
found = False
while not found:
print ("***Random Number Guess***")
guess = int(input("What is your guess?"))
if guess == target:
print("Good guess, you found it!")
repeat = input("Play again? y/n")
if repeat == 'n':
found = True
elif repeat == 'y':
target = rand.randint(1,100)
found = False
else:
if guess < target:
print("too low")
else:
print("too high")

Related

How can I generate new random numbers each time in my while loop in Python for a number game?

I've created a number game where it asks the user if they want to play again and then the loop continues. My program uses import random but I want to know how I'd generate new random numbers without having to make variables each time. (I'm a beginner and I don't know what solution to use pls help)
My code works for the most part it's just that when the loop restarts the same number from the last playthrough repeats so the player ends up getting the same results. Here's my code:
`
import random
random_number_one = random.randint (0, 100)
username = input("Greetings, what is your name? ")
start_game = input("Welcome to the number game, {0}! Would you like to play a game? (Type 'Yes/No') ".format(username))
while True:
if start_game == 'Yes' or start_game == 'yes' :
print("Let's begin!")
print(random_number_one)
user_guess = input("Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: ")
if user_guess == 'H' or user_guess == 'h' :
print("You guessed higher. Let's see: ")
import random
random_number_two = random.randint (0, 100)
print(random_number_two)
if random_number_two > random_number_one :
print("You are correct! It was higher!")
play_again_h = input("Would you like to play again? ('Yes'/'No') ")
if play_again_h == 'Yes' or play_again_h == 'yes' :
continue
else:
break
else:
play_again = input("You were wrong, it was lower. Would you like to play again? ('Yes'/'No') ")
if play_again == 'Yes' or play_again == 'yes' :
continue
else:
break
elif user_guess == 'L' or user_guess == 'l':
print("You guessed lower. Let's see: ")
print(random_number_two)
if random_number_two < random_number_one :
print("You are correct! It was lower!")
play_again_l = input("Would you like to play again? ('Yes'/'No') ")
if play_again_l == 'Yes' or play_again_l == 'yes' :
continue
else:
break
else:
play_again_2 = input("You were wrong, it was higher. Would you like to play again? ('Yes'/'No') ")
if play_again_2 == 'Yes' or play_again_2 == 'yes' :
continue
else:
break
else:
print("Invalid response. You Lose.")
break
elif start_game == 'No' or start_game == 'no':
print("Okay, maybe next time.")
break
else:
print("Invalid response. You Lose.")
break
`
You have to initialize the random number generator with a seed.
See here: https://stackoverflow.com/a/22639752/11492317
and also: https://stackoverflow.com/a/27276198/11492317
(You wrote, you're a beginner, so I give you some hints for cut a few things short...)
import random
#import time #redundant
def get_random(exclude: int = None):
next_random = exclude
while next_random is exclude:
next_random = random.randint(0, 100)
return next_random
#random.seed(time.time())
random.seed() # uses system time!
username = input("Greetings, what is your name? ")
start_game = None
while start_game is None:
start_game = input("Welcome to the number game, {0}! Would you like to play a game? (Type 'Yes'/'No') ".format(username))
if start_game.lower() in ("yes", "y", ""):
print("Let's begin!")
number_for_guess = get_random()
running = True
elif start_game.lower() == "no":
print("Ok, bye!")
running = False
else:
start_game = None
while running:
print(number_for_guess)
next_number = get_random(exclude=number_for_guess)
user_guess = ""
while user_guess.lower() not in list("lh"):
user_guess = input("Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: ")
if user_guess.lower() == "h":
print("You guessed higher. Let's see: ")
print(next_number)
if next_number > number_for_guess:
print("You are correct! It was higher!")
else:
print("You were wrong, it was lower.", end=" ")
else:
print("You guessed lower. Let's see: ")
print(next_number)
if next_number < number_for_guess:
print("You are correct! It was lower!")
else:
print("You were wrong, it was higher.", end=" ")
play_again = "-"
while play_again.lower() not in ("yes", "y", "", "no"):
play_again = input("Would you like to play again? ('Yes'/'No') ")
if play_again.lower() == "no":
running = False
print("Well played, bye!")
You are creating random_number_one only once, when the program starts.
import random
random_number_one = random.randint (0, 100)
username = input("Greetings, what is your name? ")
start_game = input("Welcome to the number game, {0}! Would you like to play a game? (Type 'Yes/No') ".format(username))
while True:
if start_game == 'Yes' or start_game == 'yes' :
print("Let's begin!")
print(random_number_one)
...
So this number is used all the time:
Greetings, what is your name? a
Welcome to the number game, a! Would you like to play a game? (Type 'Yes/No') Yes
Let's begin!
8
Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: H
You guessed higher. Let's see:
86
You are correct! It was higher!
Would you like to play again? ('Yes'/'No') Yes
Let's begin!
8
Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: H
You guessed higher. Let's see:
82
You are correct! It was higher!
Would you like to play again? ('Yes'/'No')
You have to create new random number each time the while loop repeats:
import random
username = input("Greetings, what is your name? ")
start_game = input("Welcome to the number game, {0}! Would you like to play a game? (Type 'Yes/No') ".format(username))
while True:
if start_game == 'Yes' or start_game == 'yes' :
print("Let's begin!")
random_number_one = random.randint (0, 100) # <-- MOVED HERE
print(random_number_one)
...
Then it will work as you except:
Greetings, what is your name? a
Welcome to the number game, a! Would you like to play a game? (Type 'Yes/No') Yes
Let's begin!
96
Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: H
You guessed higher. Let's see:
7
You were wrong, it was lower. Would you like to play again? ('Yes'/'No') Yes
Let's begin!
67
Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: L
You guessed lower. Let's see:
7
You are correct! It was lower!
Would you like to play again? ('Yes'/'No')
Some other small things:
Looks like you missed randint call within the lower option:
...
elif user_guess == 'L' or user_guess == 'l':
print("You guessed lower. Let's see: ")
random_number_two = random.randint (0, 100) # missing in your code
print(random_number_two)
if random_number_two < random_number_one :
print("You are correct! It was lower!")
...
You don't need to import random module each time you want to use function from it:
...
if user_guess == 'H' or user_guess == 'h' :
print("You guessed higher. Let's see: ")
import random # line not needed
random_number_two = random.randint (0, 100)
print(random_number_two)
...
You may change the line:
if user_guess == 'H' or user_guess == 'h':
into:
if user_guess.lower() == 'h':
or:
if user_guess in ('H', 'h'):
Try to split your code into smaller parts with functions.

Variable initialization and loops

I'm new to coding and was trying to make a hangman game. My code works but it does not add and remove letters from the sets above. Could somebody please explain what I'm doing wrong. Thank you in advance. The code is written below;
from random_word import RandomWords
import string
lives = 160
number_of_plays = 0
all_letters = set(string.ascii_lowercase)
print("Please type a letter to play or 1 to quit")
print('You only have 6 chances to guess the correct word')
correct_word = RandomWords()
generated_word = correct_word.get_random_word() # a random word
while number_of_plays < lives:
player_command = input('> ').lower() # player letter input
generated_word_letters = set(generated_word) # tabulates letters in the aforementioned word
guessed_letters = set() # input from the player
correct_guessed_word = (letter if letter in guessed_letters else '_' for letter in generated_word)
if player_command == '1':
print('Game over')
break
elif player_command in all_letters:
guessed_letters.add(player_command)
if player_command in generated_word_letters:
generated_word_letters.remove(player_command)
print('Current correct guessed word: ', ''.join(correct_guessed_word))
continue
elif player_command not in generated_word_letters:
number_of_plays += 1
print('You have lost one life')
print('You have used these letters: ', ''.join(guessed_letters))
print('Current correct guessed word: ', ''.join(correct_guessed_word))
continue
elif player_command not in all_letters:
number_of_plays += 1
print('You have lost one life')
print('Please type in a letter!')
You are on the right track. You just made the mistake of initializing your sets inside the loop. So, what is happening is that every time your loop starts again, you are wiping out what was in them before. Simply initialize your sets before jumping into the loop as shown below. Note: I just overrode your RandomWords with a fixed word for troubleshooting. Nice game!
#from random_word import RandomWords
import string
lives = 160
number_of_plays = 0
all_letters = set(string.ascii_lowercase)
print("Please type a letter to play or 1 to quit")
print('You only have 6 chances to guess the correct word')
#correct_word = RandomWords()
generated_word = "lunch" #correct_word.get_random_word() # a random word
generated_word_letters = set(generated_word) # tabulates letters in the aforementioned word
guessed_letters = set() # input from the player
while number_of_plays < lives:
player_command = input('> ').lower() # player letter input
correct_guessed_word = (letter if letter in guessed_letters else '_' for letter in generated_word)
if player_command == '1':
print('Game over')
break
elif player_command in all_letters:
guessed_letters.add(player_command)
if player_command in generated_word_letters:
generated_word_letters.remove(player_command)
print('Current correct guessed word: ', ''.join(correct_guessed_word))
continue
elif player_command not in generated_word_letters:
number_of_plays += 1
print('You have lost one life')
print('You have used these letters: ', ''.join(guessed_letters))
print('Current correct guessed word: ', ''.join(correct_guessed_word))
continue
elif player_command not in all_letters:
number_of_plays += 1
print('You have lost one life')
print('Please type in a letter!')

I am confused to why my python guessing game is not working properly when I ask to play again

I am trying to get it to ask for me to play again and only accept y or n but I am confused as to why it is not working correctly. I am also getting the count value wrong as I am trying to break out of the while loop answer when I have the answer correct.
#Guessing game
import random
def guess():
playAgain = 'y'
while playAgain != 'n' and playAgain != 'no':
if playAgain == 'y' or playAgain == 'yes':
randomNum = random.randint(1, 2)
answer = 'false'
count = 0
while answer != 'true':
count = count + 1
print("Can you guess the random number?")
guess = int(input())
if guess > randomNum:
print("Too high, guess again.")
if guess < randomNum:
print("Too low, guess again.")
if guess == randomNum:
print("You guessed the number! It too you " + str(count) + " tries.")
answer == 'true'
print("Do you want to play again? (y or n)")
playAgain= input()
else:
print("You must enter y or n")
print("Do you want to play again? (y or n)")
playAgain= input()
guess()
print("Thank you for playing.")
At first glance there are two easy fixes;
You can fix the typo at line 23: answer = 'true'
You can add if playAgain == "n": break at line 26 (below playAgain= input())

Number guessing game that requires suggestions for completion

how do I get the difficulty level to work? I have found other codes similar but the difficulty is based on the group of number that it will choose the number from i.e. easy(1,10), medium (1,50), hard (1,100). I need to know how to make it work for the number of guesses. It keeps telling me I don't have easy,medium, or hard defined. how do I define them in way to make this code work?
I can get through it asking for my name then it will ask for the difficulty level and when I type e,m,or,h this is what it gives me: Traceback (most recent call last): File "C:\Users\ajohn\OneDrive - Fairmont State University\BISM3800\Assign2.py", line 58, in guesses = get_guesses(level) File "C:\Users\ajohn\OneDrive - Fairmont State University\BISM3800\Assign2.py", line 50, in get_guesses if diffuculty == hard: NameError: name 'diffuculty' is not defined
here is the objectives for the code:
You are to ask the user if they wish to play the game or continue playing the game after they have guessed the number
You are to ask the user if they want easy, medium or HARD (Easy = unlimited guesses, Medium = 10 guesses, HARD = 5 guesses)
Once the game begins play you are to tell the user that you have picked a number and they are to guess what that number is
your application is to accept the players guess and if their guess is larger than the number you had picked then tell them that, if their guess is smaller then tell them that as well.
The game continues to play until the player picks the number you had originally picked or they have ran out of guesses. I also need to have an exception.
Here is my code so far:
This is a guessing the number game.
import random
this statement will allow the options for playing and quiting the game.
play = True
while play:
difficulty = 0
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
easy = random.randint (1,100)
easy = random.randint (1,100)
easy = random.randint (1,100)
prompts the user to select a difficulty to play on
def select_level():
while True:
level = str(input("Would you like to play on easy, medium, or hard? \n"
"Type 'e' for easy, 'm' for medium, or 'h' for hard!\n"))
if level != "e" and level != "m" and level != "h":
print("Invalid input!\n")
if level == "e" or level == "m" or level == "h":
break
return level
function that prompts the user to guess depending on chosen difficulty
def guess_number(level):
if level == "e":
(easy == 500)
if level == "m":
(medium == 10)
if level == "h":
(hard == 5)
return guesses
selects number of guesses depending on difficulty selected
def get_guesses(level):
if difficulty == easy:
print ("Okay, " + myName + ". You have unlimited guesses")
if difficulty == medium:
print ("Okay, " + myName + ". You have 10 guesses.")
if diffuculty == hard:
print ("Okay, " + myName + ". You have 5 guesses.")
elif level != "e" and level != "m" and level != "h":
print ("Invalid input!")
get_guesses()
return guesses
level = select_level()
guesses = get_guesses(level)
print('Well, ' + myName + ', I am thinking of a number can you guess it?')
while guessesTaken < level:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed the number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
play = False
Here's the object oriented approach :
from random import randint
class Guessing_Game () :
def __init__ (self, users_name) :
self.difficulty = 10
self.name = users_name
self.start_the_game ()
def start_the_game (self) :
my_secret_number = randint (1, self.difficulty)
print ('Well, ' + self.name + ', I am thinking of a ', end = '')
print ('between 1 and ' + str (self.difficulty) + '.')
print ('Can you guess it?')
self.guess_the_number (my_secret_number)
def guess_the_number (self, the_secret_number) :
still_playing = True
while still_playing == True :
answer = int (input ('Take a guess : '))
if answer == the_secret_number :
print ('That is exactly correct! You win!')
still_playing = False
else :
if answer > the_secret_number :
print ('Sorry, you are too high.')
if answer < the_secret_number :
print ('Sorry, you are too low.')
if self.play_again () == True :
self.start_the_game ()
def play_again (self) :
self.difficulty = self.difficulty * 2
answer = input ('Would you like to play again? ')
if answer [0].lower () == 'y' : return True
return False
users_name = input ('Please enter your name : ')
my_game = Guessing_Game (users_name)

How do you restart a python guess a number game?

I'm a newbie at python, so i couldn't figure out how to make this code repeat at the beginning again. Here is my code:
import random
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guessesTaken < 5:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
Thanks guys, please respond soon,
This must have been the code you've been looking around for
import random
inplay = 0
x = ""
def in_play():
global inplay, guessesTaken
guessesTaken = 0
if inplay == True:
play()
else:
inplay = True
play()
def play():
global guessesTaken
while inplay == True:
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guessesTaken < 5:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
elif guess > number:
print('Your guess is too high.')
elif guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
in_play()
elif guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
in_play()
in_play()
Now that was something basic but for a newbie, we totally know how it feels
Just don't Copy Paste it but try to understand what the code does and why it does it
Put your current code in a function, and then invoke it as many times as you want. For example:
import random
def main():
n_games = 5
for n in range(n_games):
play_guessing_game()
def play_guessing_game():
# Your code here.
print("Blah blah")
main()
Even better would be to accept n_games as a command-line argument (sys.argv[1]). Even better than that would be to stop writing interactive guessing games (rant: why do people teach this stuff?) and instead learn how to write a function that does binary search.
put your code in a function, then create another function that asks the user if he would like to play again.
def main():
game = "your game"
print(game)
play_again()
def play_again():
while True:
play_again = input("Would you like to play again?(yes or no) > ")
if play_again == "yes"
main()
if play_again == "no"
exit()
else:
print("I'm sorry I could not recognize what you entered")
main()

Resources