0

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

asked Jun 30, 2020 at 17:55
1
  • 5
    Your pos is a string and can not be equal to a number. Commented Jun 30, 2020 at 17:59

3 Answers 3

2

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

answered Jun 30, 2020 at 18:01
Sign up to request clarification or add additional context in comments.

Comments

1

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"))
answered Jun 30, 2020 at 17:59

Comments

1

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.

answered Jun 30, 2020 at 17:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.