码迷,mamicode.com
首页 > 编程语言 > 详细

第3章 Python 的控制语句

时间:2018-12-22 01:25:54      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:结构化   match   ...   for   字典实现   float   NPU   使用   2.4   

3.1 结构化程序设计;
3.2 条件判断语句;
3.2.1 if 条件语句;
if (表达式):
语句1
else:
语句2
x = input("x:")
x = int(x)
x = x + 1
print (x)
输入:x:9
10

执行 if 内的程序
a = input("a:")
a = int(a)
b = input("b:")
b = int(b)
if (a > b):
print (a, ">", b)
输出:a:8
b:3
8 > 3
a:2
b:7

if else 语句
a = input("a:")
a = int(a)
b = input("b:")
b = int(b)
if (a > b):
print (a, ">", b)
else:
print (a, "<", b)

3.2.2 if...elif...else 判断语句
score = float(input("score:"))
if 90 <= score <= 100:
print ("A")
elif 80 <= score <= 90:
print ("B")
elif 60 <= score <= 80:
print ("C")
else:
print ("D")

x = -1
y = 99
if (x >= 0):
if (x > 0):
y = 1
else:
y = 0
else:
y = -1
print ("y =", y)

3.2.4 switch 语句的替代方案
使用字典实现switch语句
from __future__ import division
x = 1
y = 2
operator = "*"
result = {"+": x + y, "-": x - y, "*": x * y, "/": x / y}
print (result.get(operator))
输出:2 x*y

class switch(object):
def __init__(self, value):
self.value = value
self.fall = False

def __iter__(self):
yield self.match
raise StopIteration

def match(self, *args):
if self.fall or not args:
return True
elif self.value in args:
self.fall = True
return True
else:
return False

operator = "+"
x = 1
y = 2
for case in switch(operator):
if case("+"):
print (x + y)
break
if case("-"):
print (x - y)
break
if case("*"):
print (x * y)
break
if case("/"):
print (x / y)
break
if case():
print ""

第3章 Python 的控制语句

标签:结构化   match   ...   for   字典实现   float   NPU   使用   2.4   

原文地址:https://www.cnblogs.com/wssys/p/10159031.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!