-1

I know how to do this using a list or dictionary. Im wondering how to do it with variables and strings. Is there a way to concatenate a string and instead of printing it use it as a command in the code?

import random

#For a number of times user ask a question with a yes or no answer :is it going to be raining tomorrow?
#Code has to return 8 potential answers

answer_1 = "Yes, most def!"
answer_2 = "Pretty much the case"
answer_3 = "I think you are right!"
answer_4 = "Looks like it!"
answer_5 = "Im not so sure about that"
answer_6 = "I dont think so"
answer_7 = "Nah, i woudnt bet on that"
answer_8 = "Impossible!"

def asking_8ball():
    user_question = input("Tell me what is your question human?: ")
    random_answer = random.choice(['1','2','3','4','5','6','7','8'])
    answer = ("answer_" + f"{random_answer}")
    print(answer)

asking_8ball()

This will print something random like answer_1, answer_5, answer_8 etc

But it won't print the content of the variables above. How can I run created commands that are saved as strings and execute them as if they were code?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
dev
  • 651
  • 1
  • 6
  • 14

1 Answers1

-2

I found a way to do it!

import random

#For a number of times user ask a question with a yes or no answer :is it going to be raining tomorrow?
#Code has to return 8 potential answers

answer_1 = "Yes, most def!"
answer_2 = "Pretty much the case"
answer_3 = "I think you are right!"
answer_4 = "Looks like it!"
answer_5 = "Im not so sure about that"
answer_6 = "I dont think so"
answer_7 = "Nah, i woudnt bet on that"
answer_8 = "Impossible!"

def asking_8ball():
    user_question = input("Tell me what is your question human?: ")
    random_answer = random.choice(['1','2','3','4','5','6','7','8'])
    answer = ("answer_" + f"{random_answer}")
    printing = f"print({answer})"
    #print(printing)
    exec(printing)

asking_8ball()
dev
  • 651
  • 1
  • 6
  • 14
  • [**Do not ever use `eval` (or `exec`) on data that could possibly come from outside the program in any form. It is a critical security risk. You allow the author of the data to run arbitrary code on your computer.**](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – Karl Knechtel Jul 05 '22 at 00:01