why my dictionary is not get updated in python [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
Here in my code, I am trying to update values in dic with user input using the play function. But the values(\t) is not getting updated by inputted value. Why? how can I fix this?
dic = {7: "\t",
8:"\t",
9: "\t",
4: "\t",
5: "\t",
6: "\t",
1:"\t",
2: "\t",
3: "\t"}
player1 = "null"
player2 = "null"
#player 1 is true and player 2 is false
playerOnesTurn = True
def printBoard():
print(dic[7]+ "|" +dic[8]+ "|"+ dic[9])
print(dic[4]+ "|"+dic[5]+ "|"+ dic[6])
print(dic[1]+ "|"+dic[2]+ "|"+ dic[3])
def play():
if(playerOnesTurn):
print(player1 + "'s turn")
print("Enter the position: ")
pos = input() # it is an int value
dic[pos] = "X"
play()
printBoard()

pos = input() would be a str, not int. Try changing it to pos = int(input())

Related

Python quiz - Where the user can add his questions

I'm making a quiz in Python where a user can add himself the questions and answers and specify the correct one.
I already did this
# Do you want to add another question version
from Question import Question
question_prompt = []
answer_list = []
def add_Question():
question = input('Add your question: ')
print(question)
test = int(input('If your question is correct. Enter 1 else enter 2: '))
if test == 1:
print('Type the answers propositions: ')
a = input('(a): ')
b = input('(b): ')
c = input('(c): ')
d = input('(d): ')
# print(a + '\n' + b + '\n' + c + '\n' + d )
answer = input('Which one is the correct answer? (a) (b) (c) or (d). Just type the letter ie. a: ').lower()
question_insert = f"{question} \n {a} \n {b} \n {c} \n {d}\n\n"
question_prompt.append(question_insert)
answer_list.append(answer)
listing = tuple(zip(question_prompt, answer_list))
questions = [Question(question_prompt[i],answer_list[i]) for i in range(0, len(listing))]
else :
question = input('add your question: ')
print(question)
test = int(input('if your question is correct. Enter 1 else enter 2: '))
return question, a,b,c,d,answer
def insert_question_prompt() :
again = int(input("Do you want to add another question. 1 = 'yes' and 2 = 'no' "))
while again == 1:
add_Question()
again = int(input("Do you want to add another question. 1 = 'yes' and 2 = 'no' "))
print(question_prompt)
def run_test(questions):
score = 0
for question in questions:
answer = input(question.prompt)
if answer == question.answer:
score += 1
print("Hey You got " + str(score) + "out of " + str(len(questions)) + "questions correct")
# questions = [Question(question_prompt[i],answer_list[i]) for i in range(0, len(listing))]
add_Question()
insert_question_prompt()
print(question_prompt)
print(answer_list)
In the function def insert_question_prompt() : I ask the user if he wants to insert another question and repeat the add_Question function.
The run_test function is to test the quiz. Play and access it
But I am unable to access question_prompt and answer_list in the run_test function even though they are not empty.
Basically, I'm blocked at level where the user can test the quiz ie Play and have the score.
Thanks for your help

TicTacToe doesn't apply Win-Conditions && Wrong moves on minimax

i am trying to learn python and have been trying to programm a simple tictactoe game.
Below is the code:
import random
class TicTacToe03:
def __init__(self):
# first, the board
self.board = self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
# then, the symbols the players will choose
self.playerSymbol = ""
self.aiSymbol = ""
# the game is always ongoing, unless somebody won
self.gameOngoing = True
# you also need to tell the ai how different conditions are evaluated
self.scoreBoard = {
self.playerSymbol: -10, # if the player wins, it is seen as smth bad from the ai
self.aiSymbol: 10,
"tie": 0
}
# every tictactoe game starts by drawing the board
def drawBoard(self):
print("""
{} | {} | {}
-----------
{} | {} | {}
-----------
{} | {} | {}
""".format(*self.board))
# then, eveybody chooses what the like
def chooseYourPlayer(self):
self.playerSymbol = input("choose your player X/O ").upper()
if self.playerSymbol == "X":
self.aiSymbol = "O"
else:
self.aiSymbol = "X"
# everybody has to behave and leave their turn when it's over
def nextPlayer(self, player):
if player == self.playerSymbol:
return self.aiSymbol
return self.playerSymbol
# ppl also have to be able to make moves
def move(self, player, index):
self.board[index] = player
# and find what moves they CAN make, so they don't override each-other
def availableMoves(self):
availableMoves = []
for fieldIndex in range(len(self.board)):
if self.board[fieldIndex] == " ":
availableMoves.append(fieldIndex) # yes, i append indexes, not empty fields
return availableMoves
def getMoves(self, player):
playerMoves = []
for fieldIndex in range(len(self.board)):
if self.board[fieldIndex] == player:
playerMoves.append(fieldIndex)
return playerMoves
# here is the algo to check who won, based on a set of winPos is subset of playerMoves
def won(self):
winningPositions = [{0, 1, 2}, {3, 4, 5}, {6, 7, 8},
{0, 4, 8}, {2, 4, 6}, {0, 3, 6},
{1, 4, 7}, {2, 5, 8}]
for player in ("X", "O"):
playerPositions = self.getMoves(player)
for position in winningPositions:
if position.issubset(playerPositions):
print(player + "wins")
self.gameOngoing = False
return player
if self.board.count(" ") == 0: # and this dude outside of the main loop
print("Guess it's a draw")
self.gameOngoing = False
return "tie"
def minimax(self, isMaximizing, player):
if not self.gameOngoing: # base in minimax: if this is an end-state, return it's evaluation
return self.scoreBoard[self.won()]
if isMaximizing:
bestScore = float("-Infinity") # the worst eval for max
for move in self.availableMoves():
self.move(player, move)
score = self.minimax(False, self.nextPlayer(player)) # you should pick the max of what your opponent chooses
self.move(" ", move)
bestScore = max(bestScore, score)
return bestScore
else:
bestScore = float("Infinity")
for move in self.availableMoves():
self.move(player, move)
score = self.minimax(True, self.nextPlayer(player))
self.move(" ", move)
bestScore = min(bestScore, score)
return bestScore
def findOptimalMove(self, player):
goldenMiddle = 0
choices = []
for move in self.availableMoves():
self.move(player, move)
score = self.minimax(True, player)
self.move(" ", move)
if score > goldenMiddle:
choices = [move] # this is a one-element list
break
elif score == goldenMiddle:
choices.append(move)
# here is the code block that mustn't be wrongly interpreted:
# the idea is: you choose a random element, from a ONE-ELEMENT list!!!
if len(choices) > 0:
return random.choice(choices)
else:
return random.choice(self.availableMoves())
def play(self):
self.chooseYourPlayer()
while self.gameOngoing:
personMove = int(input("Choose a position (1-9) "))
self.move(self.playerSymbol, personMove - 1)
self.drawBoard()
if not self.gameOngoing:
break
print("Computer choosing move...")
aiMove = self.findOptimalMove(self.aiSymbol)
self.move(self.aiSymbol, aiMove)
self.drawBoard()
print("Thanks for playing :)")
tictactoe = TicTacToe03()
tictactoe.play()
The game "works", as of it displays the fields of the user, however it won't show whether anybody won or not.
As you can see, i tried implementing the simple minimax algorithm, but that doesn't work properly either, because the ai just chooses the next available field to go to and not the one it logically should.
As for the errors i am getting: i only got one once, after the board was full and it was the following: IndexError: Cannot choose from an empty sequence (on line 133).
I have also posted another version of this, where the "winning" issue is not present ( TicTacToe and Minimax ), but since nobody was answering that question, I thought it would be helpful asking again (sorry if i did anything wrong)
As always, I remain open to suggestions and ways to improve my code :)
In my opinion, the only issue is that you forgot to call self.won() in the play() method:
def play(self):
self.chooseYourPlayer()
while self.gameOngoing:
personMove = int(input("Choose a position (1-9) "))
self.move(self.playerSymbol, personMove - 1)
self.drawBoard()
self.won() #<--- call self.won() here
if not self.gameOngoing:
break
print("Computer choosing move...")
aiMove = self.findOptimalMove(self.aiSymbol)
self.move(self.aiSymbol, aiMove)
self.drawBoard()
print("Thanks for playing :)")
I think you tried to do something similar in minimax() method. But I didn't understand what did you mean by:
if not self.gameOngoing:
return self.scoreBoard[self.won()]

