Python Forum
How do I create a Dynamic Variable?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I create a Dynamic Variable?
#1
USD = 1
USDs = 'United States'
CountryVariableName = 'USD'

CountryName = CountryVariableName + 's'
print(CountryName) would print "USDs", but is there anyway to make it so that it prints the value of USDs instead??

Can you think of a work around to this if what I am specifying is not possible? Appreciate it.
Reply
#2
I can think of couple of ways - but none of them is recommended.
Use dictionaries:

currencies = {'US': 'US$', 'UK': '£'}
country_name = 'US'
print(currencies[country_name])
and you get
Output:
US$
PS The name you use are un-Pythonic; Pythonistas customarily use snake-style names for variables - see PEP-8
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to create a variable only for use inside the scope of a while loop? Radical 10 1,711 Nov-07-2023, 09:49 AM
Last Post: buran
  dynamic variable name declaration in OOP style project problem jacksfrustration 3 786 Oct-22-2023, 10:05 PM
Last Post: deanhystad
  loop (create variable where name is dependent on another variable) brianhclo 1 1,140 Aug-05-2022, 07:46 AM
Last Post: bowlofred
  Create Dynamic For Loop quest 3 4,391 Apr-26-2021, 02:03 PM
Last Post: ibreeden
  Create variable and list dynamically quest_ 12 4,404 Jan-26-2021, 07:14 PM
Last Post: quest_
  How do I get the in3.Client() to create a variable with attributes? (in3 pypi pckge) Johno 2 1,859 Jan-21-2021, 02:49 AM
Last Post: Johno
  Create new variable dependent on two existing variables JoeOpdenaker 6 3,020 Oct-25-2020, 02:15 PM
Last Post: jefsummers
  Alternative to dynamic variable names catosp 13 4,589 Jun-20-2020, 03:45 PM
Last Post: catosp
  Use dynamic variable from parallel running python script Sicksym 0 1,844 May-15-2020, 02:52 PM
Last Post: Sicksym
  Mysql CREATE TABLE IF NOT EXISTS dynamic table name nisusavi 0 2,349 Apr-29-2020, 06:45 PM
Last Post: nisusavi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020