Making a flexible variable inside of an if statement

Question:

I’m currently creating a Python application to calculate financial statement ratios and am having notational issues with making a flexible variable based on user input.

First, the program establishes acceptable stock ticker inputs and creates variables for 2 companies’ annual revenues:

validStockTickers = ['FSLR', 'JKS']

RMB_USD_conversion_factor = 6406572060 / 40826521106

revenue_2019_FSLR = 3063117 * 1000
revenue_2019_JKS = 29746287759 * RMB_USD_conversion_factor

Then the program asks the user which stock ticker the user wants to learn more about:

companyStockInput = input("Which company do you want to learn more about? (Enter stock ticker)")
if companyStockInput in validStockTickers:
     print("Stock Ticker: ",companyStockInput,'n',
          'n',
          "Revenues:",'n',
          "2019 Total Revenue: " + revenue_2019_FSLR

Where I’m having issues is making the revenue_2019_FSLR be flexible based on the user input. So if the user types in JKS at the user prompt, the variable in the last line of my code would be revenue_2019_JKS, etc.

Asked By: jon bon journo

||

Answers:

I’d switch to using a Python dictionary – you can have revenue_2019 store both FSLR and JKS. Even better, you can make revenue into a variable and 2019 into a subdictionary

revenue = {
  "FLSR": {
    "2019": 3063117 * 1000
  },
  "JKS": {
    "2019": 29746287759 * RMB_USD_conversion_factor
  }
}

ticker = input("Which company do you want to learn more about? (Enter stock ticker)")
if ticker in revenue:
  print("Stock Ticker: ",ticker,'n',
    'n',
    "Revenues:",'n',
    "2019 Total Revenue: " + str(revenue[ticker]["2019"])
  )

At that point, if you want to expand revenue to show multiple years you can create a temporary variable for that ticker’s revenues over the years:

# Within the if block
ticker_revenue = revenue[ticker]

year_strings = []
# Gets the years specified as keys
for year in ticker_revenue:
  # I'm using an f-string here to make life easy
  year_strings.append(f"{year} Total Revenue: {ticker_revenue[year]}")

print("Stock Ticker: ",ticker,'n',
  'n',
  "Revenues:",'n',

  # Creates a single string from the array of year strings, joined by newlines
  "n".join(year_strings)
)

Using a dictionary here is definitely best practice, but if you absolutely cannot for some reason, you can use a ternary expression.

"2019 Total Revenue: " + revenue_2019_FSLR if ticker == "FSLR" else revenue_2019_JKS

This method is way more limited than the dictionary approach – you can’t include another ticker in your database superficially, and you can’t read the stock data from a single source into a single variable

Edit: forgot to cast revenue[ticker]["2019"] to string using str() in the first example code block

Answered By: oezingle
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.