Python语法学习一之基础语法

注意

Python是以缩进来代替其他编程语法中的 { }

一、注释

1-1、单行注释
    # 单行注释
    print('hello world')
1-2、多行注释
'''
Python多行注释
'''

二、变量类型

查看变量类型
a = "cehae"
print type(a)
3163615-644108a13c4ef937.png
图片.png

三、标识符

3-1、标识符定义

标示符由字母、下划线和数字组成,且数字不能开头,python中的标识符是区分大小写的。

3-2、命名规则:驼峰命名法
3163615-2964b3c3e75974a8.png
图片.png

四、输出

    # 打印提示
    print('hello world')
4-1、格式化输出

Python使用 % 格式化输出

    age = 10
    print("我今年%d岁"%age)

    age += 1
    print("我今年%d岁"%age)

    age += 1
    print("我今年%d岁"%age)

    age = 18
    name = "xiaohua"
    print("我的姓名是%s,年龄是%d"%(name,age))

3163615-96c3ba46a6c01edc.png
图片.png

五、运算符

5-1、算术运算符
3163615-a98beb09297b373f.png
图片.png
5-2、赋值运算符
3163615-a4d7312b42d2e85b.png
图片.png
5-3、复合赋值运算符
3163615-2f8645010cdd9048.png
图片.png
5-4、比较(即关系)运算符
3163615-5986dba85fbbc707.png
图片.png
5-5、逻辑运算符
3163615-a06109d5c144a59f.png
图片.png

六、数据类型转换

3163615-a621c4d37eb16a4f.png
图片.png

七、判断语句

7-1、if
7-1-1、if

语法

   if 条件:
            条件成立时,要做的事情

案例

    age = 30
    if age>=18:
        print "我已经成年了"
7-1-2、if else

语法

   if 条件:
            条件成立时,要做的事情
    else:
        不满足条件时逻辑

案例

age = 17
if age >= 18:
    print "我已经成年了"
else:
    print "谁还不是个宝宝"
7-1-3、if elif

语法

   if 条件1:
            条件成立时1,要做的事情
    elif 条件2:
            条件成立时2,要做的事情
    elif 条件3:
            条件成立时3,要做的事情
    elif 条件4:
            条件成立时4,要做的事情

案例

  score = 77
    if score>=90 and score<=100:
        print('本次考试,等级为A')
    elif score>=80 and score<90:
        print('本次考试,等级为B')
    elif score>=70 and score<80:
        print('本次考试,等级为C')
    elif score>=60 and score<70:
        print('本次考试,等级为D')
    elif score>=0 and score<60:
        print('本次考试,等级为E')

八、循环语句

5-1、while循环
   while 条件:
        条件满足时,做的事情1
        条件满足时,做的事情2
        条件满足时,做的事情3
        ...(省略)...
    i = 0
    while i<5:
        print("当前是第%d次执行循环"%(i+1))
        print("i=%d"%i)
        i+=1
5-2、for循环
    for 临时变量 in 列表或者字符串等:
        循环满足条件时执行的代码
    else:
        循环不满足条件时执行的代码
    name = 'cehae'
    
    for x in name:
        print(x)
    else:
        print("没有数据")
5-3、break和continue

注意:break/continue在嵌套循环中,只对最近的一层循环起作用

break结束整个循环

    i = 0
    while i<10:
        i = i+1
        print('----')
        if i==5:
            break
        print(i)
    

    name = 'dong1Ge'
    for x in name:
        print('----')
        if x == '1':
            break
        print(x)
    else:
        print "没有数据了"
3163615-ebc857ffb4ff5821.png
图片.png

continue跳出本次循环

name = 'dong1cehae'
    for x in name:
        print('----')
        if x == '1':
            continue
        print(x)
    else:
        print "没有数据"
        

    i = 0
    while i < 10:
        i = i + 1
        print('----')
        if i == 5:
            continue
        print(i)

猜你喜欢

转载自blog.csdn.net/weixin_33895604/article/details/86927895