1

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")
4
  • 3
    Please post real code. randint(str(1,3)) gives a TypeError. What exactly are you trying to do there? Commented Sep 26, 2018 at 12:47
  • randint(str(1,3)) will throw an error Commented Sep 26, 2018 at 12:48
  • len({example1,example2,example3,example4}) == 1? Commented Sep 26, 2018 at 12:49
  • As a general rule, when you have "separate variables with similar names" (and similar values and semantic), you really want a list or a dict. Commented Sep 26, 2018 at 13:14

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

@JackTaylor randint(str(1,3)) will thow an error as str can't be passed with more than 1 element
Thanks for the warning - should have tested that bit out first. Fixed now.
Thanks, this is exactly what I needed, just worded differently.
0

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])

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.