This is my first post in StackOverFlow and I'm sure that I can find for 100% percent an answer for it, but I'd really like to start my adventure with programming and know that this community might help me with it.
My questions are:
I wrote that first piece of code but I'd like to add here a function where the user writes the guess number bigger than the first one.
I am troubled with adding the additional function if for this situation - I do understand that it wouldn't suppose to be if, but elif.
Is anyone has any idea how to suppose to look-alike??
import random
top_range = input("Write a number bigger then 0: ")
if top_range.isdigit() or top_range[0] == "-":
top_range = int(top_range)
if top_range <= 0:
print('Write a number bigger then 0')
quit()
else:
print('Write a number bot a word')
quit()
random_number = random.randint(0, top_range)
guesses = 0
while True:
guesses += 1
user_guess = input("Guess the number : ")
if user_guess.isdigit():
user_guess = int(user_guess)
else:
print('Write another number.')
continue
if user_guess == random_number:
print('You did it!')
break
else:
if user_guess < random_number:
print('The number is bigger then that')
else:
print('The number is smaller than that')
print('You did it in', guesses, "guesses!")
Add a first if, then use elif for the other choices. I've also simplify a bit the first if
while True:
guesses += 1
user_guess = input("Guess the number : ")
if not user_guess.isdigit():
print('Write another number.')
continue
user_guess = int(user_guess)
if user_guess > top_range:
print("That is higher than top range, try again")
elif user_guess == random_number:
print('You did it!')
break
elif user_guess < random_number:
print('The number is bigger then that, try again')
else:
print('The number is smaller than that, try again')
Related
I'm making a guessing game, but I want to add another line of code where the user can play again after, but I don't know where to start.
print ("Welcome to the Number Guessing Game in Python!")
# Initialize the number to be guessed
number_to_guess = 7
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int (input ("Please guess a number between 1 and 10: "))
while number_to_guess != guess:
print ("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
break
elif guess < number_to_guess:
print ("Your guess was lower than the number.")
else:
print ("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input ("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print ("Well done you won!")
print ("You took" + str(count_number_of_tries) + "attempts to complete the game.")
else:
print ("Sorry, you lose")
print ("The number you needed to guess was " + str(number_to_guess) + "." )
print ("Game Over.")
I dont know if the code should be at the bottom or in between somewhere.
I also want to remove the break if possible.
Great idea! In my mind, there are two ways of continuously asking the user to play until they enter something that will let you know they want to stop like 'q', 'quit', or 'exit'. First you could nest all of your current code a while loop (indent and write 'while(): before the code), or turn your current code into a function, and call it over and over again until the user enters the exit command
Ex:
lets say i can print hello world like this
# your game here
but now I want to keep printing it until the user enters 'quit'
user_input = '.' # this char does not matter as long as it's not 'quit'
while user_input != 'quit': # check if 'user_input' is not 'quit'
# your game here
user_input = input('Press any key to continue (and enter) or write "quit" to exit: ') # prompt user to enter any key, or write quit
Put all of that code in a game() function.
Underneath, write
while True:
game()
play=int(input('Play again? 1=Yes 0=No : '))
if play == 1:
pass
else:
break
print("Bye!")
I think this should do it, just a basic while loop
playAgain = 'y'
while playAgain == 'y':
print ("Welcome to the Number Guessing Game in Python!")
# Initialize the number to be guessed
number_to_guess = 7
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int (input ("Please guess a number between 1 and 10: "))
while number_to_guess != guess:
print ("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
print("You've guessed more than three times, you're pretty bad")
elif guess < number_to_guess:
print ("Your guess was lower than the number.")
else:
print ("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input ("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print ("Well done you won!")
print ("You took " + str(count_number_of_tries) + " attempts to complete the game.")
else:
print ("Sorry, you lose")
print ("The number you needed to guess was " + str(number_to_guess) + "." )
print ("Game Over.")
playAgain = (input ("Type y to play again, otherwise press enter: "))
print("Goodbye gamer")
You can add a while loop to the outermost layer that randomly generates the value of number_to_guess on each startup. And ask if you want to continue at the end of each session.
import random
print("Welcome to the Number Guessing Game in Python!")
number_range = [1, 10]
inp_msg = "Please guess a number between {} and {}: ".format(*number_range)
while True:
# Initialize the number to be guessed
number_to_guess = random.randint(*number_range)
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int(input(inp_msg))
while number_to_guess != guess:
print("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
break
elif guess < number_to_guess:
print("Your guess was lower than the number.")
else:
print("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print("Well done you won!")
print("You took" + str(count_number_of_tries) + "attempts to complete the game.")
else:
print("Sorry, you lose")
print("The number you needed to guess was " + str(number_to_guess) + ".")
if input("Do you want another round? (y/n)").lower() != "y":
break
print("Game Over.")
I am creating a python random counting game. I'm having some difficulties with certain parts. Can anyone here review my code? I'm having difficulty with trying to implement a try/except and a tries function that counts the user's attempts. I also have to verify that the number is a legitimate input and not a variable. So far I've gotten this far and its coming along good. I just need alittle help ironing out a few things. Thanks guys you rock.
Here is the code below:
import random
def main():
start_game()
play_again()
tries()
print("Welcome to the number guessing game")
print("I'm thinking of a number between 1 and 50")
def start_game():
secret_number = random.randint(1,50)
user_attempt_number = 1
user_guess = 0
while user_guess != secret_number and user_attempt_number < 5:
print("---Attempt", user_attempt_number)
user_input_text = input("Guess what number I am thinking of: ")
user_guess = int(user_input_text)
if user_guess > secret_number:
print("Too high")
elif user_guess < secret_number:
print("Too low")
else:
print("Right")
user_attempt_number += 1
if user_guess != secret_number:
print("You ran out of attempts. The correct number was"
+str(secret_number)+ ".")
def play_again():
while True:
play_again = input("Do you want to play again?")
if play_again == 'yes':
main()
if play_again =='no':
print("Thanks for playing")
break
def tries():
found= False
max_attempts=50
secret_number = random.randint(1, 50)
while tries <= max_attempts and not found:
user_input_text = start_game()
user_guess_count=+1
if user_input_text == secret_number:
print("It took you {} tries.".format(user_guess_count))
found = True
main()
Try this method:
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
count = 1 #new line
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
count = count+
Im getting a syntax error for elif option ==2:. I was wondering what I need to do to fix it. I followed the pseudocode my professor gave us but it still won't run. I'm wondering if I shouldn't have used elif or maybe something about the indentation is off.
import random
print("Welcome to the guess my number program")
while True:
print("1. You guess the number")
print("2. You type a number and see if the computer can guess it")
print("3. Exit")
option = int(input("Please enter your number here: "))
if option ==1:
#generates a random number
mynumber = random.randint(1,11)
#number of guesses
count = 1
while True:
try:
guess = int(input("Guess a number between 1 and 10:"))
while guess < 1 or guess > 10:
guess = int(input("Guess a number between 1 and 10:")) # THIS LINE HERE
except:
print("Numbers Only")
continue
#prints if the number you chose is too low and adds 1 to the counter
if guess < mynumber:
print("The number you chose is too low")
count= count+1
#prints if the number you chose is too high and adds 1 to the counter
elif guess > mynumber:
print("The number you choose is too high")
count = count+1
#If the number you chose is correct it will tell you that you guessed the number and how many attempts it took
elif guess == mynumber:
print("You guessed it in " , count , "attempts")
break
elif option == 2:
number = int(input("Please Enter a Number: "))
count = 1
while True:
randomval = random.randint(1,11)
if (number < randomval):
print("Too high")
elif (number > randomval):
print("Too low")
count = count+1
elif (number==randomval):
print("The computer guessed it in" + count + "attempts. The number was" + randomval)
break
else:
break
The problem is simple. There is no continuity between if option == 1 and elif option == 2, because of the in between while loop. What you have to do is remove the el part of elif option == 2 and just write if option == 2.
I haven't tested the whole program myself. But at a glance, this should rectify the problem.
Please comment if otherwise.
I was just wondering if there is a way to limit the amount of times a user can input something on a while loop. This is simply a guess a number 1-100 game. I have the found variable = False.
while not found:
user_guess = int(input("Your guess: "))
if user_guess == random_number:
print("you got it!")
found = True
elif user_guess > random_number:
print("Guess lower")
else:
print("guess higher")
I wanted to see if i could make this code seem more like a game by limiting the amount a user can guess for the input. Ive had some ideas i just cannot wrap my head around it. do i have set a variable value for the input to set the amount of times it can run? Im new to programming so i am struggling a bit.
count = 0
max_guesses_allowed = pick your max here
while not found or count < max_guesses_allowed:
user_guess = int(input("Your guess: "))
if user_guess == random_number:
print("you got it!")
found = True
elif user_guess > random_number:
count += 1
print("Guess lower")
else:
count += 1
print("guess higher")
The standard way would be to count the number of loops, and then exit if they exceed the maximum.
max_allowed = 10
attempt = 0
while not found:
attempt += 1
user_guess = int(input("Your guess: "))
if user_guess == random_number:
print("you got it!")
found = True
elif attempt == max_allowed:
print("You've reached the maximum number of guesses.")
break
elif user_guess > random_number:
print("Guess lower")
else:
print("guess higher")
This question already has answers here:
Ask the user if they want to repeat the same task again
(2 answers)
Closed 4 years ago.
Basically it's a guessing game and I have literally all the code except for the last part where it asks if the user wants to play again. how do I code that, I use a while loop correct?
heres my code:
import random
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
while guess == number:
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == yes:
guess= eval(input("Enter your guess between 1 and 1000 "))
if again == no:
break
One big while loop around the whole program
import random
play = True
while play:
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
play = False
separate your logic into functions
def get_integer_input(prompt="Guess A Number:"):
while True:
try: return int(input(prompt))
except ValueError:
print("Invalid Input... Try again")
for example to get your integer input and for your main game
import itertools
def GuessUntilCorrect(correct_value):
for i in itertools.count(1):
guess = get_integer_input()
if guess == correct_value: return i
getting_close = abs(guess-correct_value)<10
if guess < correct_value:
print ("Too Low" if not getting_close else "A Little Too Low... but getting close")
else:
print ("Too High" if not getting_close else "A little too high... but getting close")
then you can play like
tries = GuessUntilCorrect(27)
print("It Took %d Tries For the right answer!"%tries)
you can put it in a loop to run forever
while True:
tries = GuessUntilCorrect(27) #probably want to use a random number here
print("It Took %d Tries For the right answer!"%tries)
play_again = input("Play Again?").lower()
if play_again[0] != "y":
break
Don't use eval (as #iCodex said) - it's risky, use int(x). A way to do this is to use functions:
import random
import sys
def guessNumber():
number=random.randint(1,1000)
count=1
guess= int(input("Enter your guess between 1 and 1000: "))
while guess !=number:
count+=1
if guess > (number + 10):
print("Too high!")
elif guess < (number - 10):
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = int(input("Try again "))
if guess == number:
print("You rock! You guessed the number in ", count, " tries!")
return
guessNumber()
again = str(input("Do you want to play again (type yes or no): "))
if again == "yes":
guessNumber()
else:
sys.exit(0)
Using functions mean that you can reuse the same piece of code as many times as you want.
Here, you put the code for the guessing part in a function called guessNumber(), call the function, and at the end, ask the user to go again, if they want to, they go to the function again.
I want to modify this program so that it can ask the user whether or not they want to input another number and if they answer 'no' the program terminates and vice versa. This is my code:
step=int(input('enter skip factor: '))
num = int(input('Enter a number: '))
while True:
for i in range(0,num,step):
if (i % 2) == 0:
print( i, ' is Even')
else:
print(i, ' is Odd')
again = str(input('do you want to use another number? type yes or no')
if again = 'no' :
break