So I'm refreshing what little I knew of Python before and playing around with some beginner projects. I'm toying arond with it now, and I'm just trying to learn and see what I can do. I made a "Guessing Game" and turned it into a function. I want to store these reults in a list each time it is used. I want the results to automatically go to the list when the game is completed and then to be able to print the list when desired.
I'm not sure if I need to create a new function for this, or if I should be creating this within my current "guessing_game" function. I've tried to create a list previously, but I'm not sure how to create and store the variable of the game result in order to add it into the list. I feel like this is probably a fairly simple problem, so I apologize if this is a dumb question.
def guessing_game():
import random
number = random.randint(1, 1000)
player_name = input("Enter name ")
number_of_guesses = 0
print('Howdy' + player_name + "Guess a number between 1 and 1000: ")
while number_of_guesses < 10:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Too Low, Joe")
if guess > number:
print("Too high, Sly")
if guess == number:
break
if guess == number:
print("You got it, Bobbit, in " + str(number_of_guesses) + " tries")
else:
print(" Well, yer were close, Stofe. Shoulda guessed " + str(number))
print(guessing_game())
You can create a list inside of the function, and then everytime they guess, you can store the guess inside the list. At the end, we can print the list.
def guessing_game():
import random
number = random.randint(1, 1000)
player_name = input("Enter name: ")
number_of_guesses = 0
guesses = []
print('Howdy ' + player_name + " Guess a number between 1 and 1000: ")
while number_of_guesses < 10:
guess = int(input())
guesses.append(guess)
number_of_guesses += 1
if guess < number:
print("Too Low, Joe")
if guess > number:
print("Too high, Sly")
if guess == number:
break
if guess == number:
print("You got it, Bobbit, in " + str(number_of_guesses) + " tries")
else:
print(" Well, yer were close, Stofe. Shoulda guessed " + str(number))
print("These were the numbers you guessed:")
for g in guesses:
print(g)
print(guessing_game())
What you need to do is create a list with something like val = []. I added it into the code and also added a formatting piece so it looks nice.
def guessing_game():
import random
guesses = []
number = random.randint(1, 1000)
guess = number / 2
player_name = input("Enter name ")
number_of_guesses = 0
print(f'Howdy {player_name}. Guess a number between 1 and 1000: ')
while number_of_guesses < 10:
guess = int(input('> '))
guesses = guesses + [guess]
number_of_guesses += 1
if guess < number:
print("Too Low, Joe")
if guess > number:
print("Too high, Sly")
if guess == number:
break
formatted_guesses = ''
for _ in range(len(guesses)):
if _ != len(guesses) - 1:
formatted_guesses = formatted_guesses + str(guesses[_]) + ', '
else:
formatted_guesses = formatted_guesses + str(guesses[_]) + '.'
if guess == number:
print("You got it, Bobbit, in " + str(number_of_guesses) + " tries")
print(f'You guessed {formatted_guesses}')
else:
print("Well, yer were close, Stofe. Shoulda guessed " + str(number))
print(f'You guessed {formatted_guesses}')
guessing_game()
I am trying to create a score system for my game. For each of the three tries, the user will get different points for getting the question right. For example, if the user gets the question right on the first try, he or she will receive 3 points. If they get it right on the second try, they will receive two points (one point on the third try and zero points if they run out of the three tries). How would I be able to do this?
total_score = 0
correct_answer = 2004
print('What was the year when Arsenal last won the Premier League?')
try:
for x in range(1, 4):
user_guess = int(input(f'Attempt {x}. '))
if user_guess == correct_answer:
total_score += 1
print(f'Good job! Your current score {total_score}')
break
else:
print(f'Incorrect! {total_score}')
except(ValueError):
print('Enter a numerical value for year.')
Like this
total_score = 0
correct_answer = 2004
MAX_POINTS = 4
print('What was the year when Arsenal last won the Premier League?')
try:
for x in range(1, MAX_POINTS):
user_guess = int(input(f'Attempt {x}. '))
if user_guess == correct_answer:
total_score += MAX_POINTS - x
print(f'Good job! Your current score {total_score}')
break
else:
print(f'Incorrect! {total_score}')
except(ValueError):
print('Enter a numerical value for year.')
MUST READ THE COMMENTS TO UNDERSTAND HOW IT WORKS..
total_score = 0
correct_answer = 2004
user_guess = '' # A blank string for user response. Strings can be reassigned later.
print('What was the year when Arsenal last won the the Premier League?')
for x in range(1, 4):
try: # This is the actual place to use exception handling
user_guess = int(input('Attempt ' + str(x) + ': '))
except ValueError:
print('You did not enter a numerical value for year.')
break
if user_guess == correct_answer:
total_score += (4-x) # will add (4-1), (4-2), (4-3) in subsequent loop runs.
print('Good Job! Your Current score: ' + str(total_score))
break
else:
print('Uh oh! You didn\'t get that right. Current score: ' + str(total_score) + '. Try Again..')
if x == 3: # To check if the three attempts have been used or not.
print('Alas! You are out of attempts. Try back later')
break
else:
continue
I am trying to make a guess game. I've used while, if, elif, and else statements but I'm stuck on how to use for and while loops as well as randomizing single hints and single answers from a nested lists.
black_box = ["guam","lakers","flash","buddha","drake","fortnite","annabelle","xmen","mars","dad"]
nested_list = [["island","yigo","cocos","kelaguen"],["kobe","la","magic","lebron"],["scarlet","speedster","dc","ezra"], ["asiangod","meditation","monk","enlightenment"],["rapper","onedance","canadian","raptors"],["game","epic","notminecraft","dances"],["doll","conjuring","soultaker","creation"],["wolverine","mystique","magneto","apocalypse"],["red","fourth","planet","ares"], ["man","american","peter","lionking"]]
i = random.randint(0,9)
word = black_box[i]
hint = nested_list[i]
print("Guess the word with the following hint: ", hint, "you have 4 tries.")
numofguesses = 0
guess = input("What is the word? ")
while numofguesses < 4:
numofguesses = numofguesses + 1
if guess == word:
print("You win!")
option = input("Do you want to try again or quit? ")
if option == "try again":
print("")
elif option == "quit":
break
if guess != word:
print("Try again!")
guess = input("What is the word? ")
if guess != word:
print("Try again!")
guess = input("What is the word? ")
I expected to get a line of code that prints "Try again!" but it skipped and started to print "What is the word? " print("Guess the word with the following hint: ", hint, "you have 4 tries.") Originally, I used hint[i] which printed out only one hint in the nested list but then I tried to run the program again but I got an error saying, "list index is out of range.
Your condition checks and loops where not correct. Try the below code, it should work fine.
black_box = ["guam","lakers","flash","buddha","drake","fortnite","annabelle","xmen","mars","dad"]
nested_list = [["island","yigo","cocos","kelaguen"],["kobe","la","magic","lebron"],["scarlet","speedster","dc","ezra"], ["asiangod","meditation","monk","enlightenment"],["rapper","onedance","canadian","raptors"],["game","epic","notminecraft","dances"],["doll","conjuring","soultaker","creation"],["wolverine","mystique","magneto","apocalypse"],["red","fourth","planet","ares"], ["man","american","peter","lionking"]]
while True:
i = random.randint(0, 9)
word = black_box[i]
numofguesses = 0
while numofguesses < 4:
hint = nested_list[i][numofguesses]
print("Guess the word with the following hint: ", hint, ". You have ", 4 - numofguesses, " tries!")
guess = input("What is the word? ")
numofguesses = numofguesses + 1
if guess == word:
print("You win!")
break
if guess != word:
print("Try again!")
option = input("Do you want to try again or quit? ")
if option == "try again":
print("")
else:
break
I have been working on this for a while now. I have been able to get parts of this to work, but never the whole thing. The end goal is to loop the user back into another game if they so choose. I think the issue is with my break statement, but I am not sure how to route around it. I have included all my code so that any mistakes can be found. Apologies if this has already been answered, I couldn't find a page with this kind of problem.
def game():
import random
from random import randint
n = randint(1, 10)
print('Enter a seed vlaue: ')
the_seed_value = input(' ')
random.seed(the_seed_value)
guessesTaken = 0
print("what is your name?")
myName = input("")
guess = int(input("Enter an integer from 1 to 99: "))
while n != "guess":
if guess < n:
print ("guess is low")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
else:
print ("Congradulations " + myName + " you guessed it in " + str(guessesTaken) + " guesses!")
break
print('Want to play agian? y/n')
answer = input(" ")
if answer == "n":
print ("Ok, See you next time!")
elif answer == "y":
print("Starting new game!")
game()
def main():
game()
if __name__ == "__main__":
main()
For one, #kerwei notes correctly that your while line has an issue, and needs to be changed from while n != "guess": to while n != guess:.
For two, your while loop is satisfied when the player guesses correctly, bypassing the Congrats line.
Since the game is currently structured to stay in the loop until the player guesses correctly, a simple fix would be to remove the else: line from the loop and place the victory statement afterwards. That is,
def game()
...
while n != guess:
if guess < n:
...
elif guess > n:
...
print('Congrats!')
print('play again?')
...
How do I get this game to end when the input is no without going back to the top and looping through or getting an error code? Note I put "End" in so that it would not iterate again
import random
it's a simple guessing game that I want to start over if yes but end if no
def main():
y_games = 2
for y in range(y_games):
play_guessingGame_()
def play_guessingGame_():
guessesTaken = 0
print('Hello Friend,\n')
print('What is your name?\n')
name = input()
print(name + ' ,It is good to meet you!\n')
print("Let's play a game!\n ")
print('I am thinking of a number between 1 and 10. . . what is my number?\n')
try:
answer = random.randint(1,10)
while guessesTaken < 5:
print("Start guessing!\n")
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess > answer:
print('Too high! Try again!\n')
elif guess < answer:
print('Too low! Try again!\n')
elif guess == answer:
break
while guess == answer:
guessesTaken = str(guessesTaken)
if guessesTaken == str(1):
print('AND ON THE FIRST TRY!!! IMPRESSIVE!!!!')
print('There is no beating you\n')
break
if guessesTaken > str(1):
print('Good job! You guessed my number in ' + guessesTaken + ' guesses')
print('There is no beating you\n')
break
if guess != answer:
print("I'm sorry, you have run out of guess.\n")
print('Better luck next time!\n')
except ValueError:
print('Please enter whole numbers only')
print('\nDo you want to try again? ')
response = input()
if response == 'yes':
print("Great! Let's do this!")
if response == 'no':
print('\nWell, all good things must come to end!')
Exit
main()
i added import random to your code and also changed Exit to exit() and there was no error and the game performed right, i hope i got your problem right..