选择结构
1.if语句
**语法:
if 条件1:(条件为真,执行缩进的语句块)
if 条件2:(嵌套语句)
条件真缩进语句块
else:(条件为假时执行)
条件假缩进语句块
其余语句
**多分支结构:
if 条件1:
语句块1
elif 条件2:
语句块2 #条件1不成立条件2成立时执行
elif 条件3:
语句块3
else: #注意 else 一定要放在最后
语句
while循环结构
1.while循环
三条件缺一不可:
初始值 | 循环条件 | 循环变量
*循环体外设定循环可执行的初始条件
*书写需要重复执行的代码(循环体)
*设定循环条件并且在循环体内部设定条件改变语句 (#很重要,否则很容易进入死循环)
#coding:utf-8
count = 1
while count<5:
print("So cold!") #重复执行的语句
count +=1
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
So cold!
So cold!
So cold!
So cold!
Process finished with exit code 0
***************************
2.常见的死循环
(1)
count = 0
while count < 10:
print count
(2)
count = 0
while count < 10:
print count
count -= 1
(3)
count = 0
while count < 10:
print count
count +=1
(4)
count = 0
while count < 10:
if count%2 ==0:
print count
(5)
count = 0
while count < 10:
if count%2 ==0:
print count
(6)
count = 0
while count < 10:
if count%2 == 0:
print count
***计算一元二次方程的解
#coding:utf-8
import math
while True:
a=float(raw_input("Please enter a:"))
b=float(raw_input("Please enter b:"))
c=float(raw_input("Please enter c:"))
if a != 0:
delta = b**2 - 4*a*c
if delta < 0:
print("No solusion")
elif delta == 0:
s = -b/(2*a)
print ("s:"),s
else:
root=math.sqrt(delta)
s1 = (-b + root) / (2*a)
s2 = (-b - root) / (2*a)
print ("Two distinct solusion are:"),s1,s2
ch=raw_input("q")
if ch == 'q':
break
***********************************
3.break 结束当前循环体
count = 0
while count < 5:
if count > 2:
break #结束当前循环体
print('Hello nihao !')
count +=1
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
C:\Users\epi\AppData\Local\Programs\Python\Python35\python.exe E:/Pycharm/文件/break和continue.py
Hello nihao !
Hello nihao !
Hello nihao !
Process finished with exit code 0
******************************
4.continute 结束当次循环
count = 0
while count < 5:
count += 1
if count > 2:
continue #j结束当次循环,不再进行print判断
print("So cold today!")
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
C:\Users\epi\AppData\Local\Programs\Python\Python35\python.exe E:/Pycharm/文件/break和continue.py
So cold today!
So cold today!
Process finished with exit code 0
for 循环
语法:
for 变量 in 对象: #枚举对象中的每一个元素
缩进语句块(循环体)
#依次的遍历对象中的每一个元素,并赋值给变量,然后执行循环内的语句
#计算1+2+3+...+10的值
s = 0
for i in range(1,11):
s += i
print("sum is :",s)
sum is : 55
在mathm模块中,math.factorial()可以用来计算阶乘
#求π的值
pi = 0
sign = 1
divisor = 1
for i in range(1,1000000):
pi += 4.0*sign / divisor
sign *= -1 #符号转换
divisor += 2
print("pi is ",pi)
pi is 3.1415936535907742
format函数可以实现对齐
#猜测平方根
x = 2
low = 0
high = x
guess = (low + high) / 2
while abs(guess ** 2 - x) > 0.001 :
if guess ** 2 > x :
high = guess
else :
low = guess
guess = (low + high) / 2
print (guess)
#次情况不能输入小于1的数,考虑该如何解决