How would I ask the user if they want to play and then start the simulation? And if they don't the program prints a goodbye message. And print the total number of times the coin was flipped at the end.
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
while True:
try:
time_flip= int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
def random_flip():
return random.randint(0, 1)
def count_for_sides():
count_head=0
count_tail=0
times=num_of_input()
while True:
if count_head + count_tail == times:
break
else:
if random_flip()==0:
count_head+=1
else:
count_tail+=1
print()
print(str(count_head) + " came up Heads")
print(str(count_tail) + " came up Tails")
count_for_sides()
You can get input from the user before calling the count_for_sides method and call it if they opt in.
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
while True:
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
def random_flip():
return random.randint(0, 1)
def count_for_sides():
count_head=0
count_tail=0
times=num_of_input()
while True:
if count_head + count_tail == times:
break
else:
if random_flip()==0:
count_head+=1
else:
count_tail+=1
print()
print(str(count_head) + " came up Heads")
print(str(count_tail) + " came up Tails")
userWantsToPlay = input("Do you want to play this game? (Y/n): ")
if (userWantsToPlay == 'Y'):
count_for_sides()
Related
I am trying to use the variables user_ans_a, user_ans_s, user_ans_m and user_ans_d inside of my game as questions randomly chosen by python. My dilemma is coming from matching the randomly chosen variable to an answer coresponding to that variable. I want the user to be able to enter an anser to those questions.
import random
import re
while True:
score = 0
top = "--- Mathematics Game ---"
print(len(top) * "━")
print(top)
print(len(top) * "━")
print(" Type 'Play' to play")
start_condition = "Play" or "play"
def checkint(input_value):
while True:
try:
x = int(input(input_value))
except ValueError:
print("That was a bad input")
else:
return x
while True:
inp = input()
if inp == "Play":
break
else:
print("Try again")
if inp == "Play":
print("What's your name?")
name = input()
print(f"Hello {name}")
while True:
try:
no_of_rounds = int(input("how many rounds do you want to play? "))
break
except ValueError:
print('Please enter a number.')
for i in range(no_of_rounds):
ran_int1 = (random.randint(1,10))
ran_int2 = (random.randint(1,10))
answer_a = (ran_int1 + ran_int2)
answer_s = (ran_int1 - ran_int2)
answer_m = (ran_int1 * ran_int2)
answer_d = (ran_int1 / ran_int2)
user_ans_a = (f"What does {ran_int1} + {ran_int2} = ")
user_ans_s = (f"What does {ran_int1} - {ran_int2} = ")
user_ans_m = (f"What does {ran_int1} * {ran_int2} = ")
user_ans_d = (f"What does {ran_int1} / {ran_int2} = ")
if checkint(user_ans_a) == int(answer_a):
print(f"That was correct {name}.")
score = score+1
else:
print(f"Wrong {name}, the answer was {answer_a}, try again")
print(f"Score was {score}")
while True:
answer = str(input('Run again? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Goodbye")
break
I'm trying to make a basic coin flipping simulator. And ask the user for their name and greet them. Then ask if they want to play the game. But when they enter something other than "Y", it gives this error message: UnboundLocalError: local variable 'time_flip' referenced before assignment how can I fix that and instead it prints a goodbye message. And ask them again if they want to keep playing.
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
userWantsToPlay = input("Do you want to play this game? (Y/N): ")
while userWantsToPlay in ("Y", "y"):
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
There is more code, but I shortened it to the part with errors
here's the full program: https://replit.com/#Blosssoom/coinpy?v=1#main.py
The assignment of time_flip may not complete if there is an error transforming the input to an integer.
To resolve, assign to time_flip before the try block:
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
userWantsToPlay = input("Do you want to play this game? (Y/N): ")
time_flip = None
while userWantsToPlay in ("Y", "y"):
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
If people don't type y or Y, the while loop will never run. This cause that every variables in the while loop will never ba created. You want to return time_flip, but because it supposes to be made in the while loop (), it won't be created -> local variable 'time_flip' referenced before assignment (self-explained).
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
userWantsToPlay = input("Do you want to play this game? (Y/N): ")
time_flip = 0 #None or anything
while userWantsToPlay in ("Y", "y"):
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
return time_flip
When I run this, it just keeps on repeating itself asking for a number over and over again. I am a beginner at python so please don't judge.
import random
import time
while True:
guess = input("Please enter a lucky number between 1 to 10:\n")
number = random.randint(0, 10)
print ("Random number is " + str(number) + ":")
if guess == number:
print ("Awesome - You guessed correctly!")
answer = input('Would you like to try again? (y/n):\n')
def func():
if answer == 'n':
print ("Have a wonderful day!")
time.sleep(2)
else:
print("Good try, Would you like to play again? (y/n):")
func()
you can do it like this:
import random
import time
number = random.randint(0, 10)
while True:
guess = int(input("Please enter a lucky number between 1 to 10:\n"))
print ("Random number is " + str(number) + ":")
if guess == number:
print ("Awesome - You guessed correctly!")
answer = input('Would you like to try again? (y/n):\n')
if answer == 'n':
print ("Have a wonderful day!")
break
else:
print("generating new number...")
number = random.randint(0, 10)
I am trying to create a game where you choose how many players there will be, name those players, and then one player is chosen at random.
From there, that chosen player would pick a number in between 1 and 10 that they DON'T want to land on.
Then, the dice rolls and if they land on that number, everyone else gets to pick a dare for him/her. If it doesn't, the game just randomly picks another player and the process begins again.
The problem is though, the program doesn't get past the part where it asks you which number you don't want to land on. This is weird, as it works fine with one person.
Here is the full code, you are looking for line 23:
# Pass Or Dare
from random import randint
firsttry = True
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
while firsttry:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
else:
firsttry = False
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
while True:
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
except ValueError:
print("Please enter a number.")
else:
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
else:
break
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
Here is a fast review of the algorithm, the problem was that the break you used while checking if the darenumber was between the desired range, causing to loop back again and never getting out of there.
Also, it's recommended that you check your control structure because it´s what made the problem.
Lastly, I strongly recommend an exit feature of your game because in some point in has to end. Hope it helps:
from random import randint
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
playercount = 0
while playercount < 1:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
print("Press 0 while it's your turn to finish the game")
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
darenum = -1
while (darenum > 10 or darenum < 0):
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
except ValueError:
print("Please enter a number.")
if darenum == 0:
break
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
print("Game Over")
Your original code, with errors sinalization (read the code's comments):
# Pass Or Dare
from random import randint
firsttry = True
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
while firsttry:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
else:
firsttry = False
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
while True:
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
except ValueError:
print("Please enter a number.")
else: #there is no if for this else
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
else:
break #this break would break the while True above
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
#there should be a break in here, otherwise the function would be stuck in the second while True
The fixed code, changing what I mentioned in the comments above:
# Pass Or Dare
from random import randint
firsttry = True
def playerpicked(list):
listwords = len(list)
numpicked = randint(0, listwords - 1)
userpicked = list[numpicked]
return userpicked
while firsttry:
try:
playercount = int(input('How many players will there be?\n'))
except ValueError:
print("That isn't a number. Please enter a number without decimals.")
else:
firsttry = False
playernames = [input("Name of Player {}: ".format(i)) for i in range(1, playercount + 1)]
while True:
playerturn = playerpicked(playernames)
print("The Player picked is:",playerturn)
while True:
try:
darenum = int(input(playerturn + ", which number do you NOT want to land on?\n"))
except ValueError:
print("Please enter a number.")
if darenum > 10 or darenum < 1:
print("Please enter a number between 1 and 10.\n")
else:
print("Okay. Rolling the dice...")
numpick = randint(1, 10)
print("The number chosen is " + str(numpick) + ".")
if numpick == darenum:
print("Whoops! The number you chose was the one that we landed on! Everyone agree on a dare for " + playerturn + "!\n\n")
input("Press Enter once " + playerturn + " has done a dare...\n")
else:
print(playerturn + " has escaped! Moving on to the next person.\n\n")
break
I'm writing a Python math game in which the program asks an addition question and the user has to get the right answer to continue. My question is, how can I make the program generate a new math problem when the user gets the last one correct?
import random
firstNumber = random.randint(1, 50)
secondNumber = random.randint(1, 50)
result = firstNumber + secondNumber
result = int(result)
print("Hello ! What\'s your name ? ")
name = input()
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
userAnswer = int(input("Your answer : "))
while (True) :
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print("Wrong\n")
userAnswer = int(input("Your answer : "))
input("\n\n Press to exit")
Implement the game with a pair of nested loops. In the outer loop, generate a new arithmetic problem. In the inner loop, keep asking the user for guesses until he either gives the right answer or decides to quit by entering a blank line.
import random
playing = True
while playing:
# Generate a new arithmetic problem.
a = random.randint(1, 50)
b = random.randint(1, 50)
solution = a + b
print('\nWhat is %d + %d? (to quit, enter nothing)' % (a, b))
# Keep reading input until the reply is empty (to quit) or the right answer.
while True:
reply = input()
if reply.strip() == '':
playing = False
break
if int(reply) == solution:
print('Correct. Good job!')
break
else:
print('Wrong. Try again.')
print('Thank you for playing. Goodbye!')
This should get you started. The getnumbers() returns two random numbers, just like in your script. Now just add in you game code. Let me know if you have questions!
import random
def getnumbers():
a = random.randint(1, 50)
b = random.randint(1, 50)
return a, b
print("Math Game!")
while True:
a, b = getnumbers()
# game code goes here
print("%d %d" % (a, b))
input()
This might do what you want:
import random
def make_game():
firstNumber = random.randint(1, 50)
secondNumber = random.randint(1, 50)
result = firstNumber + secondNumber
result = int(result)
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
userAnswer = int(input("Your answer : "))
while (True) :
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print("Wrong\n")
userAnswer = int(input("Your answer : "))
print("Hello ! What\'s your name ? ")
name = input()
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
while True:
make_game()
end = input('\n\n Press to "end" to exit or "enter" to continue: ')
if end.strip() == 'end':
break