I am making this code for a school project and whenever it enters an even number, it is supposed to check if that number is in the list then add 10 to it. instead, it just skips the +10 bit and instead minuses 5 from it. here is the code:
import random
print("Lets Play")
play1 = input("Player 1 name?")
play2 = input("Player 2 name?")
print("Hi " + play1 + " & " + play2 + ", let" + "'" + "s roll the dice")
diceNumber = float(random.randint(2,12))
diceNumber2 = float(random.randint(2,12))
diceNumber3 = random.randint(2,12)
diceNumber4 = random.randint(2,12)
diceNumber5 = random.randint(2,12)
diceNumber6 = random.randint(2,12)
diceNumber7 = random.randint(2,12)
diceNumber8 = random.randint(2,12)
diceNumber9 = random.randint(2,12)
diceNumber0 = random.randint(2,12)
print(play1, "Your number is...")
print(diceNumber)
print(play2, "Your number is...")
print(diceNumber2)
evennumber = list = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
evennumber = [float(i) for i in list]
if (diceNumber) == (evennumber):
(diceNumber01) = (diceNumber) + float(10)
else:
(diceNumber01) = (diceNumber) - float(5)
evennumber = list = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
evennumber = [float(i) for i in list]
if (diceNumber2) == (evennumber):
float(diceNumber2) + float(10)
else:
float(diceNumber2) - float(5)
print (play1, "Your total points is",diceNumber01,)
print (play2, "Your total points is",diceNumber2,)
You should use the in operator to check if a value is among the values in a list.
Change:
if (diceNumber) == (evennumber):
to:
if (diceNumber) in (evennumber):
You have a some excess and issues in here, here's a brief summary and some changes.
Only two dice being used, no need to create 10
No clear purpose for dice values being float
Can check for evens using if not x % 2, also if we were to use even list as shown, the only relevant evens are 2 through 12
diceNumber == evennumber is checking one value to see if it equals and entire list, if used properly would be if diceNumber in evennumber
This statement float(diceNumber2) + float(10) assigns the result to nothing
Here is a cleaned up version with some modifications, I recommend using random.choice here and just select a random number from a range of numbers so you don't have to randomly generate a new int in range everytime, results will be the same.
from random import choice
print("Lets Play")
play1 = input("Player 1 name: ")
play2 = input("Player 2 name: ")
print("Hi " + play1 + " & " + play2 + ", let" + "'" + "s roll the dice")
die = list(range(2, 13))
d_1 = choice(die)
print(play1, "Your number is...\n{}".format(d_1))
d_2 = choice(die)
print(play2, "Your number is...\n{}".format(d_2))
if not d_1 % 2:
d_1 += 10
else:
d_1 -= 5
if not d_2 % 2:
d_2 += 10
else:
d_2 -= 5
print (play1, "Your total points is",d_1)
print (play2, "Your total points is",d_2)
Lets Play
Player 1 name: vash
Player 2 name: stampede
Hi vash & stampede, let's roll the dice
vash Your number is...
5
stampede Your number is...
2
vash Your total points is 0
stampede Your total points is 12
Related
I'm trying to write a simple program to test out the basics of Python I've been learning. I decided to do a simple tongue in cheek gambling script that checks a user entered number against a 1,100 random generated number. I want to multiply the users stake by a different amount depending on how close to the random number the user guessed, but cant seem to get it to check within a range using == or <= etc. Or at least cant work it out.
i.e, user stakes 10 on number 15.
if the random number is 20 it's within 5 of the users number so multiply the stake by 25.
if the random number is 25 its within 10 or less of the users number so multiply by 10 etc.
Here's what I've got, would love to hear any advice on this!
if random_number == int(playernumber):
playerstake = int(playerstake) * 100
print("\nCongratulations, you hit the JACKPOT and won £" + str(playerstake) + "!!!")
#+/- 1
elif int(playernumber) == int(random_number) + 1:
playerstake = int(playerstake) * 50
print("\nCongratulations, you guessed within 1 of " + str(random_number) + " and won £" + str(playerstake) + "!")
elif int(playernumber) == int(random_number) - 1:
playerstake = int(playerstake) * 50
print("\nCongratulations, you guessed within 1 of " + str(random_number) + " and won £" + str(playerstake) + "!")
#+/- 5
elif int(playernumber) == int(random_number) + 5:
playerstake = int(playerstake) * 20
print("\nCongratulations, you guessed within 5 of " + str(random_number) + " and won £" + str(playerstake) + "!")
elif int(playernumber) == int(random_number) - 5:
playerstake = int(playerstake) * 20
print("\nCongratulations, you guessed within 5 of " + str(random_number) + " and won £" + str(playerstake) + "!")
etcetc
I understand this currently doesn't work because I'm == random number + 1
so 12 would be 13.
Apologies if I've done something frowned upon here, this was my first script I tried to tackle and wanted to see the potential ways to have done this 'properly'. Thanks for the replies!
If I'm understanding correctly, much simpler code:
dist = abs(guess - rand_num)
if dist == 0:
multiplier = 100
elif dist <= 1:
multiplier = 50
elif dist <= 5:
multiplier = 20
elif dist <= 10:
multiplier = 10
else:
multiplier = 0
player_stake += player_stake * multiplier
if dist == 0:
print("Congratulations you've won")
else:
print("Congratulations you guessed {0} within {1} and won ${3}".format([multiplier, rand_num, player_stake])
Here's a simple solution. I'll let you discover how it works!
pn = int(player_number)
rn = random_number
if rn == pn:
print("You won!")
elif rn in range(pn-1, pn+1+1): # range goes up to the final value (less than), so you need a +1
print("You won +- 1!")
elif rn in range(pn-5, pn+5+1):
print("You won +- 5!")
else:
print("You lost!")
The next chlallenge would be to make the 'checks', +-1, +-5, an array of values, but that was outside the scope of your question.
Don't repeat yourself. You could replace your if clauses with a lookup table. With only 3 things, its a toss-up whether this is better, but generally, if the logic is the same within multiple conditional clauses, its good to pull that logic out into a single implementation. The lookup table lets you change the boundaries used for selection without touching the logic.
# assumes `diff`, `random_number` and `playerstake` defined at time of use
exact_text = f"Congratulations, you hit the JACKPOT and won £{playerstake}"
near_text = f"Congratulations, you guessed within {diff} of {random_number} and won £{playerstake}"
# lookup table: (diff, payout, text)
odds = [
(0, 100, exact_text),
(1, 50, near_text),
(5, 20, near_text)
]
playernumber = int(playernumber)
playerstake = int(playerstake)
player_diff = abs(random_number - playernumber)
for diff, payout, text in odds:
if player_diff <= diff:
playerstake *= payout
print(text)
break
else:
print(f"You were {player_diff} away from the random number")
I had to build a game which awards players based on their guess. The user guesses a number and the algorithm compares that to a randomly-generated 2-digit number and awards the player accordingly.
Problem: The player needs to play this game 3 times before the game ends. When I loop it 3 times with a while loop it only loops by asking the user for their guess and does not print or return the award message. When I remove the while loop and use a for loop it only runs once and prints the message.
How do I solve this looping issue and run this program thrice?
import random
jackpot = 10000
award2 = 3000
award3 = 100
noaward = 0
play = 3
turns = 1
def lottery_game():
for x in range(play):
lottery = random.randrange(10,99)
lot = list(map(int, str(lottery)))
guess = int(input("Choose a 2 digit number: "))
n_guess = list(map(int, str(guess)))
if guess == lottery:
return "You won: " + str(jackpot) + " Euros"
elif n_guess[0] == lot[0] or n_guess[1] == lot[1]:
return "You won: " + str(award2) + " Euros"
elif n_guess[0] == lot[1] or n_guess[1] == lot[0]:
return "You won: " + str(award3) + " Euros"
else:
return "I am sorry, you won: " + str(noaward) + " Euros" + " try again"
while i <= 3:
lottery_game()
i = i + 1
According to your code, you're not initialising your i variable before your while you shoud definitely do it. But for your use case, you shouldn't use a while, you should use a for loop like this:
for i in range(0,3):
This will run the code in the loop three times.
You need to
replace return with print statement:
replace while i <= 3 with for i in range(3)
Here is updated code:
import random
jackpot = 10000
award2 = 3000
award3 = 100
noaward = 0
def lottery_game():
lottery = random.randrange(10, 99)
lot = list(map(int, str(lottery)))
guess = int(input('Choose a 2 digit number: '))
n_guess = list(map(int, str(guess)))
if guess == lottery:
print(f'You won: {jackpot} Euros')
elif n_guess[0] == lot[0] or n_guess[1] == lot[1]:
print(f'You won: {award2} Euros')
elif n_guess[0] == lot[1] or n_guess[1] == lot[0]:
print(f'You won: {award3} Euros')
else:
print(f'I am sorry, you won: {noaward} Euros. Try again')
for i in range(3):
lottery_game()
Sample output:
Choose a 2 digit number: I am sorry, you won: 0 Euros. Try again
Choose a 2 digit number: You won: 100 Euros
Choose a 2 digit number: You won: 10000 Euros
you have not initialized i
Before the while statement add i=1
I am making a number guessing game for a project as a part of my intro to the coding class. I am trying to calculate the total earnings for the user, but I keep getting a type error and I have no idea what I am doing wrong.
print("To begin the game pay two dollars")
print("You can collect your winnings when you stop playing")
import sys
count = 0
Jackpot_wins = 0
Reversed_digits = 0
Digit_WrongPlacement = 0
Digit_RightPlacement = 0
Digit_RightPlacement_two = 0
Digit_WrongPlacement_two = 0
JackpotValue = 100
Reversed_digitsValue = 10
Digit_RightPlacementValue = 10
Digit_WrongPlacementValue = 5
Cost_Per_Play = 2
Game_start = input("Would you like to play? enter 'y' for yes and 'n' for no: ")
if Game_start == "n":
print("Thats ok, maybe next time")
sys.exit()
while Game_start == "y":
count = count + 1
Money_Spent = count * Cost_Per_Play
Player_Number = int(input("Enter a number 0-99: "))
print(Player_Number)
import random
Hidden = random.randint(0,99)
Reversed_digits = (str(Hidden)[::-1])
print(Hidden)
Jackpot = Hidden == Player_Number
PN = int(Player_Number / 10)
RN = int(Hidden / 10)
PN1 = int(Player_Number % 10)
RN1 = int(Hidden % 10)
if Jackpot:
print("Jackpot!!! You win 100 dollars!!!")
Jackpot_wins = int(Jackpot_wins + 1)
elif Player_Number == Reversed_digits:
print("Right digits, wrong order!... You win 10 dollars!")
Reversed_digits = int(Reversed_digits + 1)
elif PN == RN:
print("One digit correct, place correct. You win 10 dollars!")
Digit_RightPlacement = int(Digit_RightPlacement + 1)
elif RN1 == PN1:
print("One digit correct, place correct. You win 10 dollars!")
Digit_RightPlacement_two = int(Digit_RightPlacement_two + 1)
elif PN1 == RN:
print("One digit correct, place incorrect. You win 5 dollars!")
Digit_WrongPlacement = int(Digit_WrongPlacement + 1)
elif RN1 == PN:
print("One digit correct, place incorrect. You win 5 dollars!")
Digit_WrongPlacement_two = int(Digit_WrongPlacement_two + 1)
else:
print("Completely wrong")
Game_start = input("To continue type 'y' to end type anything: ")
JP_money = Jackpot_wins * JackpotValue
RD_money = Reversed_digits * Reversed_digitsValue
DRP_money = Digit_RightPlacement * Digit_RightPlacementValue
DRP1_money = Digit_RightPlacement_two * Digit_RightPlacementValue
DWP_money = Digit_WrongPlacement * Digit_WrongPlacementValue
DWP1_money = Digit_WrongPlacement_two * Digit_WrongPlacementValue
Winnings = JP_money + RD_money + DRP_money + DRP1_money + DWP_money + DWP1_money
Total_earnings = Winnings - Money_Spent
if Game_start != "y":
print("See you next time! You played ", count, "rounds.")
print("you spent $ ", Money_Spent)
print("Wow you won the Jackpot", Jackpot_wins, "times!")
print("Your total earnings are", Total_earnings, "Congrats!")
I expected the code to keep tally of the wins and their varying values but I am either getting a type error or a value that is unbelievable like 72727171723
Yes, I tested the code, in your Winning calculation RD_Money is returning string number,
Winnings = JP_money + RD_money + DRP_money + DRP1_money + DWP_money + DWP1_money
For resolving this you can just convert it in the calculation like this
Winnings = JP_money + int(RD_money) + DRP_money + DRP1_money + DWP_money + DWP1_money
or you can do this
RD_money = int(Reversed_digits) * Reversed_digitsValue
This will solve your problem
I'm trying to debug some code I have written for homework, but I cannot fix an error that occurs no matter what I try.
I've tried copying some code from my friends, but no matter what code I try I keep getting this error.
#NEA 2019 DICE GAME
from time import sleep as wait
from random import randint as rand
#Here I have imported my modules that I will use later on.
Check1 = 0
#Here I create a check variable, for use in the usernames section.
print("welcome to Dice Game!")
print("Main Menu: \n 1. Play Game \n 2. Register User \n 3. View Leaderboard \n 4. Quit Game")
MenuChoice = int(input("Please enter the number of the option you would like to choose."))
#Nice greeting for the user, and a menu.
elif MenuChoice == 1:
while Check1 == 0:
Namae = input("Player One, Please enter your username: \n")
with open('Usernames.txt') as openfile:
if Namae in openfile.read():
print("Username",Namae, "Valid!")
Check1 = 1
Pass = input("Please enter the passkey:")
if Pass == 'VN467' or Pass == 'Backdoor':
#This 'if' statement allows the user to log in using a universal passkey, or allows an administrator to log in using a backdoor.
print("User Authenticated!")
else:
print("Invalid Passkey!")
else:
print("Username",Namae, "Invalid!")
#This block allows a user to log in as player 1.
while Check1 == 1:
Namae2 = input("Player Two, Please enter your username: \n")
if Namae == Namae2:
print("Both players can't have the same username!")
Namae2 = ''
with open('Usernames.txt') as openfile:
if Namae2 in openfile.read():
print("Username", Namae2, "Valid!")
Check1 = 0
Pass = input("Please enter the passkey:")
if Pass == 'VN467' or Pass == 'Backdoor':
print("User Authenticated!")
else:
print("Invalid Passkey!")
else:
print("Username", Namae2, "Invalid!")
#This block allows a user to log in as player 2.
P1total = 0
P2total = 0
for i in range (1,5):
print("Game starting!")
wait(1)
print("ROUND", i)
print(Namae, " Press 'Enter' to roll")
#This gives the player a message box to allow them to roll.
Roll1 = rand(1,6)
Roll2 = rand(1,6)
#This is the command to roll the dice.
if Roll1 == Roll2:
print("Double! You get an extra dice!")
Roll3 = rand(1,6)
#This gives the player another dice if they roll a double.
else:
Roll3 = 0
#This sets the value of Roll3 to zero, to prevent a NameError later on.
TempTotal = Roll1 + Roll2 + Roll3
print("The total of the dice is", TempTotal)
#These lines add together all of the dice.
if TempTotal%2 == 0:
print("Even total! +10 points!")
TempTotal = TempTotal + 10
#These lines check if the dice total is even, then adds 10 if it is.
else:
print("Odd total! -5 points")
TempTotal = TempTotal - 5
#These lines check if the dice total is odd, then subtracts 5 if it is.
P1total = P1total + TempTotal
if P1total < 0:
P1total = 0
#These lines make sure that the total cannot go below 0, and sets it to 0 if it does.
print(Namae, "Your total is", P1total)
#This prints the current total for player 1.
print(Namae2," Press 'OK' to roll")
Roll1 = rand(1,6)
Roll2 = rand(1,6)
#This rolls the two dice.
if Roll1 == Roll2:
print("Double! You get an extra dice!")
Roll3 = rand(1,6)
#This adds another dice if the player rolls a double.
else:
Roll3 = 0
#This sets Roll3 to 0 to prevent a NameError later on in the code.
TempTotal = Roll1 + Roll2 + Roll3
#This adds up the dice to create a total.
print("The total of the dice is", TempTotal)
#This tells the player what the dice rolled.
if TempTotal%2 == 0:
print("Even total! +10 points!")
TempTotal = TempTotal + 10
#This adds 10 points to the total if they roll an even number.
else:
print("Odd total! -5 points")
TempTotal = TempTotal - 5
#This takes away 5 points from the total if they roll an odd number.
P2total = P2total + TempTotal
if P2total < 0:
P2total = 0
print(Namae2, "Your total is", P2total)
if P1total == P2total:
print("There is a draw! \n Both players will roll 1 die.")
Roll1 = rand(1,6)
Roll2 = rand(1,6)
#This makes it so that there cannot be a draw
print("Player 1 rolls a", Roll1, "\n Player 2 rolls a",Roll2)
while Roll1 == Roll2:
print("Another Draw!")
Roll1 = rand(1,6)
Roll2 = rand(1,6)
#This makes it so that if the first reroll ends in a draw, there will keep being rerolls until there is no longer a draw.
print("Player 1 rolls a", Roll1, "\n Player 2 rolls a",Roll2)
if Roll1 > Roll2:
print(Namae, "Wins!")
#Prints a winning message.
else:
print(Namae2, "Wins!")
#This prints a winning message
elif P1total > P2total:
print(Namae, "wins!")
Winner = Namae
WinScore = P1total
#This prints a message if player 1 wins
else:
print(Namae2, "wins!")
Winner = Namae2
WinScore = P2total
#This prints a message if player 1 wins.
#Winscore and Winner are used to append the winner to a file later on.
LeaderboardFile = open("Leaderboard.txt", "a+")
#This opens the file to be appended
FullFileInput = Winner + "," + str(WinScore) + "\n"
#This combines the two variables from earlier into one, to make it easier to append.
LeaderboardFile.write(FullFileInput)
#This appends FullFileInput to the file.
LeaderboardFile.close
#Closes the File.
print("Top 5 Scores:")
LeaderboardFile = open("Leaderboard.txt", "r")
#Opens the file for reading.
Array = []
#Creates an empty array
FileLength = len(open("Leaderboard.txt").readlines())
#This reads how many lines the file has
for counter in range(FileLength):
record = LeaderboardFile.readline()
cells = record.split(",")
#This splits the file every time there is a comma
Array.append(cells)
SortedArray = sorted(Array, key = lambda x: x[1])
#This sorts the list in descending order, using score.
x = 1
for counter in range(0,5):
print(len(SortedArray))
holder = SortedArray[(len(SortedArray)-x)]
#This causes an error, for seemingly no reason.
print(x, ":",holder[0], holder[1])
#This prints the leaderboard, one line at a time.
x = x + 1
#Increments x by 1.
elif MenuChoice == 3:
print("Top 5 Scores:")
LeaderboardFile = open("Leaderboard.txt", "r")
Array = []
FileLength = len(open("Leaderboard.txt").readlines())
for counter in range(FileLength):
record = LeaderboardFile.readline()
cells = record.split(",")
Array.append(cells)
SortedArray = sorted(Array, key = lambda x: x[1])
x = 1
for counter in range(5):
holder = SortedArray[(len(SortedArray)-x)]
print(x, ":",holder[0], holder[1])
x = x + 1
#Lines 198 to 211 are all copied and pasted from the leaderboard earlier.
#This code is a formatting disaster, I'm sorry.
After messing around with the game for a bit, with the error appearing every time it attempted to show the leaderboard, I have some files.
Leaderboard.txt:
Contains scored in the format:
Username1,score
Username2,score
And so on...
Usernames.txt:
Contains all valid usernames.
I would expect the result to be something along the lines of:
Top 5 Scores:
1: Alpha 100
2: Beta 91
3: Gamma 85
4: Delta 76
5: Epsilon 69
Instead, the code prints:
Top 5 Scores:
1: Alpha 1
2: Alpha 1
(this always prints the first value in the file twice, without sorting it.)
And then I get the error:
Traceback (most recent call last):
File "main.py", line 200 in <module>
holder = SortedArray[(len(SortedArray)-x)]
IndexError: list index out of range.
The 'IndexError: list index out of range' means that your list indices are out of range. You are trying to refer to some index that doesn't even exist.
holder = SortedArray[(len(SortedArray)-x)]
x = x + 1
For example if x becomes greater than (len(SortedArray) you will get a negative index that can trigger that error.
I hope you don't mind, but I rewrote a part of your code.
elif MenuChoice == 3:
print("Top 5 Scores:")
Array = []
try:
with open("Leaderboard.txt", "r") as LeaderboardFile:
for l in LeaderboardFile.readlines():
name, score = l.split(',')
name = name.strip()
score = int(score.strip())
Array.append([name, score])
except Exception:
print('FileNotFound')
Array = sorted(Array, key = lambda x: x[1], reverse=True)
for i in range(5):
print(f'{i+1}: {Array[i][0]} {Array[i][1]}')
Please, note for next time that because this question is very specific to your own code it is less suitable for SO, but more for https://codereview.stackexchange.com/.
Good luck with your homework assignment.
I want to keep track of the variable TOTAL_TRI. TOTAL_TRI contains the number of correctly answered questions from the game. I need to save that value and pass it to the function statistics when statistics is called. Essentially, the player will play the game py_game, TOTAL_TRI will hold the number of questions they got right, and when the player calls the function statistics, it will display the number of questions they got right? I've been toying with this for a while with no significant progress. Any ideas?
P.S.
The other games in the menu are not yet implemented, but they'll do the same play-save correct number of questions-and let the player call to statistics kind of thing.
import random
from random import choice
from random import randint
#py_game------------------------------------------------------------------------
def py_game():
for k in range (1,3):
print('\nPractice Problem', k, 'of 2')
min_pyramid_size = 3
max_pyramid_size = 5
total_chars = 0
num_rows = random.randint(min_pyramid_size, max_pyramid_size)
for i in range(num_rows):
x = ''.join(str(random.choice('*%')) for j in range(2*i+1))
print(' ' * (num_rows - i) + x)
total_chars = total_chars + x.count('%')
try:
user_answer = int(input('Enter the number of % characters' + \
' in the pyramid: '))
except:
user_answer = print()
if user_answer == total_chars:
print('You are correct!')
else:
print("Sorry that's not the correct answer")
points = 0
for k in range (1,11):
print('\nProblem', k, 'of 10')
min_pyramid_size = 3
max_pyramid_size = 5
total_chars = 0
num_rows = random.randint(min_pyramid_size, max_pyramid_size)
for i in range(num_rows):
x = ''.join(str(random.choice('*%')) for j in range(2*i+1))
print(' ' * (num_rows - i) + x)
total_chars = total_chars + x.count('%')
try:
user_answer = int(input('Enter the number of % characters' + \
' in the pyramid: '))
except:
user_answer = print()
if user_answer == total_chars:
print('You are correct!')
points +=1
else:
print("Sorry that's not the correct answer")
TOTAL_TRI = points
#------------------------------------------------------------------------------
def statistics(points):
print('\nPyramid Game---------------------------')
incorrect = 10 - (points)
print ('You answered', points, 'questions correctly')
print ('You answered', incorrect, 'questions incorrectly')
#Main Menu--------------------------------------------------------------------------
def main_menu():
calculation_game = print("Enter 1 for the game 'Calculation'")
bin_reader = print("Enter 2 for the game 'Binary Reader'")
trifacto_game = print("Enter 3 for the game 'Trifacto'")
statistics = print("Enter 4 to view your statistics")
display_data = print("Enter 5 to display data")
save_game = print("Enter 5 to save your progress")
user_input = int(input('Make your selection: '))
if user_input == 1:
calculation()
if user_input == 2:
binary_reader()
if user_input == 3:
py_game()
if user_input == 4:
statistics(TOTAL_TRI)
if user_input == 5:
save_game()
if user_input != 1 or 2 or 3 or 4 or 5:
print('invalid input')
print('\n')
main_menu()
main_menu()
Using globals is code smell just waiting to happen. Pass your variable as an argument to your function. That's all.