1.if实现switch
输入两个数字和符号,得出结果
#!/usr/bin/env python
# -*- coding: utf-8 -*-
while 1:
num1 = input("请输入num1:")
oper = raw_input("操作符:")
num2 = input("请输入num2:")
if oper == "+":
print num1 + num2
elif oper == "-":
print num1 - num2
elif oper == "*" :
print num1 * num2
elif oper == "/":
if num2 == 0 :
print "ERROR:num2=0"
else:
print num1/num2
else:
print "操作符错误"
2.字典实现switch语句:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
num1 = input("请输入num1:")
oper = raw_input("操作符:")
num2 = input("请输入num2:")
def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 + num2
def muilt(num1, num2):
return num1 * num2
def div(num1, num2):
if num2 == 0:
print "ERROR:num2=0"
else:
return num1 / num2
dict = {
"+": add,
"-": sub,
"*": muilt,
"/": div,
}
if oper in dict:
print dict[oper](num1, num2)
else:
print "error"