python基础之运算符、if条件语句、while循环、for循环

一、运算符

计算机可以进行的运算有很多种,不只是加减乘除,它和我们人脑一样,也可以做很多运算。

种类:算术运算,比较运算,逻辑运算,赋值运算,成员运算,身份运算,位运算,今天我们先了解前四个。

算术运算:

a=10,b=20

赋值运算:

比较运算:

逻辑运算:

二、if循环

 

  • if / elif / else /

  • # 第一题:让用户输入一个数字,猜:如果数字 > 50,则输出:大了; 如果数字 <= 50 ,则输出:小了。
    num = input('请输入一个数字')
    number = int(num)
    if number > 50:
    print('大了')
    else:
    print('小了')
    # int是整型的意思,input输入的内容永远是字符串,若要与数字加减,必须使用int整型
  • and语句表示两侧的条件语句同时成立

if name = '小明' and gender = '男'

 

三、while循环

  • while的基本结构: while A>0: 注意空格和冒号
  • while 语句中 break的含义,指中止当前所有循环,stop
count = 1
while count <= 10:
    print(count)
    if count == 7:
        break
    count += 1
  • while语句中continue的含义,指不在进行本次循环,返回while 执行下次循环,类似于pass ,要点是continue会跳出本次循环,在whilie语句后改变变量,可以利用continue 规避,在if条件语句之后改变变量,陷入死循环,值得注意的跟break的区别,一个是终止所有循环,一个是终止本次
count = 0  #使用whilie continue 语句 实现1.2.3.4.5.6.8.9.10
while count <= 9:
    count += 1
    if count == 7:
        continue
    print(count)
  • while语句中whilie else的用法,用处较少,表示不在满足于while条件语句才触发,或 条件= false
  • 注意 break continue pass 的使用区别
四、for循环 (固定搭配for  * in * :)
name = 'aksbdi1'
for a in name:
    print(a)

D:\python3.6\python3.6.exe D:/python_code/day01/day04.py
a
k
s
b
d
i
1

示例:break直接退出for循环
name = 'aksbdi1'
for a in name:
    print(a)
    break
    print('123')
结果: 
D:\python3.6\python3.6.exe D:/python_code/day01/day04.py
a
示例:continue
name = 'aksbdi1'
for a in name:
    print(a)
    continue
    print('123')
 
结果:
D:\python3.6\python3.6.exe D:/python_code/day01/day04.py
a
k
s
b
d
i
1
 
# 练习题
# 1. for循环打印 “alex” 的每个元素: for > while
# 2. 请打印: 1 - 10
for i in range(1,11):
    print(i)
 
结果:
D:\python3.6\python3.6.exe D:/python_code/day01/day04.py
1
2
3
4
5
6
7
8
9
10
# 3. 请打印: 1 2 3 4 5 6 8 9 10
 for i in range(1,11):   
     if i == 7:      
     pass  
     else:
  print(i)
 
结果:
D:\python3.6\python3.6.exe D:/python_code/day01/day04.py
1
2
3
4
5
6
8
9
10 
注意:for和while的应用场景:有穷尽优先使用for,无穷尽用while

 

posted @ 2019-11-04 15:54  小蚂农  阅读(244)  评论(0编辑  收藏  举报