Josh Zylstra
Josh Zylstra

Reputation: 13

How do I make a while loop store consecutive variables each time it's run?

I'm new to Stack Overflow and Python. I'm trying to make a kind of translation program, I'm sure there is an easier way than what I'm doing, but hey that's part of learning. So basically the user inputs the letter, then the answer is translated, and printed. But I'd rather store it instead of print it, so that I can print the answer altogether at the end if that makes sense.

`a = "b"
While True:
  i = input()
  if I_1 = a:
    L_1="a"
  if I_1 = b:
    L_1 = "b"`

etc.. So i want L_1 to be stored each time, as L_1, L_2 etc so at the end i can say

`print(L_1 + L_2)`

and so on.

I know I've probably used bad conventions but hopefully it's clear enough to understand. Thanks.

Upvotes: 1

Views: 227

Answers (5)

gmds
gmds

Reputation: 19885

It is possible to do it that way (programmatic generation of variables), but it's generally considered very bad form, because it makes it difficult to reason about which variables refer to what in your program.

Instead, consider using a dict. Like a list, it is a container, but unlike a list, you access its elements with keys, which can be, in particular, strings. This is very helpful for your usecase since you can put the results of translation in the dict and access them with the original characters/words/phrases.

You also need ways to note input that isn't recognised and to end the loop (since you use an infinite loop in while True).

Lastly, after you're done, you have a list. Since, presumably, you want to concatenate its contents back into a sentence, you can use string.join, which combines the contents of the list with string in between (here '' is used, so there will be nothing between each element of the list in the final string)

For example:

translation_mapping = {'you': '你', 
                       'are': '是', 
                       'human': '人类'}
result = []

while True:
    input_string = input()
    if input_string == '_END':
        break

    try:
        result.append(translation_mapping[input_string])

    except KeyError:
        # input_string was not found in the translation mapping
        print(f"I didn't understand {input_string}. Please try again.")

print(''.join(result))

Output:

>>> you
>>> are
>>> a
I didn't understand a. Please try again.
>>> human
>>> _END
你是人类

Upvotes: 1

Andrew Guy
Andrew Guy

Reputation: 9968

Fixing some of the Python code (equality operators etc), and adding an exit condition for the loop (user input starts with 0). This is not necessarily the best way of handling user input, but I wanted to keep it vaguely similar to the original code.

You want to create an empty list to store results, and append to that in each loop.

output_data = []
while True:
   i = input()
   if i[0] == "a":
       output_data.append("b")
   if i[0] == "b":
       output_data.append("a")
   if i[0] == "0":
       break
print(output_data)

Upvotes: 0

vijay
vijay

Reputation: 187

print('Enter the number of letters')
n = input()
word=[]

i=0;
while(i<n):
    word.append(input())
    i+=1

Upvotes: 0

Kartikeya Sharma
Kartikeya Sharma

Reputation: 1383

You can do it with the help of a list, which is a python built-in array like data structure. You can append the result to it everytime. You can break the while loop by typing a certain string or character etc. Again you need to correct your operators, while loop (W is capital).

At the end to print it, you can use join which returns a string in which the elements of sequence have been joined by str separator. More about it here: https://www.geeksforgeeks.org/join-function-python/

a="b"
b="a"
lis=[]
while True:
  i = input()
  if i == a:
    lis.append("a")
  if i == b:
    lis.append("b")
  if i=="exit":
      break

print("".join(lis))

Good Luck!

Upvotes: 0

alex067
alex067

Reputation: 3281

You are looking for a data structure.

If the user is entering just a letter, a list should be enough and do the job.

There are 2 issues with your program that we have to address.

1) Wrong equality operator.

You are using the equal operator instead of the == comparison operator. Which results in every condition being true, because you are setting a variable's value to be that value.

2) Wrong scoping.

Your variables L_1 and L_2 are being scoped only to the if/else conditional operator, and not to the function itself. Make sure you declare variables outside of your loop, so you can use them again when the loop is finished.

Upvotes: 0

Related Questions