Repeating a whole algorithm - python-3.x

I am a real newbie to Python, I am taking it for GCSE at my school and I have been given an assignment to complete. I completed all of the requirements for this simple code but am not sure how to repeat it. Could someone please show me a simple way of repeating the code?
Thanks
import random
Random = random.randint(1,100)
Guess = int(input("Please guess a number between 1 and 100: "))
counter = 1
while Guess != Random:
if Guess > Random:
print("Too high")
Guess = int(input("Please guess the number: "))
else:
print("Too low")
Guess = int(input("Please guess the number: "))
counter += 1
print("Well Done:")
print("You took:",counter, "Guesses")

Easiest way of doing it would be to put it in a while True loop with a conditional break:
import random
while True:
Random = random.randint(1,100)
Guess = int(input("Please guess a number between 1 and 100: "))
counter = 1
while Guess != Random:
if Guess > Random:
print("Too high")
Guess = int(input("Please guess the number: "))
else:
print("Too low")
Guess = int(input("Please guess the number: "))
counter += 1
print("Well Done:")
print("You took:",counter, "Guesses")
choice = input("Would you like to continue? y/n")
if choice == "n":
break
Note, randint(1,100) will return a number from 1-99 inclusive, and you are actually asking the user for a guess 2-99 inclusive the way you have phrased it.

Related

How do I get back to the top of a while loop?

so I am trying to make a guessing game on my own and when the game ends I hope it will prompt the player if he wants to play again by typing yes or no like this:
Guess a number between 1 to 10: 7
YOU WON!!!!
Do you want to continue playing? (y/n) y
Guess a number between 1 to 10: 7
YOU WON!!!!
Do you want to continue playing? (y/n) n
Thank you for playing!
I managed to get the game working but I can't play the game again. I am stuck here:
guess = int(input("Guess a number between 1 and 10: "))
while True:
if guess > num:
print("Too high, try again!")
guess = int(input("Guess a number between 1 and 10: "))
elif guess < num:
print("Too low, try again!")
guess = int(input("Guess a number between 1 and 10: "))
else:
print("You guessed it! You won!")
replay = input("Do you want to continue playing? (y/n) ")
if replay == "y":
**what to insert here???**
else:
break
I don't know what to type inside the if statement that will return my code to the top of the loop if the user press "y" and allows me to restart the game.
Any help will be appreciated! Please do not give me the entire solution but try to give me hints so I can solve this by myself! Thank you!
you can use the continue statement as it returns the control to the beginning of the while loop, in python.
You have to use two while loops. The first one to decide whether the player wants to play again or not and the second one is to get guess from the user until the user does the correct guess.
while True:
guess = int(input("Guess a number between 1 and 10: "))
wantToPlay = False
while True:
if guess > num:
print("Too high, try again!")
guess = int(input("Guess a number between 1 and 10: "))
elif guess < num:
print("Too low, try again!")
guess = int(input("Guess a number between 1 and 10: "))
else:
print("You guessed it! You won!")
replay = input("Do you want to continue playing? (y/n) ")
if replay == "y":
wantToPlay = True
else:
break
if wantToPlay == False:
break

How do i make my input take all int and str type of data

I'm trying to get a guessing game with the user input as an answer and if the user type exit the game will show the amount of time the player tried but the program won't run because it can only take either interger or string type.
import random
while True:
number = random.randint(1,9)
guess = int(input('guess the number: '))
time = 0
time += 1
if guess == number:
print('you guessed correct')
elif guess < number:
print('your guessed is lower than the actual number')
elif guess > number:
print('your guessed is higher than the actual number')
elif guess == 'exit':
print(time)
break
something like this
import random
time = 0
number = random.randint(1,9)
while True:
guess = input('guess the number: ')
time += 1
if guess == "exit":
print(time)
break
elif int(guess) < number:
print('your guessed is lower than the actual number')
elif int(guess) > number:
print('your guessed is higher than the actual number')
elif int(guess) == number:
print('you guessed correct')
print(time)
break
note that time and number have to be initializate outside the while loop, because if not, we would get different random numbers for each iteration, and also time would be initializate to 0 each time.
You can test the input as a string first before converting it to an integer:
while True:
response = input('guess the number: ')
if response == 'exit':
break
guess = int(response)
# the rest of your code testing guess as a number

While Loop complication in guess the number game

