1

I have a basic Python encryption program. The program is pretty much done, but I keep getting errors because of the way Python is building my variable.

Here is an example of what I am trying to do:

A = 4
B = 2
C = 3

for i in range (3):
     A=A, ((B*2) + C)

A = (((4, 7), 7), 7)

I want A to output 4, 7, 7, 7 and as it loops, it adds numbers onto the end instead of adding them together. The issue here is that for whatever reason, I can't target specific values, for example, if I did

print (A[2])

The output would be an error

Traceback (most recent call last):
  File "C:/Users/name/Desktop/Python/Test.py", line 8, in <module>
    print (A[2])
IndexError: tuple index out of range

Ignoring the above code, what is the best way I could do this? Thanks!

7
  • Are you trying to sum the numbers or concatenate them? Commented Dec 7, 2016 at 17:17
  • What is your expected output? Commented Dec 7, 2016 at 17:18
  • I'm trying to concatenate them. Commented Dec 7, 2016 at 17:18
  • I want A to output 4, 7, 7, 7 Commented Dec 7, 2016 at 17:19
  • So in essence, you want A to be a list and append to it in each loop? Commented Dec 7, 2016 at 17:19

2 Answers 2

1

Did you mean this,

A = 4
B = 2
C = 3

l = [A]
for i in range (3):
    l.extend([B*2 + C])

print(l)
# [4, 7, 7, 7]
Sign up to request clarification or add additional context in comments.

2 Comments

Yes. Thank you, some how I forgot I could use and append a list. Will mark is as answered when I can. :)
@Spookichicken, you can do that any time.
0

If you want to keep using a tuple you can do it like this:

A = 4
B = 2
C = 3

A = (A,) # Convert A to tuple
for i in range(3):
     A += ((B*2) + C,)

print(A)
# (4, 7, 7, 7)

Note: tuples are immutable, which means you are creating a new tuple in each iteration, this can be an expensive operation if the loop is very big.

Comments

Your Answer

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.