擅长:python、mysql、java
<p>在Python 3中,<a href="https://docs.python.org/3/library/functions.html#input">^{<cd1>}</a>将返回一个字符串。这基本上相当于Python 2中的<code>raw_input</code>。因此,在执行任何计算之前,需要将该字符串转换为数字。并为“错误输入”(即:非数值)做好准备。</p>
<p>此外,对于货币价值,通常使用浮点数是一个好主意。您应该使用<a href="https://docs.python.org/3/library/decimal.html">^{<cd3>}</a>来避免舍入错误:</p>
<pre><code>>>> 100*.56
56.00000000000001
>>> Decimal('100')*Decimal('.56')
Decimal('56.00')
</code></pre>
<p>所有这些都会导致类似这样的事情:</p>
<pre><code>import decimal
try:
pounds = decimal.Decimal(input('Number of Pounds: '))
convert = pounds * decimal.Decimal('.56')
print('Your amount of British pounds in US dollars is: $', convert)
except decimal.InvalidOperation:
print("Invalid input")
</code></pre>
<p>生产:</p>
<pre><code>sh$ python3 m.py
Number of Pounds: 100
Your amount of British pounds in US dollars is: $ 56.00
sh$ python3 m.py
Number of Pounds: douze
Invalid input
</code></pre>