0
yen = 0.0067
bsp = 1.35
usd = 0.65
ero = 0.85

if choice == "2":
    Current_Currency = input("What currency do you want to exchange: Japenese Yen if so please type yen // British Sterling Pound please type bsp // US Dollers please Type usd // Euro please type ero.")
    if Current_Currency == "yen":
        amount = input("Type amount you wish to exchange")
        Future_Currency = input("What currency do you want to exchange into: Japenese Yen if so please type yen // British Sterling Pound please type bsp // US Dollers please Type usd // Euro please type ero.")
        New_Amount = Future_Currency * amount

我必须构建它,显然我需要通过研究进行浮动,但我不知道如何实现它。

4

2 回答 2

2

看起来您将变量名称与变量混淆了。因为你从用户那里得到的货币类型是一个字符串,所以它不能用来引用变量,除非你对它调用 eval。

new_amount = eval(future_currency) * amount

这样做的缺点是 usingeval为用户提供了一种可能的方式来影响您的代码。相反,您可以使用字典。字典将字符串映射到值,因此您可以使用变量声明:

yen = 0.0067
bsp = 1.35
usd = 0.65
ero = 0.85

并将它们变成字典:

currencies = {'yen': 0.0067, 'bsp': 1.35, 'usd': 0.65, 'ero': 0.85}

使用它,您可以在字典中找到您要查找的值。不要忘记正确处理错误的用户输入!

currencies = {'yen': 0.0067, 'bsp': 1.35, 'usd': 0.65, 'ero': 0.85}

current_currency = raw_input()
future_currency = raw_input()
amount = int(raw_input())
// Check for errors in input here
new_amount = amount * currencies[future_currency] / currencies[current_currency]
于 2013-08-15T20:29:44.263 回答
0

线

Current_Currency = input("What currency do you want to exchange: Japenese Yen if so please type yen // British Sterling Pound please type bsp // US Dollers please Type usd // Euro please type ero.")

如果输入未知变量会抛出错误,Current_Currency并将设置为用户提供的变量名的值,所以该行

if Current_Currency == "yen":

不是真的需要。

yen = 0.0067
bsp = 1.35
usd = 0.65
ero = 0.85

Current_Currency = input("What currency do you want to exchange: Japenese Yen if so please type yen // British Sterling Pound please type bsp // US Dollers please Type usd // Euro please type ero.")
amount = input("Type amount you wish to exchange")
Future_Currency = input("What currency do you want to exchange into: Japenese Yen if so please type yen // British Sterling Pound please type bsp // US Dollers please Type usd // Euro please type ero.")
New_Amount =  Current_Currency / Future_Currency * amount
于 2013-08-15T20:39:13.367 回答