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.
Related
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())
I am creating an Among Us ripoff (for fun!) and the while True & if/elif/else statements will only return false (not An Impostor) with the inputs. I had created a list for the names and 2 random elements from the list will be chosen as An Impostor. However, whenever I input a name that is The Impostor, it will only return
(player) was not An Impostor.
Here is my code;
import sys, time, random
names = ["player1", "player2", "player3", "player4", "player5", "player6", "player7", "player8", "player9", "player10"]
print("Players: ")
for x in names:
print(x)
print('—————————————————————————')
impostor1 = random.choice(names)
impostor2 = random.choice(names)
crewmates = 8
impostors = 2
tries = 6
while True:
talk = input("Guess who The Impostor(s) are. " + str(crewmates) + " Crewmates are left. " + str(impostors) + " Impostors are left. You have " + str(tries) + " tries left.")
if talk in names:
print(talk + " was voted for.")
time.sleep(0.1)
if talk != impostor1 or talk != impostor2:
notimp = talk + " was not An Impostor. "
names.remove(talk)
for y in notimp:
sys.stdout.write(y)
sys.stdout.flush()
time.sleep(0.05)
crewmates -= 1
tries -= 1
elif talk == impostor1 or talk == impostor2:
wasimp = talk + " was An Impostor. "
names.remove(talk)
for v in wasimp:
sys.stdout.write(v)
sys.stdout.flush()
time.sleep(0.1)
impostors -= 1
else:
print("That player was either ejected or is not a valid player.")
However, whenever I put the Impostor in the input, it says it isn't An Impostor?
I think this line is the source of the problem:
if talk != impostor1 or talk != impostor2:
Let's say impostor1 is player1 and impostor2 is player2 and someone input in player1, according to Python Boolean expression operator or that if statement will evaluate like this:
if player1 != impostor1 evaluated to False because player1 is indeed equals to impostor1.
So far so good, but because the first test is a False, Python simply evaluates and returns the right side operand which may be either True or False. In your case Python will evaluate if talk != impostor2 and return True, thereafter executes the nested block.
I'am trying to create a definition that assigns objects in a list to variables but unfortunately it is not working:
when I try to print player_1 (as in the last step) it gives me a
NameError
Any suggestion or feedbacks on how to make the definition shorter or better is always welcome. The whole project( it is till the beginning) is on https://github.com/ahmadkurdo/project---a
If you have time and look at it and give me some feedback on it would be appreciated.
def assign_players(list_of_names):
if len(list_of_names) == 2:
player_1 = list_of_names[0]
player_2 = list_of_names[1]
elif len(list_of_names) == 3:
player_1 = list_of_names[0]
player_2 = list_of_names[1]
player_3 = list_of_names[2]
elif len(list_of_names) == 4:
player_1 = list_of_names[0]
player_2 = list_of_names[1]
player_3 = list_of_names[2]
player_4 = list_of_names[3]
elif len(list_of_names) == 5:
player_1 = list_of_names[0]
player_2 = list_of_names[1]
player_3 = list_of_names[2]
player_4 = list_of_names[3]
player_5 = list_of_names[4]
elif len(list_of_names) == 6:
player_1 = list_of_names[0]
player_2 = list_of_names[1]
player_3 = list_of_names[2]
player_4 = list_of_names[3]
player_5 = list_of_names[4]
player_6 = list_of_names[5]
number_of_players = int(input('How many players are playing? '))
list_of_players = []
while number_of_players > 0:
name_player = input('What is your name ')
list_of_players.append(name_player)
number_of_players = number_of_players - 1
assign_players(list_of_players)
print(player_1)
Your problem is the scope of your variables. Scope means: where is my variable defined/visible and when is it no longer defined.
If you define a variable inside a function (like you do) it is only known inside this function - you can not access it once you leave the function.
The variable is unknown - hence NameError.
You can however return it and by assign it to some other variable as return of your function.
You can work around your specific problem (and get rid of those if statements) by simplifying your code like this:
number_of_players = int(input('How many players are playing? '))
list_of_players = []
for _ in range(number_of_players):
list_of_players.append(input('What is your name '))
player_1,player_2,player_3,player_4,player_5,player_6, *rest = list_of_players + [None]*5
print(list_of_players + [None] * 5)
print(player_1)
print(player_2)
print(player_3)
print(player_4)
print(player_5)
print(player_6)
print(rest)
Output for 2 + 'jim' + 'bob':
['jim', 'bob', None, None, None, None, None] # filled up with [None] * 5
jim
bob
None
None
None
None
[]
The code works by filling up your list to the needed amount of items (using [None] for any not inputted) so that you can decompose the list again into your variables. BUT it would be much easier to leave them in a list:
for round in range(1,10):
for player in list_of_players:
print (player, "'s turn:")
# do something with this player
This is kindof difficult to do if you want to use your player_X variables instead and would lead to lots of duplicate code and you still would have to check if your player_X are filled or None ...
Read more about:
variable scope
list decomposing
As function:
def assign_players(p):
return p + [None]*5
p1,p2,p3,p4,p5,p6,*rest = assign_players(list_of_players)
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
I have the task of producing a Blackjack game in Python which allows up to 4 human players to play plus the automated House.
I have to use a function 'get_deck' (see code below).
I am struggling to figure out how to get a card from 'get_deck' and append it to the player's list.
I managed to make the program when using my own defined list for the cards but for this assignment I have to use the 'get_deck' function. The '?????' in the below code are where I referenced my first card values list.
Here is my code:
def get_deck():
deck = [value + suit for value in '23456789TJQKA' for suit in 'SHDC']
random.shuffle(deck)
return iter(deck)
while True:
get_deck()
player1 = []
player2 = []
player3 = []
player4 = []
house = []
player1.append(random.choice(?????))
player2.append(random.choice(?????))
player3.append(random.choice(?????))
player4.append(random.choice(?????))
house.append(random.choice(?????))
player1_bust = False
player2_bust = False
player3_bust = False
player4_bust = False
house_bust = False
if number_players[0] == 1:
player1_total = total(player1)
while True:
player1_total = total(player1)
print "Player 1 has these cards %s with a total value of %d." % (player1, player1_total)
if player1_total > 21:
print "Bust!"
player1_bust = True
break
elif player1_total == 21:
print "Blackjack!"
break
else:
hit_stand = raw_input("Hit or Stand? (h or s): ").lower()
if 'h' in hit_stand:
player1.append(random.choice(?????))
else:
break
I hope this makes sense! Thanks in advance.
Using Python 2.7
The get_deck function is already randomly shuffling the deck for you. You don't need to get random elements from its list, because it's already randomized. Just get the next element from the iterator that get_deck returns.
https://docs.python.org/2/library/stdtypes.html#iterator-types