Python practice questions 5.3 four operations (using a dictionary)

Four operations (implemented with a dictionary), compare the switch statement of c language.

Input format:

Enter a number on a line Enter a four-digit operator (+,-, *, /) on a line Enter a number on a line

Output format:

Output operation results in one line (retain 2 decimal places)

code show as below:

#!/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)

This program is simple and uses eval to calculate formulas.


There is always a book and fitness on the road

Guess you like

Origin www.cnblogs.com/Renqy/p/12760043.html