locale.currency problem?
I’m running the following script (from Murach’s Python Programming Ch01), using Python 3.6.1 on OS X Sierra. It runs fine when invoked from the Terminal, and when run inside IDLE, but fails when run within PyCharm Edu 2.0.4, with “ValueError: Currency formatting is not possible using the 'C' locale.” Why the different behaviour?
I’m new at all of this so if you need further information, please ask.
#!/usr/bin/env python3
import locale
# set the locale for use in currency formatting
result = locale.setlocale(locale.LC_ALL, '')
if result == 'C':
locale.setlocale(locale.LC_ALL, 'en_US')
# display a welcome message
print("Welcome to the Future Value Calculator")
print()
choice = "y"
while choice.lower() == "y":
# get input from the user
monthly_investment = float(input("Enter monthly investment:\t"))
yearly_interest_rate = float(input("Enter yearly interest rate:\t"))
years = int(input("Enter number of years:\t\t"))
# convert yearly values to monthly values
monthly_interest_rate = yearly_interest_rate / 12 / 100
months = years * 12
# calculate the future value
future_value = 0
for i in range(months):
future_value = future_value + monthly_investment
monthly_interest_amount = future_value * monthly_interest_rate
future_value = future_value + monthly_interest_amount
# format and display the result
print("Future value:\t\t\t%s" % locale.currency(
future_value, grouping=True))
print()
# see if the user wants to continue
choice = input("Continue? (y/n): ")
print()
print("Bye!")
Please sign in to leave a comment.
Hi M Godotishere!
on macOS returns not only C so
is not executed. I believe you should change
to just
Hi Pavel,
Thank you for your help. Can you explain to me why the script should work when run within Terminal or IDLE on macOS?
Doesn't that suggest that the explanation involves some feature of PyCharm that differs to the Terminal and IDLE environments?
It's not PyCharm specific, if I run it inside terminal on macOS with
it fails the same way. That's probably because I have LC_CTYPE="UTF-8" so when one call
LC_CTYPE changed it's value from C (which is set on the program start) back to UTF-8, so
return not C but C/UTF-8/C/C/C/C because not all locale categories are equal and than it breaks program execution because if clause was not executed as I wrote above. I'm not sure though why this is not the case in IDLE, looks like
has no effect there. Hope it makes sense. I will check the docs, there's probably an answer there.