四則運算(用字典實現),比較c語言的switch語句。
輸入格式:
在一行中輸入一個數字 在一行中輸入一個四幟運算符(+,-,*,/) 在一行中輸入一個數字
輸出格式:
在一行中輸出運算結果(小數保留2位)
代碼如下:
#!/usr/bin/python # -*- coding: utf-8 -*- sf = {'+':'x+y','-':'x-y','*':'x*y','/':'x/y if y!=0 else "divided by zero"'} x = int(input()) xysf = input() y = int(input()) result = eval(sf[xysf]) if type(result) != str: print("{:.2f}".format(result)) else: print(result)
這個程序簡單,使用eval進行公式計算。
讀書和健身總有一個在路上