Python <function at 0x> output [duplicate]

This question already has answers here:
"Function ________ at 0x01D57aF0" return in python
(2 answers)
Closed 6 years ago.
I wrote a new function and when I execute it, I get an error:
<function read_grades at 0x000001F69E0FC8C8>
Ok so here is my code:
def add(x, y):
z = x / y * 100
return z
def calc_grade(perc):
if perc < 50:
return "1"
if perc < 60:
return "2"
if perc < 75:
return "3"
if perc < 90:
return "4"
if perc >= 90:
return "5"
def calc_command():
num1 = input("Input your points: ")
num2 = input("Input maximum points: ")
num3 = add(float(num1), float(num2))
grade = calc_grade(num3)
print("This is your result:", str(num3) + "%")
print("Your grade:", grade)
save = open("grades.txt", "r")
read_grades = save.read()
save = open("grades.txt", "w")
save.write(read_grades + grade)
save.close()
def read_grades():
save = open("grades.txt", "r")
read_grades = save.read()
grades = read_grades.split()
save.close()
return grades
while True:
command = input("Input your command: ")
if command == "CALC":
calc_command()
elif command == "EXIT":
break
elif command == "GRADES":
print(read_grades)
elif command == "HELP":
print("These are the commands:\nCALC - Calculates your grade and writes in the file.\nEXIT - Exits the program.\nGRADES - Reads your previous grades.\nHELP - This command. It helps you.")
else:
print("You inputed an invalid command. Type HELP for help.")
This error happens when I execute the read_grades() function or the GRADES command.
For those who marked this question: I did some searching and I didn't find that post and now that i read it i dont understand the answer
That's not a runtime error, you printed a function
print(read_grades)
Try calling it instead
read_grades()
And you override your function here
read_grades = save.read()
So, advice is to not use variable names that conflict with your function names

