Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
Ok so I want to make a very very very very very simple coin flipping program and I want to make it so the player can choose if to close after the coin flipped or if to flip again. This is the code I used, the person can type either 1 or 2, and choose if to flip again or if to close the program, I tried using open("Coinflip.py) but it didn't do anything. What should I do?
import random
import time
flip = random.randint(1, 2)
if flip == 1:
print("The coin landed heads")
if flip == 2:
print("The coin landed tails")
print('')
print("")
time.sleep(1)
choice = int(input("Type 1 to exit or 2 to flip again and press enter "))
if choice == 1:
exit()
elif choice == 2:
open("Coinflip.py")
input()
You can use a function and a while loop to continuously ask for coin flips:
import random
import time
def coin_flip():
flip = random.randint(1, 2)
if flip == 1:
print("The coin landed heads")
if flip == 2:
print("The coin landed tails")
time.sleep(1)
def main():
while True:
choice = int(input("Type 1 to exit or 2 to flip again"))
if choice == 1:
break
elif choice == 2:
coin_flip()
if __name__ == "__main__":
main()
technically you don't need a function, but lets use one anyway
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
i'm stuck and need a little help.
how can i make this more efficient and reduce the number of if/elif/else.
i thought to make a function that check the range of an input let's say between 1 to 5 and then return the value to print out what i need.
i would love to hear your thoughts on it:
there some code:
while True:
difficulty = input("Please choose difficulty from 1 to 3: ")
if not difficulty.isdigit():
print("Please enter a valid number: ")
else:
break
while True:
if difficulty == "1":
print("Level of difficulty is very easy.")
break
elif difficulty == "2":
print("Level of difficulty is easy.")
break
elif difficulty == "3":
print("Level of difficulty is normal.")
break
else:
difficulty = input("You chose an invalid number, choose between 1 - 3. Try again:")
Ideally, you check the range of the number in the first loop
Other than that, use a list
descriptions = [
"very easy, ok you are scared to loose but let's play.",
"easy, ok let's play."
]
while True:
i = int(difficulty) - 1
if i not in range(5):
# invalid input, get it again
difficulty = input("must be between 1 and 5: ")
continue
lines()
print("Level of difficulty is " + descriptions[i])
break
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
they closed this question so I can't delete it because people "answered it" whatever
The problem is that the scoreboard isn't updating when the game ends; it's only shown at the beginning.
How do we fix this? Do we need to implement a loop, or rearrange parts of our code?
Here is the code:
import time
print("Tic-Tac-Toe Game ")
print("Please Wait...")
time.sleep(3)
def game_winner(player):
if Game==Draw:
print("Game Draw")
return 'D'
elif Game==Win:
player-=1
if player != 0:
print("Player 1 Won")
return
else:
print("Player 2 Won")
return
So, I just ran your code and managed to get through one game correctly. You are right that upon completion of one game, entering "yes" does not show the scoreboard correctly.
You already have your code set up as various functions, which is good. What you might want to do is have a play(board, player:str, move:int) function that accepts the player and the respective move and updates the board each time. You will need a modified while loop, because a draw, win or lose condition would end the game. The play() function should just keep track of the current player, and switch between 0 and 1, respectively as each move is played.
You might have something like:
# Set player 0 to start, X
start_player = 0
while not checkGameEnd():
# Take player input
move = int(input("Where do you want to move?"))
# Make the play
play(board, start_player, move)
# Print the board
printBoard()
# Change player
start_player = 1 if start_player is 0 else 1
# Game should end here
printScores()
playAgain()
This is sort of pseudo-code, but you can modify the logic as per your usecase.
The scoreboard printed at the end for me when I responded n to the question 'Do you want to play again?'.
However, it showed 0-0 because the code doesn't update the scores. I think you want to add the following in the game_winner function:
elif Game ==Win:
player -= 1
if player != 0:
print("Player 1 Won")
score_board[player1] += 1
return
else:
print("Player 2 Won")
score_board[player2] += 1
return
Also, you'll need to move the game_winner(player) function call at the end outside of the while loop so that it only called once.
you need to modify the score_board variable at the end of each match, so that when you print it at the end of the game it will be updated with the final score,to do so you can modify your game_winner function like this:
def game_winner(player):
if Game==Draw:
print("Game Draw")
score_board[player1] += 0.5
score_board[player2] += 0.5
return 'D'
elif Game ==Win:
player -= 1
if player != 0:
print("Player 1 Won")
score_board[player1] += 1
return
else:
print("Player 2 Won")
score_board[player2] += 1
return
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am making a Blackjack game in Python, and I am using a while loop. In my code I got an input with an if statement where if the player choose to play another round (types in "Y"), the game starts again (which I got no problem with). My problem is that if the player types in "N" (for no), the game still reruns. What I am trying to do is that when the player types in "N", the game is ended. What is wrong in my code? I am stuck and can't figure it out.
Also as you can see in my code, I use the closed = True several times in the while-loop and it works (for example if the player gets a score of 21, the game ends). The only time the closed = True does not work is in the elif play_again.lower() != "Y": closed = True part of my code.
closed = False
while not closed:
if player_total == 21:
print("\nCongrats, the player got a Blackjack!")
closed = True
else:
input_answer = int(input("\n1 - Hit \n2 - Stand \n \nDo you wish to Hit or Stand? "))
if input_answer == 1:
print("You chose to Hit.")
give_cards(player_hand, 1)
player_total = bjm.calculate_hand_value(player_hand)
print(f'\nThe player has got a new card: {player_hand[2]}. \nThe player currently has {", ".join(player_hand)},'
f' with a total value of {player_total}.')
if player_total > 21:
print("Busted! You got a total value over 21.")
closed = True
elif input_answer == 2:
print("\nYou chose to Stand.")
print(f'The dealers cards are: {" and a ".join(dealer_hand)}, with a total value of {dealer_total}.')
print(f'The players cards are {", ".join(player_hand)} with a total value of {player_total}.')
print_result(player_hand, dealer_hand)
play_again = input("\nDo you want to play another round? Y/N: ")
if play_again.lower() != "N":
print("You wanted to play another round, you will be dealt two new cards.\n")
player_hand.clear()
dealer_hand.clear()
give_cards(player_hand, 2)
give_cards(dealer_hand, 2)
print(f'\nThe players new cards are: {" and a ".join(player_hand)}, with a total value of {player_total}.')
print(f'The dealers new cards are: {" and a ".join(dealer_hand)}, with a total value of {dealer_total}.')
elif play_again.lower() != "Y":
closed = True
closed = True
A better way than what you are using right now to end the loop is to simply replace your condition in closed = True with break.
Additionally, the reason your code isn't working is because you are trying to compare the .lower() (which will always give you a lower case letter) with a capital case letter, which means that this condition:
elif play_again.lower() != "Y":
closed = True
will never be true.
replace it with "y" instead of "Y"
I'm not sure why you are using double negatives. Try this instead:
while True:
...
elif play_again.lower() != "Y":
break #instead of closed=True
Remove the .lower(). You are trying to lowercase and validate it with Y or N which will never get to else statement
Example -
play_again = input("\nDo you want to play another round? Y/N: ")
if play_again != "N":
print("You wanted to play another round, you will be dealt two new cards.\n")
elif play_again != "Y":
print("Dont want to play")
You could set the acceptable answers as
valid_answers = ['yes', 'no']
if valid_answers == "no":
print("You wanted to play another round, you will be dealt two new cards.\n")
player_hand.clear()
dealer_hand.clear()
give_cards(player_hand, 2)
give_cards(dealer_hand, 2)
print(f'\nThe players new cards are: {" and a ".join(player_hand)}, with a total value of {player_total}.')
print(f'The dealers new cards are: {" and a ".join(dealer_hand)}, with a total value of {dealer_total}.')
else:
closed = True
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So I am creating a new simple game to practice my python programming, it is a point/score system that I wanted to implement. I also wanted to make it so it's intelligent by asking the user if it wants to play. So I have three problems at the moment, when I ask the user if it wants to play I wasn't sure what to do if they said no or "n" if they didn't want to play, instead what happens is that it just continues playing then crashes saying "n" is not defined. The second problem that I have is when the user puts the right answer for the random function I put print("You guessed it right!") but it just prints a bunch of them. My third and final problem is the point system, I wasn't sure if it executed after the million printed statements, but I'll see after I fix it.
Here is my game
import random
total_tries = 4
score = 0
print("Welcome to Guess the number game!")
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))
guess = int(input("I am thinking of a number between 1 and 20: "))
while n!= guess:
if guess < n:
total_tries - 1
print("That is too low!")
guess = int(input("Enter a number again: "))
elif guess > n:
print("That is too high")
total_tries - 1
guess = int(input("Enter a number again: "))
else:
break
while n == guess:
score = +1
print("You guessed it right!")
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
print("Mark:", str(mark) + ""%"")
print("Goodbye")
Error when putting no for playing:
while n!= guess:
NameError: name 'n' is not defined
For question 1 you want the system to exit when the user says no. I would do this by using sys.exit to kill the code.
import sys
...
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))**strong text**
else:
sys.exit('User does not want to play, exiting')
For problem 2 you are getting your print statement a million times because you're failing to exit. In the code below n is always equal to guess because you never change n. You don't need a while statement here because you already know you only left the above section when n started to equal guess. Another issue to think about. How will you make it stop when the number of turns runs out?
while n == guess:
score = +1
print("You guessed it right!")
For the third question, think about what will happen here if the number of turns reaches 0.
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
In particular, what would happen when you try to calculate mark?
This condition will only trigger when answer is "y"
if answer == "y":
n = (random.randrange(1, 10))
Remove this and the code will run or modify it as such
if answer == "y":
n = (random.randrange(1, 10))
elif answer == "n"
# set n to some other value
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Im currently in make of creating a math game that involves: addition, subtraction, multiplication and division. These parts with purple borders around them are the questions that i had created for the addition part when the user chooses to pick addition.
I dont know how to make these question be shown at random. When the user goes to select addition for addition questions everytime he does or goes back to do it again after he is done i want the questions not to be the same each time i want them to be in a different order. So its random each time.
#addition questions
def beginnerquestionsaddition():
os.system('clear')
score = 0
beginner1 = input("2 + 3 = ")
if beginner1 == ("5"):
print("Correct, Well Done!")
score += 1
time.sleep(1)
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
beginner2 = input("6 + 7 = ")
if beginner2 == ("13"):
print("Correct, Well Done!")
score += 1
time.sleep(1)
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
beginner3 = input("2 + 5 = ")
if beginner3 == ("7"):
print("Correct, Well Done!")
score += 1
os.system('clear')
time.sleep(1)
endquestadditionbeginner()
print("your score was: ")
print(score)
time.sleep(3)
introduction()
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
endquestadditionbeginner()
print("your score was: ")
print(score)
time.sleep(3)
introduction()
So this isn't exactly an answer for the specific way you decided to go about this program but this is a much simpler way:
from random import randrange
def beginner_addition():
A = randrange(1,11) # Increase range on harder questions
B = randrange(1,11) # Ex. for intermediate_addition(), randrange would be (10,21) maybe...
C = A + B
ans = input("What's the answer to " + str(A) + "+" + str(B) + "? ")
if ans == str(C):
print('Correct')
else:
print('Incorrect')
while True:
beginner_addition()
Of course, this is just example code. You could easily include your points system and perhaps move up in difficulty when the points hit a certain level. You could also randomize the operation. Sorry if this isn't what you want but I saw your code and I figured there is nothing wrong with simplifying your code...