I am having trouble finding a way to allow my Python project to accept a non-integer value and not crash. My intention is that when the user inputs a non-integer value or any value other than the ones assigned by the random sampkle, the game will prompt the function "repeatr()" which will tell them to input the value again.
I've put in the entire solution, but the most relevant sections are in bold and it's that particular section that I want to allow to prompt the repeatr() function instead of crashing
import random
user_wins = 0
user_draws = 0
user_losses = 0
rounds = 0
def closr():
quit()
def repeatr():
print("That is not a valid input. Please input a correct value.")
**def promptr():
print("Please select an input from the following options.")**
options = [5, 4, 3, 2, 1]
randomlist = random.sample(range(1, 5), 3)
randomr = randomlist
x=1
while x == 1:
user_input = int(input("Type 5/4/3/2/1 or Q to quit."))
if user_input in options:
x=2
elif user_input != options:
repeatr()
continue
elif user_input == "q":
closr()
**y=1
while rounds < 10:
promptr()
player_choice = int(input(randomlist))
npc = random.randint(1,5)
if player_choice in randomr:
print("Your opponent has drawn: ", npc)
y=2
else:
repeatr()
continue**
if npc > int(player_choice):
print("You have been defeated this round.")
user_losses = user_losses + 1
print("The score is:" , user_wins , ":" , user_losses)
rounds = rounds + 1
elif npc < player_choice:
print ("You have won this round.")
user_wins = user_wins + 1
print ("The score is:" , user_wins , ":" , user_losses)
rounds = rounds + 1
elif npc == player_choice:
print ("You have drawn this round.")
user_draws = user_draws + 1
print ("The score is:" , user_wins , ":" , user_losses)
rounds = rounds + 1
rounds = 10
if user_losses < user_wins:
print("You have won the game!")
elif user_losses > user_wins:
print("You have lost this game. Better luck next time!")
elif user_losses == user_wins:
print("The game has ended in a draw.")
print("the number of wins you had was:" , user_wins)
print("the number of draws you had was:" , user_draws)
print("the number of losses you had was:" , user_losses)
print("The final score was (Player vs CPU):" , user_wins, ":" , user_losses)
u=1
while u == 1:
resu=input("Press Q to quit the game.")
if resu=="q":
closr()
I hope the question makes sense.
Related
Sometimes when I pick odd, and the result is odd it gives me that the computer won but it's wrong.
Also the scores aren't working, the score always prints 1.
import random
options = ["odd", "even"]
user_wins = 0
comp_wins = 0
while True:
user_answer = input("Choose odd or even. ").lower()
if user_answer not in options:
print("Try again.")
quit()
user_answer2 = input("Choose a number larger than zero. ")
if user_answer2.isdigit():
user_answer2 = int(user_answer2)
if user_answer2 <= 0:
print("Type a number larger than zero. ")
quit()
else:
print("Type a number next time.")
quit()
comp_pick = random.randint(0, 10)
if user_answer == "odd":
print("Computer picked even and its number is", comp_pick)
else:
print("Computer picked odd and its number is", comp_pick)
total = user_answer2 + comp_pick
if total % 2 == 0:
result = "even"
else:
result = "odd"
if result == "even" and user_answer == "even":
print("The result is", total, "You won!")
user_wins =+ 1
else:
print("The result is", total, "Computer won!")
comp_wins =+ 1
print("Your score:", user_wins)
print("Computer score:", comp_wins)
You can't win if you choose odd because of your last if statement:
if result == "even" and user_answer == "even":
which only lets you win if you choose even. You could try changing it to
if result == user_answer:
comp_wins =+ 1 is the same as comp_wins = +1 which is the same as comp_wins = 1. You must have meant:
comp_wins += 1
Same applies to user_wins =+ 1.
So I'm relatively new to python and I'm having issues with fixing the leaderboard part of the code. I've spent a lot of time but I haven't been able to make it work. I know there are a few examples of answers to the same question on stack overflow but so far none of them have worked. Is there any way to make it work?
#task2
import random #When the user rolls the dice this will give them a random number
import time #It'll pause the sequence for a specific amount of time
enter = 0 #the number of times a user enters Username and Password
tries = 0 #this is the number of times a user fails to enter the correct verification
rolling = 0 #this is the number of rounds the game continues to loop, which is 5
i = 0 #required for for...loop
rounds = 0 #this is for last while statements where the winner is decided
p1sc = 0 #for total score of player 1 which is added or taken away each round
p2sc = 0 #for total score of player 2 which is added or taken away each round
while enter == 0: #if enter becomes anything other than 0, the game will start
try:
leaderboard_list = [0,0,0,0,0,'-','-','-','-','-']
file = open('leaderboard.txt', 'x')
for item in leaderboard_list:
file.write('%s\n' % item)
file.close
except:
print("")
code = input("Input the authorization code to play this game: ")
if code == ("password"): #Checking whether the input code is "dice" or not
print("You have entered authorization code correctly, enjoy the game!")
player1 = input("What would Player 1 like to be called? ") #asking user 1 to input the name they want to be called
player2 = input("What would Player 2 like to be called? ") #asking user 2 to input the name they want to be called
print(player1,"and",player2 +", prepare to play, the game will now start...")
time.sleep(1)
enter = 1
else:
print("\nIncorrect authorization code please try again!")
tries = 1 + tries #required for next if statement
if tries == 4: #If user enters wrong password or username 4 times than the user have to wait 1 minute and try again until the user gets username and password correct
print("You have entered incorrect authorization code too many times, please try again after 1 minute!")
time.sleep(60) #For 1 minute the user won't be able to try again
tries = 0
else:
print()
if enter == 1:
for i in range(0,5): #this will allow the upcoming code to be looped only 5 times
while rolling == 0: #if rolling is 1 then player 2 has to roll the dices this continues, until i is in range(0,5)
p1 = input("\n"+ str(player1) +", press r to roll the dice: ")
if p1!= "r":
print()
else:
p1dice1 = random.randint(1,6) #allows any number to be chosen from 1 to 6
p1dice2 = random.randint(1,6)
p1dice3 = random.randint(1,6)
print("Rolling dice 1...")
time.sleep(1)
print("Dice 1 rolled a", p1dice1)
print("Rolling dice 2...")
time.sleep(1)
print("Dice 2 rolled a", p1dice2)
p1total = p1dice1 + p1dice2
rolling = 1 #for next while loop statement which is for player 2
if p1dice1 == p1dice2: #if statements according to the game rule
print("You rolled a double.Well done! You get to roll one more die.")
time.sleep(1)
print("Rolling dice 3...")
time.sleep(1)
print("Dice 3 rolled a", p1dice3)
p1total = p1total + p1dice3
else:
p1total = p1total
if p1total%2 == 0: #To check whether the number is odd or even
p1sc = p1sc + p1total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10. Now,you have",p1sc,"as a total score.")
elif p1total%2 == 1:
p1sc = p1sc + p1total - 5 #after it is subtracted from 5, elif statement is used as only after subtracting the number; the number can be less than, equal or greater than 0
if p1sc == 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted 5. Now,you have",p1sc,"as a total score.")
elif p1sc < 0:
p1sc = 0
print("Your total score was subtracted by 5 and went below 0 but according to the game rule, the total score can't go below 0. So, your total score remains 0.")
elif p1sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5. Now,you have",p1sc,"as a total score.")
else:
print()
while rolling == 1: #if rolling is 0 then player 1 has to roll the dices this continues, until i is in range(0,5)
p2 = input("\n"+ str(player2) +", press r to roll the dice: ")
if p2!= "r":
print()
else:
p2dice1 = random.randint(1,6)
p2dice2 = random.randint(1,6)
p2dice3 = random.randint(1,6)
print("Rolling dice 1...")
time.sleep(1)
print("Dice 1 rolled a", p2dice1)
print("Rolling dice 2...")
time.sleep(1)
print("Dice 2 rolled a", p2dice2)
p2total = p2dice1 + p2dice2
rolling = 0 #for player 1 to roll the dices again
rounds = rounds + 1 #for the game to loop 5 times and be checked by upcoming while rounds == 5
if p2dice1 == p2dice2:
print("You rolled a double.Well done!You get to roll one more die.")
time.sleep(1)
print("Rolling dice 3...")
time.sleep(1)
print("Dice 3 rolled a", p2dice3)
p2total = p2total + p2dice3
else:
p2total = p2total
if p2total%2 == 0:
p2sc = p2sc + p2total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10. Now,you have",p2sc,"as a total score.")
elif p2total%2 == 1:
p2sc = p2sc + p2total - 5
if p2sc == 0:
print("You have total score as an odd number. So,according to the rule;your new total score now will be subtracted 5. Now,you have",p2sc,"as a total score.")
elif p2sc < 0:
p2sc = 0
print("Your total score was subtracted by 5 and went below 0 but according to the game rule, the total score can't go below 0. So, your total score remains 0.")
elif p2sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5. Now,you have",p2sc,"as a total score.")
else:
print()
while rounds == 5:
while p1sc == p2sc:
print("\nAs you both have the same score, now you both will have to keep rolling 1 dice until someone wins!")
time.sleep(2)
p1 = input("\n"+ str(player1) +", press y to roll the dices: ")
if p1 != "y":
print()
else:
p1dice1 = random.randint(1,6)
print("Rolling the dice...")
time.sleep(1)
print("The dice rolled a", p1dice1)
p1total = p1dice1
if p1total%2 == 0:
p1sc = p1sc + p1total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10.")
elif p1total%2 == 1:
p1sc = p1sc + p1total - 5
if p1sc == 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted 5.")
elif p1sc < 0:
p1sc = 0
print("Your total score was subtracted by 5 :(;(")
elif p1sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5.")
else:
print()
p2 = input("\n"+ str(player2) +", press y to roll the dices: ")
if p2 !="y":
print()
else:
p2dice1 = random.randint(1,6)
print("Rolling the dice...")
time.sleep(1)
print("The dice rolled a", p2dice1)
p2total = p2dice1
if p2total%2 == 0:
p2sc = p2sc + p2total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10.")
elif p2total%2 == 1:
p2sc = p2sc + p2total - 5
if p2sc == 0:
print("You have total score as an odd number. So,according to the rule;your new total score now will be subtracted 5.")
elif p2sc < 0:
p2sc = 0
print("Your total score was subtracted by 5 :(;(")
elif p2sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5.")
else:
print()
if p1sc > p2sc:
time.sleep(1)
print("\nThe scores have been added up and....")
time.sleep(3)
print(str(player1)+" is the winner with "+str(p1sc)+" points.")
print(str(player2)+", better luck next time. Your total score is "+str(p2sc)+".")
rounds = 6 #to stop the loop
else:
time.sleep(1)
print("\nThe scores have been added up and....")
time.sleep(3)
print(str(player2)+" is the winner with "+str(p2sc)+" points.")
print(str(player1)+", better luck next time. Your total score is "+str(p1sc)+".")
rounds = 6 #to stop the loop
leaderboard_list = [] # Reads the highscore list
with open('leaderboard.txt') as reader:
for line in reader:
leaderboard_list.append(line.rstrip("\r\n"))
for j in range(0,4): #Converts the scores from the list into integers
leaderboard_list[j] = int(leaderboard_list[j])
for x in range(0,4): #Shuffles the list down depending on how high the scoore was
curr = leaderboard_list[x]
if leaderboard >= curr:
for i in range(5, x + 1, -1):
leaderboard_list[i + 4] = leaderboard_list[i + 3]
leaderboard_list[i - 1] = leaderboard_list[i - 2]
leaderboard_list[x] = leaderboard
leaderboard_list[(x + 5)] = winner
break
else:
pass
file = open('score.txt', 'w+') #Writes the updated highscore list into the txt file
for item in leaderboard_list:
file.write('%s\n' % item)
file.close()
print("""The highscores for this game are """) #Prints the highscore list
for x in range(5):
print(x + 1,") ", leaderboard_list[x], " by ", leaderboard_list[x + 5])
The error message:
Traceback (most recent call last):
File "main.py", line 190, in <module>
leaderboard_list[j] = int(leaderboard_list[j])
IndexError: list out of range
Thanks! Any help would be appreciated!
The relevant part of your code is this:
leaderboard_list = [] # Reads the highscore list
with open('leaderboard.txt') as reader:
for line in reader:
leaderboard_list.append(line.rstrip("\r\n"))
for j in range(0,4): #Converts the scores from the list into integers
leaderboard_list[j] = int(leaderboard_list[j])
When posting a question here, it's probably best to keep it small like that.
Anyway, you are iterating over range(0,4). This gives you:
[0, 1, 2, 3] as values for j.
So essentially, your for-loop is doing the following:
leaderboard_list[0] = int(leaderboard_list[0])
leaderboard_list[1] = int(leaderboard_list[1])
leaderboard_list[2] = int(leaderboard_list[2])
leaderboard_list[3] = int(leaderboard_list[3])
And this crashes with an IndexError.
That means that one (or all) of these indexes do not exist. The list is probably either empty, or less than 4 lines long.
The easiest way to debug this is to simply print the list before you do this operation:
print(*leaderboard_list)
And the operation that you're trying to do (turn them all into int values) can be done like this:
leaderboard_list = map(int, leaderboard_list)
Good luck on your Python journey!
I wanted to create a function which can keep track of the scores from each of the questions and then use it in another function which returns the final result to the user. I have no idea of how to do so.
# Function for question 1
def ask_question_one(difficulty):
score = 0
print("What is the capital city of Canada?")
answer = input()
if difficulty <= 3:
if answer == "Ottawa" or answer == "ottawa":
score = score + 10
print("Your score is:", score)
else:
print(score)
elif difficulty > 3 and difficulty <= 7:
if answer == "Ottawa" or answer == "ottawa":
score = score + 30
print ("your score is:", score)
else:
print("You have given an incorrect answer. You lose 5 points.")
score = score - 5
print("Your score is:", score)
else:
count = 1
while count < 3:
answer = input()
if answer != "Ottawa" or answer != "ottawa":
score = score - 5
print("Your score is:", score)
score = score + 50
print("Your score after two tries is:", score)
def display_result(difficulty, score):
if difficulty <= 3 and score > 30:
print("Your difficulty level is", str(difficulty) + " and your score is", str(score))
# Top-level code.
set_difficulty = int(input("Please enter a difficuty level between 1 and 10: "))
if set_difficulty == "":
print("You did not enter a difficulty level. Try again! Exiting quiz.")
exit()
elif set_difficulty == 0:
print("0(zero) is not a valid difficulty. Exiting quiz.")
exit()
elif set_difficulty > 10:
print("Select a difficulty level less than 10.")
exit()
else:
print("....Let's begin the quiz....")
ask_question_one(set_difficulty)
here is what i have done so far
Please explain the comment correctly. Then maybe I can answer (I am putting this here because I don't have enough reputation for posting comments :'( ).
Hi all programming masters! Im working on a python guessing game and want to change the format of my print to file from "name: win 0: loss 0: guess 0", to "Name | Win or loss (not both) | number of guesses". Im not sure how to make it print the win OR loss, do i need another if statement to print to the txt file?
import random
print("Number guessing game")
name = input("Hello, please input your name: ")
win = 0
loss = 0
guesses = 0
diceRoll = random.randint(1, 6)
if diceRoll == 1:
print("You have 1 guess.")
if diceRoll == 2:
print("You have 2 guesses.")
if diceRoll == 3:
print("You have 3 guesses.")
if diceRoll == 4:
print("You have 4 guesses.")
if diceRoll == 5:
print("You have 5 guesses.")
if diceRoll == 6:
print("You have 6 guesses.")
elif diceRoll != 1 and diceRoll != 2 and diceRoll != 3 and diceRoll != 4 and diceRoll != 5 and
diceRoll != 6:
print("Invalid input!")
number = random.randint(1, 3)
chances = 0
print("Guess a number between 1 and 100:")
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
win += 1
guesses = guesses + 1
break
elif guess < number:
print("Your guess was too low")
guesses = guesses + 1
else:
print("Your guess was too high")
guesses = guesses + 1
chances += 1
else:
print("YOU LOSE!!! The number is", number)
loss += 1
print(name)
print("win: "+str(win))
print("loss: "+str(loss))
stat = open("Statistics.txt", "a")
stat.write(name + ":" + " win: "+str(win) + " loss: " +str(loss) +" guesses: "+str(guesses)),
stat.close()
You can solve the critical part using the ternary statement, an "if-then-else" expression, like this:
result = "Win" if win == 1 else "Loss"
stat.write((name + ":" + result + " guesses: "+str(guesses))
Beyond this, I strongly recommend that you look up "Python output format", so you can improve your range of expression. You won't have to keep doing string construction for your output statements.
Doing a dice Rolling game in python, and whenever I start my second round I still end up getting the same dice results from the previous round.
import random
import time
#gets the dice side
def roll_dice(sides):
dice_results = list()
for side in sides:
roll_result = random.randint(1,side+1)
dice_results.append(roll_result)
return dice_results
#pulls a dice out from the list
def dice_fell(roll_result):
player1_dice = player1_dice_results
player2_dice = player2_dice_results
for item in player1_dice:
if item % 4 == 0:
player1_dice.remove(item)
return player1_dice
for item in player2_dice:
if item % 4 == 0:
player2_dice.remove(item)
return player2_dice
# variables
dice_set1=[4, 6, 8, 10, 12, 20, 100]
dice_set2=[4, 6, 8, 10, 12, 20, 100]
player1_dice_results = roll_dice(dice_set1)
player2_dice_results = roll_dice(dice_set2)
player1_final_results = dice_fell(player1_dice_results)
player2_final_results = dice_fell(player2_dice_results)
player1_total= sum(player1_dice_results)
player2_total= sum(player2_dice_results)
player1_score = 0
player2_score = 0
while player1_score < 3 or player2_score < 3:
# This part just announces what happens
exit= input(str("Press Enter to start! Press 'q' to leave after each round! \n"))
if exit != "q":
print("Let's begin! Be careful for the small table!")
elif exit == "q":
quit()
print("You are rolling...")
time.sleep(2)
print("You have rolled: ",player1_final_results)
if len(player1_final_results) < 7:
print("Sorry player 1, some of your dice have fallen off the table!")
print()
print("Your total is: ",player1_total)
print()
print("Player 2 is rolling...")
time.sleep(2)
print("Player 2 has rolled:" ,player2_final_results)
if len(player2_final_results) < 7:
print("Sorry player 2, some of your dice have fallen off the table!")
print()
print("Player 2's total is: ",player2_total)
print()
if player1_total > player2_total:
print()
print("You have won the round with,",player1_total,"!"),
player1_score += 1
print("Your score is: ",player1_score)
elif player2_total > player1_total:
print()
print("Player 2 has won the round with,",player2_total,"!"),
player2_score += 1
print("Player 2's score is: ",player2_score)
if player1_score == 3:
print("Congratulations, you won!")
elif player2_score == 3:
print("Player 2 wins! Better luck next time champ!")
I believe that I've fixed the indentation problems.
I have reproduced the problem.
As Kevin said, your immediate problem is that you roll the dice only once, before you enter your while loop. Here's what it looks like with the rolls inside the loop, but after the player decides whether to continue.
dice_set1=[4,6,8,10,12,20,100]
dice_set2=[4,6,8,10,12,20,100]
player1_score = 0
player2_score = 0
while player1_score < 3 or player2_score < 3:
# This part just announces what happens
exit = raw_input(str("Press Enter to start! Press 'q' to leave after each round! \n"))
if exit != "q":
print("Let's begin! Be careful for the small table!")
elif exit == "q":
quit()
player1_dice_results = roll_dice(dice_set1)
player2_dice_results = roll_dice(dice_set2)
player1_final_results = dice_fell(player1_dice_results)
player2_final_results = dice_fell(player2_dice_results)
player1_total= sum(player1_dice_results)
player2_total= sum(player2_dice_results)
print("You are rolling...")
... # remainder of code omitted
That said, do note that you have several other problems with the program. You won't terminate until both players have won three times -- use and instead of or in the while condition.
Most of my other comments are more appropriate for the codeReview group; you might post there when you're done debugging.