-3

I have a couple of strings with some info and I'm trying to ask the user which info to print out.

Could anyone help me solve this?

challenge1 = "Do x"
challenge2 = "Do y"

input = input("What challenge would you like to learn about? \n")

Here I was doing either

print(input)

or

challenge_to_print = "challenge" + input
print(challenge_to_print)

But if I wrote "challenge1" or "challenge2" as input it doesn't work.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Udo
  • 1
  • 1
    So what is the actual question here? – DallogFheir Aug 26 '23 at 00:40
  • idk how to print the actual "do x" and "do y" stuff – Udo Aug 26 '23 at 00:42
  • its just printing "challenge1" or "challenge2" – Udo Aug 26 '23 at 00:43
  • 4
    You mean you're inputting "challenge1" and want to output the contents of the variable named "challenge1"? Use a dictionary: `challenges = { "challenge1": "Do X", ... }`, and then `print(challenges[input])`. Also don't name your variable "input", as that overrides the builtin function. – DallogFheir Aug 26 '23 at 00:55
  • thank you so much! i didnt know that the python equivalent of a switch was called a dictionary lol. As for the variable names, i just put something random in this example, im too ashamed to tell you what the actual ones are called – Udo Aug 26 '23 at 01:02
  • Welcome to Stack Overflow! Please take the [tour] to learn how Stack Overflow works. See also [ask]. For us, ["Can someone help me?" is not an actual question](//meta.stackoverflow.com/q/284236/4518341). That said, I guess you want to ask something like, "How can I get the contents of a variable given the name of the variable as a string?" which is a duplicate of [How do I create variable variables?](/q/1373164/4518341) – wjandrea Aug 26 '23 at 01:24
  • Duplicate of [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – esqew Aug 26 '23 at 01:55

1 Answers1

0

You need conditional statement and logical operator:

challenge1 = "Do x"
challenge2 = "Do y"

challenge = input("What challenge would you like to learn about? \n")

if challenge == 'challange1':
   print(challenge1)
elif challenge == 'challange2':
   print(challenge2)
else:
   print('challange1 or challange2')

or structural pattern matching on python 3.10+ using match case statement (like switch case in C/C++ or Java):

challenge1 = "Do x"
challenge2 = "Do y"

challenge = input("What challenge would you like to learn about? \n")

match challenge:
    case 'challange1':
        print(challenge1)
    case 'challange2':
        print(challenge2)
    case _:
        print('challange1 or challange2')
Arifa Chan
  • 947
  • 2
  • 6
  • 23
  • 1
    Noting that structural pattern matching is only available starting 3.10: https://docs.python.org/3.10/whatsnew/3.10.html#summary-release-highlights – Gino Mempin Aug 26 '23 at 01:44