Dice Poker Scoring System (Function producing NoneType)

So in my coding class we are required to make a "Dice Poker" game. We need to implement a scoring system, however, mine keeps returning a "None", therefore causing issues when I want to add the accumulated score to the base score of 100, since NoneTypes and integers can not be added. I'm aware that I need to fix whatever is causing the None, but I'm not sure how. I believe the problem could be in the "scoring" function, but perhaps it is more lurking in the later parts (After the #Choosing Last Roll or #Scoring output comments) of the function "diceGame". I'm very new to coding, and after hours of looking at this thing I'm not really sure what I'm looking at anymore. Thank you so much for your help!
Text-based dice game
from random import randint
def rollFiveDie():
allDie = []
for x in range(5):
allDie.append(randint(1,6))
return allDie
def outputUpdate(P, F):
print(P)
print(F)
def rollSelect():
rollSelected = input("Which die would you like to re-roll? (Choose 1, 2, 3, 4 and/or 5 from the list) ")
print(" ")
selectList = rollSelected.split()
return selectList
def rollPicked(toRollList, diceList):
for i in toRollList:
diceList[int(i) - 1] = randint(1,6)
def scoring(dList):
counts = [0] * 7
for value in dList:
counts[value] = counts[value] + 1
if 5 in counts:
score = "Five of a Kind", 30
elif 4 in counts:
score = "Four of a Kind", 25
elif (3 in counts) and (2 in counts):
score = "Full House", 15
elif 3 in counts:
score = "Three of a Kind", 10
elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
score = "Straight", 20
elif counts.count(2) == 2:
score = "Two Pair", 5
else:
score = "Lose", 0
return score
def numScore(diList):
counts = [0] * 7
for v in diList:
counts[v] = counts[v] + 1
if 5 in counts:
finScore = 30
elif 4 in counts:
finScore = 25
elif (3 in counts) and (2 in counts):
finScore = 15
elif 3 in counts:
finScore = 10
elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
finScore = 20
elif counts.count(2) == 2:
finScore = 5
else:
finScore = 0
return finScore
def printScore(fscore):
print(fscore)
print(" ")
def diceGame():
contPlaying = True
while contPlaying:
playPoints = 30
if playPoints > 9:
playPoints -= 10
else:
print("No more points to spend. Game Over.")
contPlaying = False
playing = input("Would you like to play the Dice Game? (Answer 'y' or 'n'): ")
print(' ')
if playing == 'y':
#First Roll
fiveDie = rollFiveDie()
outputUpdate("Your roll is...", fiveDie)
#Choosing Second Roll/Second Roll execution
pickDie = input("Which die would you like to re-roll? (Choose 1, 2, 3, 4 and/or 5 from the list) ")
print(" ")
pickDie = pickDie.split()
rollPicked(pickDie, fiveDie)
outputUpdate("Your next roll is...", fiveDie)
#Choosing Last Roll
pickDie = rollSelect()
rollPicked(pickDie, fiveDie)
outputUpdate("Your final roll is...", fiveDie)
#Scoring output
scoring(fiveDie)
finalScore = numScore(fiveDie)
playPoints += finalScore
print(playPoints)
else:
contPlaying = False
def main():
diceGame()
main()

How to get two variables from the previous function in python? [duplicate]

This question already has answers here:
What's the best way to return multiple values from a function? [duplicate]
(6 answers)
Closed 8 years ago.
I'm very new at python so I'm still learning some things. But I'm doing this code and I need to know how to get the x and y variables from the "getHumanMove" function so that I can use it in the "getPiles" function
def getHumanMove(x,y):
finished = False
while not finished:
x=int(input("Which pile would you like to take from?(1 or 2)"))
y=int(input("How many would you like from pile "+ str(x)+ "? "))
if pile1 and pile2<y:
print("pile " +str(x)+ " does not have that many chips. Try again.")
elif y==0:
print("You must take at least one chip. Try again.")
else:
print("That was a legal move. Thank You.")
finished = True
return x,y
def getPiles(pile1, pile2):
print("Here are the piles: ")
#################################Here is where I need to put the x, y variables
pile1= pile1
pile2= pile2
if temp_x == 1:
pile1= pile1- temp_y
print("pile 1: ", str(pile1))
print("pile 2: ", str(pile2))
elif temp_x == 2:
pile2= pile1- temp_y
print("pile 1: ", str(pile1))
print("pile 2: ", str(pile2))
return pile1, pile2
##############################Main##############################
move= getHumanMove(pile1, pile2)
pile= getPiles(pile1, pile2)
How about in your call to getPiles:
pile = getPiles(pile1, pile2, move)
and then in your getPiles definition:
def getPiles(pile1, pile2, move):
x, y = move
Assuming this is what you mean:
x,y = getHumanMove(pile1, pile2)
pile1, pile2 = getPiles(x, y)
You can use tuple unpacking:
move = getHumanMove(pile1, pile2)
pile = getPiles(*move)
Or get each variable separately, so you can pass them separately too:
move1, move2 = getHumanMove(pile1, pile2)
pile = getPiles(move1, move2)
When a function is returning two values, you can do
value1, value2 = some_function(argument1, argument2, argument3, ...)
to store the two return values in value1 and value2.

Categories

Resources