Reputation: 13
I'm trying to check 4 separate variables for the exact same strings using separate variables with similar names. An example is below. The print functions are also an example, they're not my final goal.
from random import randint
example1 = randint(1,3)
example2 = randint(1,3)
example3 = randint(1,3)
example4 = randint(1,3)
if example1 == 1:
print ("A")
elif example1 == 2:
print ("C")
else:
print ("M")
Can anyone suggest how I could repeat this area for all of the variables?
if example1 == 1:
print ("A")
elif example1 == 2:
print ("C")
else:
print ("M")
Upvotes: 1
Views: 78
Reputation: 10624
A more scalable approach to your problem:
from random import randint
example1 = randint(1,3)
example2 = randint(1,3)
example3 = randint(1,3)
example4 = randint(1,3)
int_char_map = {1: "A", 2: "C", 3: "M"}
examples = [example1, example2, example2, example4]
print(examples)
for example in examples:
print(int_char_map[example])
Upvotes: 0
Reputation: 4606
Remove str
from randint(str(1,3))
l = [example1, example2, example2, example4]
for i in l:
if i == 1:
print ("A")
elif i == 2:
print ("C")
else:
print ("M")
or
[print('A') if i == 1 else print('C') if i ==2 else print('M') for i in l]
C C C A
Upvotes: 2
Reputation: 6227
You can use a for loop:
from random import randint
example1 = randint(1,3)
example2 = randint(1,3)
example3 = randint(1,3)
example4 = randint(1,3)
for example in (example1, example2, example3, example4):
if example == 1:
print ("A")
elif example == 2:
print ("C")
else:
print ("M")
The (example1, example2, example3, example4)
part creates a tuple containing all of the four variables. The for example in ...
part then repeats your desired code for each variable, with the example
variable taking on the value of each different variable each time round the loop.
For more on for loops, you can take a look at the official tutorial.
Upvotes: 0