Python TikTakToe game if statement not working properly - python

So I am writing a python tiktaktoe game as a project. I am required to use multidimensional arrays and have no errors. In the function p_turn() (Which manages the player move), I was going to implement an if statement to check whether the move is valid (between 1 and 3). But now, no matter what number I put in, it still says that the move is invalid.
The desired outcome is for the game not to allow numbers that aren't between 1 and 3.
def p_turn():
system(command='cls')
print_board()
p_play_1 = int(input("Choose a position for the Y between 1 and 3 --> "))
p_play_2 = int(input("Choose a position for the X between 1 and 3 --> "))
if p_play_1 != 1 or p_play_1 != 2 or p_play_1 != 3 or p_play_2 != 1 or p_play_2 != 2 or p_play_2 != 3: # This is whats not working correctly
print("This is not a valid move. The values must be betweeen 1 and 3! ")
time.sleep(3)
p_turn()
if board[p_play_1 - 1][p_play_2 -1] == " ":
board[p_play_1 - 1][p_play_2 - 1] = "X"
system(command='cls')
print_board()
c_turn() # Computer play
elif board[p_play_1 - 1][p_play_2 - 1] == "X" or [p_play_1 - 1][p_play_2 - 1] == "O":
print("Someone already went there! ")
time.sleep(3)
p_turn()
Also, if it's important, this is how I store my board.
board = [[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "]]
def print_board():
print()
print(f"{board[0][0]} | {board[0][1]} | {board[0][2]}")
print("---------")
print(f"{board[1][0]} | {board[1][1]} | {board[1][2]}")
print("---------")
print(f"{board[2][0]} | {board[2][1]} | {board[2][2]}")
print()

Rename p_turn to player_turn. That way you give your function much more meaning. The same applies to c_turn - cumputer_turn is far more clear. In your small example, it doesn't make that big a difference but in larger projects, naming is really important!
p_play_1 and p_play_2 would make much more sense if they were simply named x and y.
Your boundary check is essentially:
if x != 1 or x != 2 or x != 3 or # ... repeat for y
That can't work. The above if condition is evaluated from left to right and terminates as soon as something is True. Take for example x = 2 (which is a valid coordinate). x != 1 evaluates to True and your move is considered invalid.
There are many ways to check whether a variable is within a certain range in Python.
Using comparison operators:
if lower_bound <= value <= upper_bound:
# value is between lower and upper bound
Using range():
if value in range(lower_bound, upper_bound + 1):
# value is between lower and upper bound

You could try something like this:
while not 1 <= (p_play_1 := int(input("Choose a position for the Y between 1 and 3 --> "))) <= 3:
print(f"Invalid Y position: {p_play_1}")
while not 1 <= (p_play_2 := int(input("Choose a position for the X between 1 and 3 --> "))) <= 3:
print(f"Invalid X position: {p_play_2}")

Related

adding to a string based on the number of characters

the problem says to print "that's a really really ... big number" with one "really" for every extra digit that the number has (so 15 would be "that's a really big number", 150 would be "that's a really really big number", 1500 would be "that's a really really really big number", and so on.)
the input is an integer, and the only requirements listed are that the code should run correctly with any integer, should use a while loop to keep dividing the number by 10 and should use += to add onto the end of a string
x = input(("input an integer: "))
count = len(x)
y = int(x / 10)
countx = count - 1
print("that's a " + count("really") + " big number")
i don't really know what i did, but i can tell it's not correct
Try this one. Uses while loop to divide number by 10 and += to add onto the string. You will need to take a string variable and then append to it as count increases. Loop will run until number >= 10 as conditions you mentioned.
x = int(input(("input an integer: ")))
str=""
while x>=10:
x=x//10
str+="really "
print("that's a " + str + "big number")
Added the while loop as you stated in your question
strVar = ""
y = 0
length = 0
cnt = 0
finished = False
num = input("Type a number: ")
while not finished:
y = int(num)//10
length = int(len(str(y)))
if length <= cnt:
finished = True
else:
strVar += " really"
cnt += 1
print("That's a" + strVar + " big number!")
Give this a try. It finds how many trailing zeroes there are in a given number and based on that creates a certain amount of really's.
x = input(("input an integer: "))
count = int(len(x) - len(x.rstrip('0')))
if count == 0:count = 1
really = "really "*count
print(f"that's a {really} big number")
Try this
x = int(input("enter an integer"))
print("that's a " + 'really '*(len(str(x))-1) + " big number")
If you want to correct your function use this
x = input(("input an integer: "))
count = len(x)
y = int(x) / 10
countx = count - 1
print("that's a " + countx*" really" + " big number")

How do I assign a boolean from second block of code to the first block of indentation in python?

When I assign the out_of_marks_limit = True in 5th block, I want the first block of if statement to be "True" and I don't want the code to loop or ask the user anymore.
In other programming language indentation is used to make the program look good. But because python only checks the condition of first block to the same indent, I can't assign boolean of 2 block of code to the first block.
This is what I'm trying to say.
I'm an intermediate level programmer and this program is just for practice purpose.
a = int(input("Enter no. of subjects: "))
count = 1
d = 0
out_of_marks_limit = False #I want the out_of_limit to be True
if a <= 10:
if not out_of_marks_limit:
if count <= a:
for c in range(a):
b = float(input("Enter mark of subject " + str(count) + ": "))
if b <= 100: #If this condition went false then it will skip to else statement
d += b
count += 1
if count > a:
cal = round(d/a, 2)
print("Your percentage is " + str(cal) + "%")
else:
out_of_marks_limit = True #So this boolean value should passed to the first line of code
print("Marks enter for individual subject is above 100")
else:
print("Subject limit exceeded")
I expect the output to print("Marks enter for individual subject is above 100"), if out_of_marks_limit is True and don’t want to loop anymore
I think you can use a while loop to check your out_of_marks_limit condition:
a = int(input("Enter no. of subjects: "))
count = 1
d = 0
out_of_marks_limit = False #I want the out_of_limit to be True
while not out_of_marks_limit:
if a <= 10:
if not out_of_marks_limit:
if count <= a:
for c in range(a):
b = float(input("Enter mark of subject " + str(count) + ": "))
if b <= 100: #If this condition went false then it will skip to else statement
d += b
count += 1
if count > a:
cal = round(d/a, 2)
print("Your percentage is " + str(cal) + "%")
else:
out_of_marks_limit = True #So this boolean value should passed to the first line of code
print("Marks enter for individual subject is above 100")
else:
print("Subject limit exceeded")

python integer values are equal but if statement does nothing

I'm taking a course online to learn python. I am working on a project to code a tic-tac-toe game. I've built this game around a nested list represented by the 3x3 tic-tac-toe grid. Here is the nested list:
grid = [[1,2,3],[4,5,6],[7,8,9]]
I'd like to prompt the user to select a number 1-9 and then replace the selected number in the nested list with either an X or an O depending on which player made the selection.
I can find the value inside the list just fine, and it will print out okay, along with the number that was entered by the user. However, when I try to compare the two values with an if statement, nothing happens. I'd like to just update the nested list value after the if statement but I can't figure out what I'm doing wrong or why the if statement won't fire. I can't get the value to update so I replaced that line with a print statement just to see how it would handle but the line I'm trying to print just gets ignored. Here is the if statement, where p = the number input by the user.
for r in grid:
for c in r:
print str(c) + " / " + str(p) # so I can see the values
if c == p:
print "Winner winner, chicken dinner!"
When I run the code and feed it an integer (in this case 4), I expect to see the chicken dinner line printed out but instead I just get the following:
1 / 4
2 / 4
3 / 4
4 / 4
5 / 4
6 / 4
7 / 4
8 / 4
9 / 4
Why doesn't it recognize that 4 == 4?
UPDATE: I tried sticking the variables in the str() to make sure they were the same type, but I got the same results. Here is the whole code so far:
grid = [['1','2','3'],['4','5','6'],['7','8','9']]
plyr = ("X","O")
turn = 0
def drw_brd():
i = 1
f = turn
for spc in grid:
print " " + spc[0] + " | " + spc[1] + " | " + spc[2] + " "
if i<=2:
print "-----------"
i+=1
print''
print "Player %s (%s's) it's your turn!" %(str(f+1),plyr[turn])
place = input('Cell number to take:')
place_sym(int(place))
check_win()
def check_win():
switch_plyr()
def switch_plyr():
global turn
"""
if turn == 0:
turn = 1
else:
turn = 0
"""
if turn <= 0:
turn = 1
elif turn >= 1:
turn = 0
#print turn
drw_brd()
def place_sym(p):
global turn
global grid
global plyr
print plyr[turn]
for r in grid:
for c in r:
print str(c) + " / " + str(p)
if c == p:
print "Winner winner, chicken dinner!"
The problem is that p is a string, c is an integer. Wherever you are getting your value for p (should look something like)
p = input("enter a number")
you should put
p = int(input("enter a number"))
this should fix your problem
Edit
Not all values were of the same type. Grid defined the numbers as strings,
grid = [['1','2','3'],['4','5','6'],['7','8','9']]
and input was running eval on the entered number, changing its type to an int, which meant the check for p == c returned False, as they were different types

How exactly do I create this Tallying program?

I get this error "TypeError: Can't convert 'int' object to str implicitly"
when I try to run this code. it's on the x += 1 line.
The goal of this program is to receive input such as "RA1" or "R04" and add 1 to the value, which always starts at 0. I then want it to "print" the results when I type END. This is proving to be quite the challenge. Python 3.5.1
x = 0
y = 0
z = 0
print("Enter 3 digit code.")
x = str(input())
while x != "END":
if x == "RA1":
x += 1
continue
elif x == "R04":
y += 1
continue
elif x == "etc":
z += 1
continue
else:
print('Please enter a 3 digit value or END')
There were multiple problems in your code.
The cause of the TypeError was that you unintentionally made x a string by writing x = str(input()) and when you wanted to add 1 to it, Python tried to convert 1 to a string to concatenate it to x.
The infinite loop was unrelated to the TypeError you received. It occurred because of the misplacement of the str(input()) call.
This is the working code with the fixed while loop:
x = 0
y = 0
z = 0
i = ""
print("Enter 3 digit code.")
while i != "END":
i = input()
if i == "RA1":
x += 1
elif i == "R04":
y += 1
elif i == "etc":
z += 1
else:
print('Please enter a 3 digit value or END')
print(str(x) + " " + str(y) + " " + str(z))
You need to cast your integers into strings by wrapping each with str().
Afterwards, use x = raw_input() for your inputs. When you first enter the loop, you need to take an input, but also when you loop back around. So, therefore, you need a way to stop your infinite loop. Hence, x = raw_input() needs to be added at the start of the loop.
You can actually just get your input at the start of the loop, there's no need for 2.
Additionally, your x, y and z should also just be empty strings or null, not 0.
x = ""
y = ""
z = ""
while x != "END":
print("Enter 3 digit code.")
x = raw_input()
if x == "RA1":
x += str(1)
continue
if x == "R04":
y += str(1)
continue
elif x == "etc":
z += str(1)
continue
else:
print('Please enter a 3 digit value or END')

How to count correct answers in python?

I'm VERY new to programming (as in, in an intro class) and python. My assignment is to prompt a user to answer math questions, count the number they got correct/incorrect, calculate/display their numeric grade, and display their letter grade.
Everything seems to be working fine.. except I can't figure out how to get it to count the number of correct/incorrect answers. Any help?
def main():
name = input("What is your name? ")
correct = 0
incorrect = 0
ans = int(input("What is 4 + 5? "))
val = add(4, 5)
if(ans == val):
correct + 1
else:
incorrect + 1
ans2 = int(input("What is 20 * 6? "))
val2 = mult(20, 6)
if(ans2 == val2):
correct + 1
else:
incorrect + 1
ans3 = int(input("What is 14 - 10? "))
val3 = sub(14, 10)
if(ans3 == val3):
correct + 1
else:
incorrect + 1
ans4 = int(input("What is 30 / 5? "))
val4 = div(30, 5)
if(ans4 == val4):
correct + 1
else:
incorrect + 1
ans5 = int(input("What is 29 + 2? "))
val5 = add(29, 2)
if(ans5 == val5):
correct + 1
else:
incorrect + 1
ans6 = int(input("What is 50 - 10? "))
val6= sub(50, 10)
if(ans6 == val6):
correct + 1
else:
incorrect + 1
ans7 = int(input("What is 5 * 11? "))
val7 = mult(5, 11)
if(ans7 == val7):
correct + 1
else:
incorrect + 1
ans8 = int(input("What is 9 / 3? "))
val8 = div(9, 3)
if(ans8 == val8):
correct + 1
else:
incorrect + 1
ans9 = int(input("What is 90 - 5? "))
val9 = sub(90, 5)
if(ans9 == val9):
correct + 1
else:
incorrect + 1
ans10 = int(input("What is 412 + 5? "))
val10 = add(412, 5)
if(ans10 == val10):
correct + 1
else:
incorrect + 1
print()
print("Thanks, " + str(name) + "!")
print()
print("Correct " + str(correct))
print()
print("Incorrect " + str(incorrect))
print()
calcGrade(correct)
def add(value, value2):
return value + value2
def sub(value, value2):
return value - value2
def mult(value, value2):
return value * value2
def div(value, value2):
return value / value2
def calcGrade(correct):
grade = (correct * 100)/ 10
print("Numeric Grade " + str(grade))
if(grade > 90):
letterGrade = "A"
if(grade > 80):
letterGrade = "B"
if(grade < 70):
letterGrade = "C"
if(grade < 69):
letterGrade = "F"
print()
print("Letter Grade " + str(letterGrade))
main()
When you write correct + 1 you are evaluating what correct plus one is equal to, but you aren't updating the value stored in correct.
What you want to put instead is correct = correct + 1. Or, more succinctly, correct += 1.
The same applies to incorrect.
Every programming language has some specific features which you can use for different purposes. In Python, there is this function called eval() which is very useful for your case ...
Here is an example if its use:
In [2]: eval('2*3'), eval('12+13'), eval('30/5')
Out[2]: (6, 25, 6)
Notice that you do the same set of operations many times:
Print a prompt
Input a number
evaluate another number
see of the two numbers are equal
increment respective counters
In Python (or in many other languages), these would be done in a loop. For this, you need to create a list if things you want to loop over. The list will look like this:
In [4]: qns
Out[4]:
['4+5',
'20*6',
'14-10',
'30/5',
'29+2',
'50-10',
'5*11',
'9/3',
'90-5',
'412+5']
At this point, you can use something called list comprehension to get all the results ...
In [5]: [input('what is ' + q + '?') for q in qns ]
what is 4+5?9
what is 20*6?12
what is 14-10?34
what is 30/5?6
what is 29+2?31
what is 50-10?40
what is 5*11?50
what is 9/3?2
what is 90-5?85
what is 412+5?417
Out[5]: [9, 12, 34, 6, 31, 40, 50, 2, 85, 417]
Now you need to compare them with the actual values. You can actually put the comparison within the list comprehension into a single operation.
In [6]: results = [input('what is ' + q + '?') == eval(q) for q in qns ]
what is 4+5?9
what is 20*6?12
what is 14-10?34
what is 30/5?6
what is 29+2?31
what is 50-10?40
what is 5*11?50
what is 9/3?2
what is 90-5?85
what is 412+5?417
In [7]: results
Out[7]: [True, False, False, True, True, True, False, False, True, True]
In Python, it turns out that True == 1 and False == 0 for some cases. Which cases you ask? Well, that's something that comes with experience in something called duck typing. So in a couple of months, with enough experience, you will find the answer to "which cases" almost trivial. Anyway, because of this phenomenon, you can count the right answers as:
In [8]: sum(results)
Out[8]: 6
And the incorrect answers?
In [9]: len(qns) - sum(results)
Out[9]: 4
Cheers, and happy programing!
you have some mistakes with your code. Please try to this. correct +=1 or correct = correct + 1 and incorrect -=1 and incorrect = incorrect - 1
correct = correct + 1
incorrect = incorrect + 1
By doing this, the current value of the correct/incorrect answers is incremented and stored in the same variable, basically, this is a counter, for the number of correct and incorrect answers

Categories