The first stage base Python Notes (a)

Just getting started with Python, did not clarify what has been a clue, look at Daniel's suggestion, I intend to write notes, slightly and patted it.
Exchange rate first class
1, of the strings
in Python strings are ordered starting from 0, the last character is starting from -1 sort of forward, i.e.,
0 1 2. 5. 4. 3
Python
-6 -5 - 4-3-2-1
will have to amount extraction unit in the input string can be used [-3:] or extracting CNY USD

# 带单位的货币输入
currency_str_value = input('请输入带单位的货币金额:')

# 获取货币单位
unit = currency_str_value[-3:]

After completion of the extraction unit amount of money, and then extract money

rmb_str_value = currency_str_value[:-3]
rmb_value = eval(rmb_str_value)

Wherein [: -3] represents the characters have been extracted from the beginning to the -2 position of the character, the character is not included in the -3 position. The eval function extracted by the character into a digital format.
2, if statement
in other languages if statement with no difference in C language and the like, the end of the colon to note, while the indent is demanded for Python, {} is used instead of, and not under the code if the if statement thereof, use the Tab key to indent.

if unit == 'CNY':
elif unit == 'USD':
else:

3, while loop

# 带单位的货币输入
currency_str_value = input('请输入带单位的货币金额(退出程序请输入Q):')
while currency_str_value != 'Q':
    # 带单位的货币输入
    currency_str_value = input('请输入带单位的货币金额(退出程序请输入Q):')
print('程序已退出!')

4, the function package

def convert_currency(im, er):
    """
        汇率兑换函数
    """
    out = im * er
    return out
# 汇率
USD_VS_RMB = 6.77

# 带单位的货币输入
currency_str_value = input('请输入带单位的货币金额:')

unit = currency_str_value[-3:]

if unit == 'CNY':
    exchange_rate = 1 / USD_VS_RMB

elif unit == 'USD':
    exchange_rate = USD_VS_RMB

else:
    exchange_rate = -1

if exchange_rate != -1:
    in_money = eval(currency_str_value[:-3])
    # 调用函数
    out_money = convert_currency(in_money, exchange_rate)
    print('转换后的金额:', out_money)
else:
    print('不支持该种货币!')

Defined lambda 5, simple function

 in_money = eval(currency_str_value[:-3])
 # 使用lambda定义函数
 convert_currency2 = lambda x: x * exchange_rate
 # 调用lambda函数
 out_money = convert_currency2(in_money)

Guess you like

Origin blog.csdn.net/holddoor/article/details/78317213