why the assign() function does not change the string into integer?
the assign function does not return the values i set in if statement!
p1 = raw_input("Player 1 ?")
p2 = raw_input("Player 2 ?")
def assign(n):
if n == "r":
return (1)
elif n == "s":
n = 2
elif n == "p":
n = 3
else:
print "Wrong input!"
return n
assign(p1)
assign(p2)
print p1
print p2
if p1 - p2 == 0:
print "Tie!"
elif (p1 - p2) / 2 != 0:
print " Player 1 is winner!"
else:
print" Player 2 is the winner!"
The variable n inside the function is distinct from the expression (or variable) supplied as an argument. As such, assigning to n inside the function will not affect any of the variables outside. (This is because Python is not Call By Reference.)
Instead, use the return value, eg.
def classifyInput(n):
if n == "r":
return 1
elif n == "s":
return 2
elif n == "p":
return 3
else:
print "Wrong input!"
# implicit: return None
p1_inp = raw_input("Player 1 ?")
p1 = classifyInput(p1_inp)
Related
I am writing a program were add and subtract numbers from an integer to keep score. The admin and subtracting is working but I am trying to add a feature that if you add number after the word add or subtract it changes by that number, but I can’t get that to work.
cont = True
score = 0
num = False
while cont == True:
q = input("add, subtract, or end: ")
for char in q:
n = q.isnumeric()
if n == True:
num = True
num2 = q
if num == False:
if q.lower() == "add":
score += 1
elif q.lower() == "subtract" or q.lower() == "sub":
score -= 1
elif q.lower() == "end":
cont = False
print(score)
elif num == True:
if "add" in q.lower():
score += num2
elif "subtract" in q.lower() or "sub" in q.lower():
score -= num2
elif q.lower() == "end":
cont = False
print(score)
I expect it to add one if you type add subtract one if you type sub or subtract and end the program if you type end, that works the part that I expected and doesn’t work is that it is supposed to detect if there is a number in the string using the isnumeric() function and add or subtract that number.
Your code simplifies neatly to something like:
score = 0
while True: # Infinite loop; we'll use `break` to end
print("Score:", score)
q = input("add, subtract, or end: ").lower().strip() # lower-case, remove whitespace
words = q.split() # Split entry by spaces
verb = words.pop(0) # Remove first word
if verb == "end":
break
if words and words[0].isnumeric(): # If there is a second word and it's numeric
value = int(words[0])
else: # Otherwise default to 1
value = 1
if verb == "add":
score += value
elif verb == "subtract":
score -= value
else:
print("Unknown verb", verb)
I'm a beginner and I can't figure out why I can't get the output I
want. It's a craps game. It's suppose to go like:
How many games do you want to play > 6 You rolled 5 + 2 = 7 You
win
What I got is something like: You rolled 1 + 6 = 7 You rolled 1 + 6 =
7 You rolled 1 + 6 = 7 You lose
import random
def rollDice():
roll_1 = random.randint(1,7)
roll_2 = random.randint(1,7)
return roll_1, roll_2
def determine_win_or_lose(dice1,dice2):
sum = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", sum )
if sum == '2' or '3' or '12':
return 0
elif sum == '7' or '11':
return 1
else:
print("Point is", sum)
determinePointValueResult(sum)
if determinePointValueResult(sum) == 1:
return 1
elif determinePointValueResult(sum) == 0:
return 0
def determinePointValueResult(sum):
point = sum
while sum != 7 and sum != point:
x, y = rollDice()
sum = x + y
if sum == point:
return 1
elif sum == '7':
return 0
print("You rolled", x, "+", y, "=", sum )
#==== MAIN =====
win = 0
lose = 0
game = int(input("How many games do you want to play > "))
for i in range(game):
x, y = rollDice()
determine_win_or_lose(x, y)
if determine_win_or_lose(x, y) == 1:
print("You win")
win = win + 1
elif determine_win_or_lose(x, y) == 0:
print("You lose")
lose = lose + 1
print("Game results: ", win, "wins and", lose, "losses")
Your issue come from the main, because you call the determine_win_or_lose function 3 times, the first one before the if (and i'm not sure why since you do nothing with it), a second time to check the condition of the if and a third time to check the condition of the elif.
Since it's this function that print the message, and you call the function 33 times each iteration of the for loop, it's normal to get the message printed 3 times.
(
Also since the determine_win_or_lose will always return 0 or 1 you don't really need an elif you can just do an if/else to achieve the same thing and simplify your code a bit.
)
So i'd suggest the following :
#==== MAIN =====
win = 0
lose = 0
game = int(input("How many games do you want to play > "))
for i in range(game):
x, y = rollDice()
result = determine_win_or_lose(x, y)
if result == 1:
print("You win")
win = win + 1
else:
print("You lose")
lose = lose + 1
print("Game results: ", win, "wins and", lose, "losses")
Obvious issues:
You call determine_win_or_lose too many times in your for loop. Change it to:
for i in range(game):
x, y = rollDice()
result = determine_win_or_lose(x, y)
if result == 1:
print("You win")
win = win + 1
elif result == 0:
print("You lose")
lose = lose + 1
Your check in determine_win_or_lose is incorrect. It should be something like:
def determine_win_or_lose(dice1,dice2):
sum = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", sum )
if sum == 2 or sum == 3 or sum == 12:
return 0
elif sum == 7 or sum == 11:
return 1
else:
print("Point is", sum)
determinePointValueResult(sum)
if determinePointValueResult(sum) == 1:
return 1
elif determinePointValueResult(sum) == 0:
return 0
In determinePointValueResult you shouldn't compare sum to a string, but an integer:
def determinePointValueResult(sum):
point = sum
while sum != 7 and sum != point:
x, y = rollDice()
sum = x + y
if sum == point:
return 1
elif sum == 7:
return 0
print("You rolled", x, "+", y, "=", sum )
It's possible that determine_win_or_lose and determinePointValueResult are returning None. You may need to change your elifs to elses or create a new else case.
I am learning functions in Python and was asked to make a script that takes two inputed values and does some math function on them. I wrote the code below but keep getting the error message that on line 17 where I try to print the answer, 'result' is not defined. I dont understand this as I feel like I am defining 'result' within each function. Clearly I am missing some basic concept related to functions and returned values. Any help would be appreciated.
def sum(a,b):
result = a + b
return result
def times(a,b):
result = a * b
return result
def divide(a,b):
result = a / b
return result
def subtract(a,b):
result = a / b
return result
print "Answer is %d" % result
def start():
print "This program can perfom a math function of any two numbers"
a = int(raw_input("Enter first number: "))
b = int(raw_input("Enter second number: "))
c = raw_input("Enter math function you want: ")
if c == "+":
sum(a,b)
elif c == "x":
times(a,b)
elif c == "/":
divide(a,b)
elif c == "-":
subtract(a,b)
else:
print "you didnt enter a function!"
start()
Here is the error:
File "defPrac2.py", line 17, in
print "Answer is %d" % result
See the problem is you are not returning anything from the start function ,
again Python follows a indentation level i.e anything written on the first level (line with no space will be executed first ),
remove the line print line from the top and modify the start function to return the value :
def start():
print "This program can perfom a math function of any two numbers"
a = int(raw_input("Enter first number: "))
b = int(raw_input("Enter second number: "))
c = raw_input("Enter math function you want: ")
res = -1
if c == "+":
res = sum(a,b)
elif c == "x":
res = times(a,b)
elif c == "/":
res = divide(a,b)
elif c == "-":
res = subtract(a,b)
else:
print "you didnt enter a function!"
return res
result = start()
# use format instead of access specifier as it may give you error if
# not handling the specific type case format is more generic
print "Answer is {0}".format(result)
Happy coding :)
Try this, when you have return values, either you can put that value in a new variable and then print or directly print in in the print statement.
`
def sum(a,b):
result = a + b
return result
def times(a,b):
result = a * b
return result
def divide(a,b):
result = a / b
return result
def subtract(a,b):
result = a / b
return result
def start():
print "This program can perfom a math function of any two numbers"
a = int(raw_input("Enter first number: "))
b = int(raw_input("Enter second number: "))
c = raw_input("Enter math function you want: ")
if c == "+":
print("The answer is "+sum(a,b))
elif c == "x":
print("The answer is "+times(a,b))
elif c == "/":
print("The answer is "+divide(a,b))
elif c == "-":
print("The answer is "+subtract(a,b))
else:
print "you didnt enter a function!"
start()
`
I have made a logic gate that takes in two inputs which will then feed through into a AND gate in this case. For example the user will enter 0 and 0 then the AND gate will process as 0.
The problem here is when we use the IF statement to determine our two inputs, they are not recognised otherwise everything else in the program to process the two inputs along with a temporary storage for the output.
A = input("Enter a value of 1 or 0: ")
B = input("Enter a value of 1 or 0: ")
print(A)
print(B)
So the part above I am able to enter the inputs and create a storage for it.
The program tells me that A and B are unrecognised so does anyone know what I am doing wrong here?
this is where the problem takes place: everything from here to the else statement is ignored.
def first_AND ():
if A == 0 and B == 0:
AND_1()
print(AND)
print("Now solve the XOR gate")
gate_path_A()
elif A == 1 and B == 0:
AND_2()
print(AND)
print("Now solve the XOR gate")
gate_path_A()
elif A == 0 and B == 1:
AND_3()
print(AND)
print("Now solve the XOR gate")
gate_path_A()
elif A == 1 and B == 1:
AND_4()
print(AND)
print("Now solve the XOR gate")
gate_path_A()
else:
print("Error")
it skips all my elif statements and just prints an error.
def AND_1():
print(A & " AND " & B & " = 0")
AND = 0
def AND_2():
print(A & " AND " & B & " = 0")
AND = 0
def AND_3():
print(A & " AND " & B & " = 0")
AND = 0
def AND_4():
print(A & " AND " & B & " = 1")
AND = 1
I cleaned up your code for you: you should read up on python syntax, f.e. https://docs.python.org/2/reference/index.html (for 2.7.x) and do some tutorials
# define global
AND = None
#define the used functions
def gate_path_A():
print("Reached gate_path_A()")
return
def first_AND (A,B):
if A == 0 and B == 0:
AND_1(A,B)
print(AND)
print("Now solve the XOR gate")
gate_path_A()
elif A == 1 and B == 0:
AND_2(A,B)
print(AND)
print("Now solve the XOR gate")
gate_path_A()
elif A == 0 and B == 1:
AND_3(A,B)
print(AND)
print("Now solve the XOR gate")
gate_path_A()
elif A == 1 and B == 1:
AND_4(A,B)
print(AND)
print("Now solve the XOR gate")
gate_path_A()
else:
print("Error")
return
def AND_1(A,B):
print(A , " AND " , B , " = 0")
AND = 0
return
def AND_2(A,B):
print(A , " AND " , B ," = 0")
AND = 0
return
def AND_3(A,B):
print(A , " AND " , B , " = 0")
AND = 0
return
def AND_4(A,B):
print(A , " AND " , B , " = 1")
AND = 1
return
MAIN Program
# get one integer from user
a = None
while a is None:
try:
a = int(input("Enter a number: "))
except ValueError:
print("Not an integer value...")
print(str(a));
# get second integer from user
# you should really put this in a def and return the integer: DRY principle
b = None
while b is None:
try:
b = int(input("Enter a number: "))
except ValueError:
print("Not an integer value...")
print(str(b));
# call to the first and thing and supply the params your got from user
first_AND(a,b);
I am making a Tic Tac Toe game and can't assign the sign of player/computer to 2d list.
array = []
player_choice = 0
computer_choice = 0
player_move_col = 0
player_move_row = 0
def starting_array(start_arr):
for arrays in range(0, 3):
start_arr.append('-' * 3)
def print_array(printed_arr):
print printed_arr[0][0], printed_arr[0][1], printed_arr[0][2]
print printed_arr[1][0], printed_arr[1][1], printed_arr[1][2]
print printed_arr[2][0], printed_arr[2][1], printed_arr[2][2]
def player_sign():
choice = raw_input("Do you want to be X or O?: ").lower()
while choice != 'x' and choice != 'o':
print "Error!\nWrong input!"
choice = raw_input("Do you want to be X or O?: ").lower()
if choice == 'x':
print "X is yours!"
return 2
elif choice == 'o':
print "You've chosen O!"
return 1
else:
print "Error!\n Wrong input!"
return None, None
def player_move(pl_array, choice, x, y): # needs played array, player's sign and our col and row
while True:
try:
x = int(raw_input("Which place do you choose?: ")) - 1
y = int(raw_input("What is the row? ")) - 1
except ValueError or 0 > x > 2 or 0 > y > 2:
print("Sorry, I didn't understand that.")
# The loop in that case starts over
continue
else:
break
if choice == 2:
pl_array[x][y] = 'X'
elif choice == 1:
pl_array[x][y] = "O"
else:
print "Choice didn't work"
return pl_array, x, y
starting_array(array)
print_array(array)
# print player_choice, computer_choice - debugging
player_move(array, player_sign(), player_move_col, player_move_row)
print_array(array)
It gives me an error :
pl_array[x][y] = "O"
TypeError: 'str' object does not support item assignment
How can i change the code to make it change the item I show the program to write "X" or "O" in it?
Just like the error says, 'str' object does not support item assignement, that is you cannot do:
ga = "---"
ga[0] = "X"
But you can use lists in your example by changing:
start_arr.append('-' * 3)
to
start_arr.append(["-"] * 3)