So I am making a guess the number game in Python 3
After the whole process, I want my while loop to generate another number so that I can start the game again without running the program again.
Please let me know what I'm doing wrong, and if you could provide me with some insight on how to use the while loop, it'll be much appreciated.
Here's the code :
import random
while True:
number = random.randint(1, 1000)
count = 0
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
Not sure if the code you pasted was a typo (on indentation), but I may have accidentally changed your implementation.
Regardless, you should just add another while loop, and a break condition when the user gets it right.
import random
while True:
number = random.randint(1, 1000)
count = 0
while True: # Added, and added another layer of indentation
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
break # Added
In doing so, the code will keep looping to guess the correct number until they are correct. And then generate a new number to guess. However this code will never end unless you add another breaking condition (such as setting a flag the while loop will check to break out of the outer loop.
I wrote some quick code that prompts the user if they want to continue playing or not and then loops through and continues the game with a new number if they want to. I also fixed some minor bugs. Your count kept getting reset in the loop so it would always say you found it in 1 try.
import random
def promptUser():
user_continue = input("Do you want to continue playing? y/n")
if (user_continue == 'y'):
number = random.randint(1, 10)
game(0, number)
def game(count, number):
while True:
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
promptUser()
break
promptUser()

Python 3 number guessing game

I created a simple number guessing game, but every time I don't type in a number the system crashes. Can someone please help!
import random
randNum = random.randint(1, 100)
guesses = 0
for i in range(1, 8):
guesses = guesses + 1
print("hi human guess a number 1-100! \n")
guess = input()
guess = int(guess)
if guess > randNum:
print("your guess is too high")
elif guess < randNum:
print("your guess is too low")
elif guess == randNum:
print("duuude you're a genius \n")
print("you needed " + str(guesses) + " guesses")
I took a quick look at your code and one thing which stands out is that on Line 10, you cast the input to an int without checking if the input is indeed an int.
The system crashes because Python cannot typecast characters to integers when you type cast them. You should explicitly write a condition to check for characters i.e. if the input string is anything except numbers, your code should print something like "Try Again" or "Invalid Input".
import random
randNum = random.randint(1, 100)
guesses = 0
for i in range(1, 8):
guesses = guesses + 1
print("hi human guess a number 1-100! \n")
guess = input()
if guess.isdigit():
if int(guess) > randNum:
print("your guess is too high \n")
elif int(guess) < randNum:
print("your guess is too low \n")
elif int(guess) == randNum:
print("duuude you're a genius \n")
print("you needed " + str(guesses) + " guesses")
else:
print("Invalid Input! Try a number. \n")
Try this code. I hope it helps. And from next time try to upload code instead of images. ;-)
import random
def game():
computer = random.randint(1, 10)
# print(computer)
user = int(input("Please guess a number between 1-10: "))
count = 0
while count < 5:
if computer > user:
count += 1
print("You guessed too low!")
print("You have used " + str(count) + "/5 guesses")
user = int(input("Please guess a number another number!: "))
elif computer < user:
count += 1
print("You guessed too high!")
print("You have used " + str(count) + "/5 guesses")
user = int(input("Please guess a number another number: "))
else:
print("YOU WON!!")
again = input("Would you like to play again?")
if again in["n", "No", "N", "no"]:
break
elif again in["y", "Yes", "Y", "yes"]:
pass
game()
if count == 5:
print("Bummer, nice try...the number was actually " + str(computer) + "!")
again = input("Would you like to play again?")
if again in["n", "No", "N", "no"]:
break
elif again in["y", "Yes", "Y", "yes"]:
pass
game()
else:
print("I'm sorry that's an invalid entry! Restart the game to try again!")
game()

Having a struggle in a number-guessing game in Python 3.6

I created a number guessing game, that is the code:
#Guess the number game
import random
guesses = 6
number = random.randint(0, 100)
win = False
while guesses > 0:
guess = int(input("Guess: "))
guesses -= 1
if guess > number:
print("Your guess is too high", guesses, "remaining")
elif guess < number:
print("Your guess is too low", guesses, "remaining")
elif guess - number < 6:
print("You are very close")
else:
print("Congrats, you guessed")
win = True
guesses = 0
if win == False:
print("Sorry, you didn't guess the number", number)
However, I want it so that if the user inputs a number which is bigger by 5 or lower by 5 than the random number(number variable), to print "You are close".
how about this:
import random
guesses = 6
number = random.randint(0, 100)
win = False
while guesses > 0:
guess = int(input("Guess: "))
guesses -= 1
if guess == number:
win = True
guesses = 0
elif abs(guess - number) < 6:
print("You are very close")
elif guess > number:
print("Your guess is too high", guesses, "remaining")
elif guess < number:
print("Your guess is too low", guesses, "remaining")
if win == False:
print("Sorry, you didn't guess the number", number)
else:
print("Congrats, you guessed correct")
you need to check early if the number is close (before the guess > number checks); and abs is there to accept a difference in both directions
your guess - number < 6 will never be reached; one of the 2 conditions above will already have been met; and without the abs this condition will be true even for very small guesses.
and maybe it would be better to loop over the guesses with a for loop and break if the solution has been found.

Resources