If try to change an element inside a globally declared array I get the desired result in this code:
a = [['a','b','c'], ['d','e','f'], ['g','h','i']]
for r in a:
for c in r:
print(c,end = " ")
print()
print()
def changeValue(ch):
a[0][0]=ch
ch=input("Please enter a character\n")
changeValue(ch)
for r in a:
for c in r:
print(c,end = " ")
print()
print()
But in the following code, I don't get the desired result ,i.e, the element at a[0][0] doesn't change
a = [['a','b','c'], ['d','e','f'], ['g','h','i']]
for r in a:
for c in r:
print(c,end = " ")
print()
print()
def enterSymbol(pos,ch):
if pos==1:
a[0][0]=ch
elif pos==2:
a[0][1]=ch
pos=input("Enter a position\n")
enterSymbol(pos,'X')
for r in a:
for c in r:
print(c,end = " ")
print()
Please help
3 Answers 3
The pos in input is always a string. That is why it will not go into the if conditions in enterSymbol (string compared to int).
pos = int(input("Enter a position"))
Replace this with the pos and it should work
Comments
The input function returns a string, not a number:
>>> pos=input("Enter a position\n")
Enter a position
1
>>> pos
'1'
>>>
So this condition:
if pos==1:
is never True.
One way to solve your problem is to change your code to:
pos=int(input("Enter a position\n"))
Comments
Python understands your entry input as a char, not an integer.
You can for example replace your if pos==1: with if pos=='1': and that will work.
posis a string and can not be equal to a number.