• 963 Players on Java
  • us.mineplex.com
  • 10547 Players Online
  • 9584 Players on Bedrock
  • pe.mineplex.com
!
Attention Internet Explorer Users
To have the best user experience on our site please consider upgrading to Google Chrome or Mozilla Firefox

Python Tutorial - Get a variable by string.

Discussion in 'Technology' started by UCYT5040, Nov 2, 2020.

  1. Hi! So I have seen some people with a string (like "hello") that need to change a variable (in the example the variable is hello)
    print(f"Hello 1 plus one is {str(1+1)}") is the same as print("Hello 1 plus one is " + str(1+1)) but f-strings make it shorter.

    Code:
    hello = 5
    
    var = input("What variable do you want to change?")
    # user give hello
    value = input(f"What do you want to change {var} to?")
    # user gives 10
    
    var = value
    print(var)
    # prints 10
    print(hello)
    # prints 5
    Expiation: var is a variable set to "hello". var = value is the same as "hello" = value. Basically you can't change a variable with a string, but what if you can? Here is how.

    Code:
    hello = 5
    
    var = input("What variable do you want to change?")
    # user give hello
    value = input(f"What do you want to change {var} to?")
    # user gives 10
    
    exec(f"{var} = {value}")
    print(var)
    # prints 10
    print(hello)
    # prints 10
    Using exec() we can change the value without eval or anything like that.

    How To Use:
    var = 10
    varName = "var"

    exec(f"{varName} = 20")

    The first param is the var name.
    {varName} is only for f strings
    You can also use exec(varName + "=" + value)

    I hope this helps!
     
    Posted Nov 2, 2020
    GoldenCodes likes this.
  2. Nice tutorial! Python's syntax is extremely "friendly" for first time programmers, and even easier to understand if you've been programming in another language such as Java, Kotlin, C++, etc. Personally, I'm very fond of this language because of the fact that there's so many things you can do with it; good luck to any first time programmers out there who are starting off with Python! And if your looking to learn Python or any other language in "depth", I would honestly suggest checking out "Udemy" for some amazing programming courses; best of luck!
     
    Posted Nov 4, 2020
  3. Hey! I've been a developer in Python for around 6 months now. I started with the basics, as anyone else did. I then moved on to coding discord bots with Python, and then currently I'm just making some smaller projects while trying to learn C# and build a game with graphics. As @GoldenCodes said, Udemy is an amazing resource for courses, the best location for courses in my opinion. Good luck to anyone using python.
     
    Posted Nov 4, 2020
    GoldenCodes likes this.

Share This Page