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)
Related
I am learning Python functions and loops; however, I am running in to an error when trying to calculate two variables assigned to an integer within a loop, I post my code below as well as a draw.io diagram so better explain what I am trying to accomplish:
in the included image the green represents a working loop, or function and the red represent a broken loop or function, the white represents not yet coded
in the included code, the loops work on input option m and l, however the loop does not work on option q. the q option will also not work with additions with the w,e and r options.
P.S I have coded nothing in the w, e, r or y options yet (as you can see) however I have assigned integers to the q,w,e and r variables.
q = 1
w = 2
e = 3
r = 4
def exitprogram():
print ("exiting...")
def q_function():
Q_loop = True
while Q_loop:
print("Q function selected, select addition - press k to go back or x to exit")
print("")
Q_addition = int(input("Add Q with "))
#exit program
if Q_addition =="x":
exitprogram()
break
#additions
elif Q_addition == "w":
q_w = q+w
print(q_w)
if Q_addition == "k":
start()
#invalid input
else:
print("invalid input - try again")
continue
def w_function():
print("W function operational")
W_addition = int(input("Add W with - to exit select x "))
def e_function():
print("E function operational")
E_addition = int(input("Add E with - to exit select x "))
def r_function():
print("R function operational")
R_addition = int(input("Add R with - to exit select x "))
def t_function():
T_loop = True
while T_loop:
T_selection = input("T function operational - press k to go back or x to exit ")
if T_selection == "k":
more()
elif T_selection == "x":
exitprogram()
break
else:
print("invalid input - try again")
continue
def y_function():
print("Y function operational")
def more():
moreloop = True
while moreloop:
l = input ("select t or y - to go back select k to exit select x ")
if l =="t":
t_function()
break
if l =="y":
y_function()
break
if l =="x":
exitprogram()
break
elif l =="k":
start()
else:
print("invalid input - try again")
continue
def start():
loop1 = True
while loop1:
a = input("select q, w, e or y - for more options select m or to exit select x ")
if a == "x":
exitprogram()
break
elif a == "q":
q_function()
break
elif a == "w":
w_function()
break
elif a == "e":
e_function()
break
elif a == "r":
r_function()
break
elif a =="m":
more()
break
else:
print("invalid input - try again")
continue
start()
Error traceback included below
Traceback (most recent call last):
File "x:/xxx/xxx/xxxx/xxxx.xx", line 115, in <module>
start()
File "x:/xxx/xxx/xxxx/xxxx.xx", line 95, in start
q_function()
File "x:/xxx/xxx/xxxx/xxxx.xx"", line 16, in q_function
Q_addition = int(input("Add Q with "))
ValueError: invalid literal for int() with base 10: 'w'
You have Q_addition = int(input("Add Q with ")) so are attempting to cast the input (x, k, e, etc) to an int. This throws the error. Also your logic checks for strings not int
#exit program
if Q_addition =="x":
Q_loop = False #set the loop variable to false to exit the loop and return to main function
#changed to elif as Q_addition can only be one option
elif Q_addition =="x":
...
elif Q_addition == "w":
#if you'd like addition with the other variables need to add them
elif Q_addition == "e":
q_e = q+e
print(q_e)
elif Q_addition == "r":
q_r = q+r
print(q_r)
...
#changed to elif, see above
elif Q_addition == "k":
remove the int() cast so Q_addition = input("Add Q with ")
I am a beginner in python and I got a task to make a game of guesses using python. In my assignment, I was told to count the number of tries. But I can't make it work. Any suggestion would be appreciated. (note: the list is for nothing...I was just messing with the code and trying things.)
`
# import random
# a=random.randint(1,30)
a = 23
Dict1 = ["Hello there! How are you?", 0,
"Guess a number Between 1 to 50",
"Your number is too high",
"Your Number is too low",
"Make Your Number A Bit Higher",
"Make Your Number a Bit Lower",
"Congratulations You Have guessed the right number :)"
]
print(Dict1[0])
name = input("What is your Name?\n=")
# print("hi!,{}, Wanna Play a game?".format(name))
print(Dict1[2])
while 1:
inp = float(input("="))
if inp > 50:
print(Dict1[3])
continue
elif inp < 1:
print(Dict1[4])
continue
elif inp < a:
print(Dict1[5])
continue
elif inp > a:
print(Dict1[6])
continue
elif inp == a:
print(Dict1[7])
q = input("Do You Want to Go again? Y or N\n=")
if q.capitalize() == "Y":
print('You have', 5 - 4, "tries left")
print(Dict1[2])
continue
elif q.capitalize() == "N":
break
else:
break
op = inp
while 1:
x = 4
if -137247284234 <= inp <= 25377642:
x = x + 1
print('You have', 5 - x, "tries left")
if x == 5:
break
if x == 5:
print("Game Over")
`
One way to go about it would be to set up a variable to track attempts outside the while loop between a and Dict1
a = 23
attempts = 1
Dict1 = [...]
Then each time they make an attempt, increment in the while loop:
if inp > 50:
print(Dict1[3])
attempts += 1
continue
elif inp < 1:
print(Dict1[4])
attempts += 1
continue
elif inp < a:
print(Dict1[5])
attempts += 1
continue
elif inp > a:
print(Dict1[6])
attempts += 1
continue
EDIT:
Looking more carefully at your code, it seems like you want a countdown. So you could change it to
attempts = 5
and in the while loop
while 1:
...
if q.capitalize() == "Y":
attempts -= 1
print('You have', attempts, "tries left")
print(Dict1[2])
continue
I wanted to add a confirmation for my code so that the user will be able to change their input. I haven't yet added the loop for the question but for some reason when I run this it fails to run def calc() and therefore the calculations I created cannot continue. Help!!
n=0
x=0
while True:
numbers = input("Please enter a, b,c, or, d to select a equation")
if numbers == "a":
n =3
x = 2
break
elif numbers =="b":
n = 4
x = 5
break
elif numbers == "c":
n=5
x=6
break
elif numbers == "d":
n=6
x=7
break
else:
print("Please enter a,b,c, or d")
w = float(input("Please enter weight"))
choice = input("Is this your answer?")
if choice == "yes":
def calc():
if n > w :
weight = (x - w)
weight2 = weight/n
print(weight)
elif w < x:
weight = (w - x)
weight2 = weight/n
print(weight)
calc()
elif choice =="no":
print ("Lets change it")
else:
print("Please respond with 'yes' or 'no'")
In Python 3.2, I'm writing up a basic menu program, and when the option to quit is entered, the function is not ending.
When quit is chosen, it ends the loop the rest of the script is in, and should terminate the script, but it isn't, for whatever reason?
Am I missing an 'end' function that kills the script, or is the new Python Shell just buggy?
Pretty sure this wasn't necessary in Python 2.7.
import random
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate blah\n(Q)uit\n>>>"))
while choice != "q" or choice != "Q":
while choice != "i" and choice != "I" and choice != "c" and choice != "C" and choice != "q" and choice != "Q":
print("Invalid menu choice.")
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate blah\n(Q)uit\n>>>"))
if choice == "i" or choice == "I":
print("blahblah.")
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate blah\n(Q)uit\n>>>"))
if choice == "c" or choice == "C":
x = int(input("Please enter the number of x: "))
while x < 0:
x = int(input("Please enter the number of x: "))
y = int(input("Please enter the number of y: "))
while y < 0:
y = int(input("Please enter the number of y: "))
z = str(input("blah (B) or (P) z?: "))
while z != "b" and z != "p" and z != "B" and z != "P":
z = str(input("blah (B) or (P) z?: "))
if z == "b" or z == "B":
total = x*10 + y*6 + 0
print("blah $", total, " blah ", x, " x and ", y, " y. blah!")
#function that outputs the cost of premium z
if z == "p" or z == "P":
luck = random.randrange(1, 11, 1)
if luck == 10:
total = x*10 + y*6
print("\nblah$", total, " blah z for ", x, " x and ", y, " y. blah!")
#below is the normal function, for when the customer is not a lucky winner
if luck != 10:
total = x*12.50 + y*7.50
print("blah $", total, " blah ", x, " x and ", y, " y. blah!")
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate\n(Q)uit\n>>>"))
Your condition is wrong:
while choice != "q" or choice != "Q": # this should be "and"!
always returns True, creating an infinite loop.
Also, you've got quite a convoluted bit of logic here. This can be simplified a lot:
import random
while True:
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate blah\n(Q)uit\n>>>")).lower()
if choice == "i":
print("blahblah.")
continue
elif choice == "q":
break
elif choice == "c":
while True:
x = int(input("Please enter the number of x: "))
if x >= 0: break
while True:
y = int(input("Please enter the number of y: "))
if y >= 0: break
while True:
z = str(input("blah (B) or (P) z?: ")).lower()
if z in "bp": break
if z == "b":
total = x*10 + y*6 + 0
print("blah $", total, " blah ", x, " x and ", y, " y. blah!")
#function that outputs the cost of premium z
else: # z must be "p"
luck = random.randrange(1, 11, 1)
if luck == 10:
total = x*10 + y*6
print("\nblah$", total, " blah z for ", x, " x and ", y, " y. blah!")
#below is the normal function, for when the customer is not a lucky winner
if luck != 10:
total = x*12.50 + y*7.50
print("blah $", total, " blah ", x, " x and ", y, " y. blah!")
else:
print("Invalid menu choice.")
continue
One way to perform quit operations in Python is to throw a custom exception and catch that exception explicitly. Please correct me if I am wrong, AFAIK this doesn't put a big over-head on your python program. It could done as simple as the what I show below:
...
class QuitException(Exception);
...
def MyMenuProgram():
...
...
...
if __name__ == '__main__':
try:
MyMenuProgram()
catch QuitException:
pass
catch Exception, e:
raise
As #Tim answered, your loop condition is wrong.
while choice != "q" or choice != "Q":
Let's take a look at this, logically:
if choice == "q", choice != "Q", loop condition evaluates to false or true, which is true
if choice == "Q", choice != "q", loop condition evaluates to true or false, which is true
if choice != "q" or "Q", loop condition evaluates to true or true, which is true
You need to change this loop condition to:
while choice != "q" and choice != "Q":
or
while choice.lower() != "q":
Edit: Redacted - input() is indeed the way to get user input in Py3k. Another of the glorious differences between Python 2.7 and Python 3.2.
I am new to Python and I do not know why but the if, elif in the following code is not working as I expect it to. However,
It works perfectly when I type 1 to 7
it works perfectly when I type 0 8 or 9 (it says "Try again")
It does not work if I type 10 to 69, 100 to any number
When I say it does not work I mean it prints
my_shape_num = h_m.how_many()
But I do not know why. It has to stop if choice is not between 1 and 7
def main(): # Display the main menu
while True:
print
print " Draw a Shape"
print " ============"
print
print " 1 - Draw a triangle"
print " 2 - Draw a square"
print " 3 - Draw a rectangle"
print " 4 - Draw a pentagon"
print " 5 - Draw a hexagon"
print " 6 - Draw an octagon"
print " 7 - Draw a circle"
print
print " X - Exit"
print
choice = raw_input(' Enter your choice: ')
if (choice == 'x') or (choice == 'X'):
break
elif (choice >= '1' and choice <= '7'):
my_shape_num = h_m.how_many()
if ( my_shape_num is None):
continue
d_s.start_point() # start point on screen
if choice == '1':
d_s.draw_triangle(my_shape_num)
elif choice == '2':
d_s.draw_square(my_shape_num)
elif choice == '3':
d_s.draw_rectangle(my_shape_num)
elif choice == '4':
d_s.draw_pentagon(my_shape_num)
elif choice == '5':
d_s.draw_hexagon(my_shape_num)
elif choice == '6':
d_s.draw_octagon(my_shape_num)
elif choice == '7':
d_s.draw_circle(my_shape_num)
else:
print
print ' Try again'
print
Edit: Ok, sorted:
choice = raw_input(' Enter your choice: ')
if (choice == 'x') or (choice == 'X'):
break
try:
choice = int(choice)
if (1 <= choice <= 7):
my_shape_num = h_m.how_many()
if ( my_shape_num is None):
continue
d_s.start_point() # start point on screen
if choice == 1:
d_s.draw_triangle(my_shape_num)
elif choice == 2:
d_s.draw_square(my_shape_num)
elif choice == 3:
d_s.draw_rectangle(my_shape_num)
elif choice == 4:
d_s.draw_pentagon(my_shape_num)
elif choice == 5:
d_s.draw_hexagon(my_shape_num)
elif choice == 6:
d_s.draw_octagon(my_shape_num)
elif choice == 7:
d_s.draw_circle(my_shape_num)
else:
print
print ' Number must be from 1 to 7!'
print
except ValueError:
print
print ' Try again'
print
Strings are compared lexicographically: '10' is greater than '1' but less than '7'. Now consider this code:
elif (choice >= '1' and choice <= '7'):
In addition to accepting '7', this will accept any string beginning with 1, 2, 3, 4, 5 or 6.
To fix, convert choice to integer as soon as you've tested for 'x', and use integer comparisons thereafter.
'43' < '7' # True
43 < 7 # False
int('43') < int('7') # False
You're comparing strings (text), so the order is like a dictionary. You need to convert them into integers (numbers), so that comparisons put them in counting order.
Then, course, you also need to be prepared for people typing things that aren't numbers:
int('hi') # ValueError
I think it's because you are using string for comparing... try
choice = int(choice)
before if, elif block and change their comparisons to
if choice == 1:
(without quotes)