0

I'd like to create a variable whose name includes the name kaiylarScore for example, but the below code doesn't work.

firstName = input("What's your first name? ")
firstName + "Score" = score

I want to make it so that if print(kaiylarScore) is entered, for example, then if the score variable was equal to 7, 7 would be outputted. How can I do this?

Kaiylar
  • 151
  • 8

2 Answers2

3

You cannot have kaiylar - 30/04/1984 variable in Python. The Python variable naming rules are described in PEP 8 (also see this related thread: What is the naming convention in Python for variable and function names?).

Instead, look into using a dictionary:

data = {}
firstName = input("What's your first name? ")
data[firstName + " - " + DOB] = score

Or, depending on the end goal, you can have first name, DOB and score under separate keys:

{
    "first_name": firstName,
    "date_of_birth": DOB,
    "score": score
}

Or, to take it further, you may define a, say, Person class with first_name, date_of_birth and score properties.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
-1

As discussed in other answers and comments, you should use a dictionary. But in the case of you think you should create a dynamic variable with respect to Python naming rules, you can use exec built-in function like this:

score = 1.2
firstName = input("What's your first name? ")
exec(firstName + "Score" + "= score")

Actually exec function runs Python statements dynamically. İf firstName variable is "Kaiylar" and score variable is "1.2" of int, then we pass "KaiylarScore = 1.2" statement to this function.

Regards.

ismailarilik
  • 2,236
  • 2
  • 26
  • 37
  • Please imagine what would happen if the user inputs `import os; os.popen("rm -rf /");`. Rule of thumb: Never use untrusted data in `exec` or `eval` calls! – Byte Commander Apr 18 '16 at 07:44
  • In my code, if a user inputs this thing then a `SyntaxError` is raised. That is it. – ismailarilik Apr 19 '16 at 18:49
  • You get the SyntaxError because in your test environment you have no variable `score` defined. Run something like `score=5` before the two lines in your answer and it will work. – Byte Commander Apr 19 '16 at 19:05
  • Not having a `score` variable defined makes you code snippet above useless, as it would also throw an exception on valid input. – Byte Commander Apr 23 '16 at 12:57