Python基础-03

目录

1.del语句

2.身份运算符

3.运算符优先级

面试题

练习题

面试题

作业

4.语句

4.1 行

4.2 pass语句

4.3选择语句***

4.4真值表达式与条件表达式

4.5循环语句

4.6跳转语句

练习


1.del语句

a = '孙悟空'
b = a
c = a
del a   # a虽然删除了,但是不影响b、c;“孙悟空”的引用量为2,不会被销毁
​
a = '孙悟空'
b = a
c = a
del a,b # a、b虽然删除了,但是不影响c;“孙悟空”的引用量为1,不会被销毁(不释放对象“孙悟空”)
​
a = '孙悟空'
b = a
c = a
del a,b
c = None
# a、b删除了,c不再引用对象“孙悟空”;“孙悟空”的引用量为0,会被回收(不是立即回收,而是内存标记为可回收)

  • 语法:del 变量名1,变量名2

  • 作用:用于删除变量,同时解除与对象的关联,如果可能则释放对象。(删除变量并不代表释放对象)

  • 自动化内存管理的引用计数:每个对象记录被变量绑定(引用)的数量,当为0时被销毁

    补充:百度“python的内存管理机制”

2.身份运算符

  • 语法

    x is y
    x is not y
    a = 1000
    b = 800
    # 使用id函数,可以获取变量存储的对象地址
    print(id(a))    # 1961551198704
    print(id(b))    # 1961551198352
    print(a is b)    # False
    ​
    c = a
    print(id(c))    # 1961551198704
    print(c is a)    # True
    ​
    d = 1000
    print(a is d)    # True,这里只适合文件式python不适合交互式python
  • 作用:

    is 用于判断两个对象是否是同一个对象,是则返回True,否则返回False。is的本质就是通过id函数进行判断。

    is not的作用与is 相反

3.运算符优先级

常用的运算符优先级有三个:

  • 算数运算符 > 比较运算符

if 2+10>11:
    print ("真")
else:
    print("假")

  • 比较运算符 >逻辑运算符

if i >2 and 2<10:
    print("成立")
else:
    print("不成立")

  • 逻辑运算符内部三个优先级:not > and > or

if not 1 and 1>2 or 3==8:
    print ("真")
else:
    print("假")

上述三个优先级从高到低总结:加减乘除 >比较 >not and or

TIPS:加括号,小括号表示优先级

面试题

逻辑运算中:and 与 or

and:只要有一个是False,整体就是False(一假俱假)

or:只要有一个为True,整体就是True(一真俱真)

v1 = name=="alex" and pwd =="123"
    #v1最终表示的是True/False  and  True/False
        
if name=="alex" and pwd =="123":
    pass
v2="wupeiqi" and "alex"
"""   如果and/or后面的不是True/False,而是字符串或数字处理规则如下:
​
    第一步:将该字符串或数字转换为布尔值——True and True
    第二步:判断本次操作取决于哪个(由于前面是True,所以本次逻辑判断本质上取决于后面的值)
    第三步:所以后面的值等于多少,最终的结果(等于原始值)就等于多少。           v2="alex"
​
"""
-------------------------------------------------------------------
v3 = "" and "alex"
"""
第一步:将该字符串或数字转换为布尔值——False and True
    第二步:判断本次操作取决于哪个(由于前面是False,所以本次逻辑判断本质上取决于前面的值)
    第三步:所以前面的值等于多少,最终的结果(等于原始值)就等于多少。           v2=""
"""
------------------------------------------------------
v4 = 1 or 8             
"""
第一步:将该字符串或数字转换为布尔值——True or True
    第二步:判断本次操作取决于哪个(由于前面是True,所以本次逻辑判断本质上取决于前面的值)
    第三步:所以前面的值等于多少,最终的结果(等于原始值)就等于多少。           v4=1
"""
-----------------------------------------------------------
​
v5 = 0 or 8             """
第一步:将该字符串或数字转换为布尔值——False or True
    第二步:判断本次操作取决于哪个(由于后面是True,所以本次逻辑判断本质上取决于后面的值)
    第三步:所以后面的值等于多少,最终的结果(等于原始值)就等于多少。           v5=8
"""

练习题

v1 = 1 or 2
v2 = -1 or 3
v3 = 0 or -1
v4 = 0 or 100
v5 = "" or 10
v6 = "wupeiqi" or ""

print(v1, v2, v3, v4, v5, v6)


u1 = 4 and 8
u2 = 0 and 6
u3 = -1 and 88
u4 = "" and 7
u5 = "武沛齐" and ""
u6 = "" and 0
u7 = 0 and "中国"

print(u1, u2, u3, u4, u5, u6, u7)

面试题

TIPS:先计算and 后计算or

not > and > or

v1 = 0 or 4 and 3 or 7 or 9 and 6
"""
第一步:(4 and 3)→3;(9 and 6)→6,即:v1 = 0 or 3 or 7 or 6
第二步:只剩下or,从前往后来。(0 or 3)→3;(3 or 7)→3;(3 or 6)→3
	即,v1 = 3
"""
v2 = 0 or 3 and 4 or 2 and 0 or 9 and 7
"""
第一步:(3 and 4)→4;(2 and 0)→0;(9 and 7)→7,即v2 = 0 or 4 or 0 or 7
第二步:只剩下or,从前往后来。(0 or 4)→4;(4 or 0)→4;(4 or 7)→4
	即:v2=4
"""

v3 = 0 or 2 and 3 and 4 or 6 and 0 or 3
"""
第一步:(2 and 3)→3;(3 and 4)→4;(6 and 0)→0,即v3=0 or 4 or 0 or 3
第二步:只剩下or,从前往后来。(0 or 4)→4;(4 or 0)→4;(4 or 3)→4
	即:v3=4
"""

v4 = not 8 or 3 and 4 or 2
"""
第一步:(not 8)→false;(3 and 4)→4;即v4 = false or 4 or 2
第二步:只剩下or,从前往后来。(false or 4)→4;(4 or 2)→4
	即:v4= 4
"""

作业

1.判断下列逻辑语句的True,False

1 > 1 or 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6
# false or true or false and true and true or false
# false or true or false or false
#True
not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6
# not true and true or false and true and true or false
#false and true or false and true and true or false
#false or false and true or false
#false or false or false
#False

2.求出下列逻辑语句的值

V1 = 8 or 3 and 4 or 2 and 0 or 9 and 7
#8 or 4 or 0 or 7
#V1 = 8


v2 = 0 or 2 and 3 and 4 or 6 and 0 or 3
#0 or 4 or 0 or 3
#v2 = 4

3.下列结果是什么?

u1 = 6 or 2 > 1   #u1=6
u2 = 3 or 2 > 1		#u2=3
u3 = 0 or 5 < 4		#u3=False
u4 =5 < 4 or 3		#u4=3
u5 = 2 > 1 or 6		#u5=True
u6 = 3 and 2 > 1		#u6=True
u7 = 0 and 3 > 1		#u7=0
u8 = 2 > 1 and 3		#u8=3
u9 = 3 > 1 and 0		#u9=0
u10 = 3 > 1 and 2 or 2 < 3 and 3 and 4 or 3 > 2		#u10=2

4.实现用户登录系统,并且要支持三次输错之后直接退出,并且在每次输错时显示剩余错误次数(提示:使用字符串格式化)

num = 1
while num < 4:
    name = input("请输入用户名:")
    password = input("请输入密码:")
    if name == "wupeiqi" and password == "123":
        break
    else:
        data = 3 - int(num)
        script = "剩余次数为:{data}"
        text = script.format(data = 3 - int(num))
        print(text)
        num += 1
#老师讲解:法二
count = 3
while count >0:
    count -=1
    name = input("请输入用户名:")
    password = input("请输入密码:")
    if name == "wupeiqi" and password == "123":
        print("登录成功")
        break
        
    else:
        message ="用户名或密码错误,剩余次数为{}次".format(count)
        print(message)

5.猜年龄游戏,要求:允许用户最多尝试三次,三次都没有猜对就直接退出,如果猜对了就打印“恭喜你 猜对了”并退出。

num = 1
while num < 4:
    age = input("请输入年龄:")
    if int(age) ==66:
        print("恭喜你猜对了")
        break
    else:
        num += 1
#老师讲解:
count = 0
while count <3:
    count+=1
    age = input("请输入年龄:")
    age = int(age)
    if age ==66:
        print("恭喜你猜对了")
        break
    else:
        print("猜错了")
print("程序结束")        

6.猜年龄游戏升级版,要求:允许用户最多尝试三次,每尝试三次后,如果还没猜对就问用户是否还想继续玩,如果回答Y就继续让其猜三次,以此往复,如果回答N,就退出程序,如果猜对了就直接退出

num = 0
flag = True
while flag:
    age = input("请输入年龄:")
    if int(age) == 66:
        print("恭喜你猜对了")
        flag = False
    else:
        num += 1
        if num % 3 == 0:
            choice = input("请输入Y或者N决定是否继续游戏:")
            if choice == "N":
                flag = False
            else:
                num = 0
#老师讲解:
count = 0
while count <3:
    count+=1
    age = input("请输入年龄:")
    age = int(age)
    if age ==66:
        print("恭喜你猜对了")
        break
    else:
        print("猜错了")
    if count==3:
        choice = input("请输入Y或者N决定是否继续游戏:")
        if choice =="N":
            break
        elif choice == "Y":
            count =0
        else:
            print("输入有误")
            break
print("程序结束")        

4.语句

4.1 行

  • 物理行:程序员编写代码的行

  • 逻辑行:python解释器需要执行的指令

    a = 1
    b = a + 2
    c = a + b
    # (3个)物理行与(3个)逻辑行一一对应
    
    a = 1 ; b = a + 2 ; c = a + b
    # (1个)物理行、(3个)逻辑行,不建议
    
    d = 1+2
    \+3+4+5+6
    # (2个)物理行、(1个)逻辑行。\表示折行符
    
    d = (1+
         2+
         3+
         4+
         5+6)
    # (5个)物理行、(1个)逻辑行。括号是天然的折行符
    

  • 建议一个逻辑行在一个物理行上

  • 如果一个物理行中使用多个逻辑行,需要使用分号 ; 来隔开

  • 如果逻辑行过长,可以使用隐式换行或显式换行。

    隐式换行:所有括号的内容换行,称为隐式换行。括号包括:()、[]、{}三种

    显式换行:通过折行符\(反斜杠)换行,必须放在一行的末尾,目的是告诉解释器下一行也是本行的语句

4.2 pass语句

通常用来填充语法空白

4.3选择语句***

4.3.1 if、elif、else 语句(一个 Tab键默认4个空格)

gender = input("请输入性别:")
if gender == "男":
	print("您好,先生!")
elif gender == "女":
	print("您好,女士!")
else:
    print("您输入的性别有误!")
print("后续逻辑")
  • 调试:让程序中断,逐语句执行(让语句执行就执行,不让语句执行就不执行)。调试是一种排错的手段。
  • 调试目的:①审查运行过程中变量取值;②审查程序运行流程。
  • 调试步骤:①加断点(可能出错的行);②调试运行:运行-调试(debug);③执行一行F8 ;④停止:Ctrl+ F2

练习1:从控制台中获取商品单价、数量及客户已交付金额,如果已付金额大则提示需要找零多少,反之则提示钱不够需要还差多少钱。

price = float(input("请输入商品单价:"))
num = float(input("请输入商品数量:"))
paid = float(input("请输入已付金额:"))
total = price * num
if paid > total:
    msg = "应找回{}".format(paid - total)
elif paid == total:
    msg = "不多不少刚刚好"
else:
    msg = "还差{}".format(total - paid)
print(msg)

练习2:在控制台中获取一个季度(春夏秋冬),显示出相应的月份。

season = input("请输入季节(春夏秋冬):")
if season == "春":
    month = "一月、二月、三月"
elif season == "夏":
    month = "四月、五月、六月"
elif season == "秋":
    month = "七月、八月、九月"
elif season == "冬":
    month = "十月、十一月、十二月"

msg = "{}季对应的月份为{}".format(season,month)
print(msg)

练习3:在控制台中录入两个数字、一个运算符,根据运算符计算两数字的运算结果。

num_1 = float(input("请输入一个数字:"))
num_2 = float(input("请输入一个数字:"))
operator = input("请输入运算符:")
if operator == "+":
    result = num_1 + num_2
elif operator == "-":
    result = num_1 - num_2
elif operator == "*":
    result = num_1 * num_2
elif operator == "/":
    result = num_1 / num_2
else:
    result = "运算符输入有误"
print(result)

练习4:在控制台分别录入四个数字,打印输出最大的数字

num_1 = float(input("请输入第一个数字:"))
num_2 = float(input("请输入第二个数字:"))
num_3 = float(input("请输如第三个数字:"))
num_4 = float(input("请输入第四个数字:"))
if num_1 > num_2:
    data_1 = num_1
else:
    data_1 = num_2

if num_3 > num_4:
    data_2 = num_3
else:
    data_2 = num_4

if data_1 > data_2:
    result = data_1
else:
    result = data_2
print(result)

# 法二
num_1 = float(input("请输入第一个数字:"))
num_2 = float(input("请输入第二个数字:"))
num_3 = float(input("请输如第三个数字:"))
num_4 = float(input("请输入第四个数字:"))
result = num_1
if result < num_2:
    result = num_2

if result < num_3:
    result = num_3

if result < num_4:
    result = num_4
print(result)

练习5:在控制台中获取成绩判断等级(优秀/良好/及格/不及格/成绩输入有误)

grade = float(input("请输入成绩:"))
if 85 < grade <=100:
    result = "优秀"
elif 70 < grade <=85:
    result = "良好"
elif 60 <= grade <=70:
    result = "及格"
elif 0 <= grade <60:
    result = "不及格"
else:
    result = "成绩输入有误"
print(result)

# 优化:if、elif及else之间是互斥的关系。
grade = float(input("请输入成绩:"))
if grade < 0 or grade > 100:
    result = "成绩输入有误"
elif 85 < grade:
    result = "优秀"
elif 70 < grade:
    result = "良好"
elif 60 <= grade:
    result = "及格"
else:
    result = "不及格"

print(result)

练习6:在控制台中获取月份,打印输出天数。

1 3 5 7 8 10 12→31天;4 6 9 11→30天;2→28天

month = int(input("请输入月份:"))
if month == 2:
    result = 28
elif month == 4 or month == 6 or month == 9 or month == 11:
    result = 30
elif month == 1 or month == 3 or month == 5 \
        or month == 7 or month == 8 or month == 10 or month == 12:
    result = 31
else:
    result = "月份输入有误"
print(result)


month = int(input("请输入月份:"))
list_1 = [1,3,5,7,8,10,12]
list_2 = [4,6,9,11]
if month in list_1:
    result = "31天"
elif month in list_2:
    result = "30天"
elif month == 2:
    result = "28天"
else:
    result = "月份输入有误"
print(result)

4.4真值表达式与条件表达式

  • 真值表达式

if 100:		# 相当于if bool(100):
	print("真值")
str_input = input("请输入:")
if str_input:
    print("输入的字符串不是空的")
  • 条件表达式:有选择性的为变量进行赋值

    可以适当简化代码,但是不要以代码可读性为代价来简化代码。

    语法:变量 = 结果1 if 条件 else 结果2

    作用:根据条件(True /False)来决定返回结果1还是结果2

gender = None
if input("请输入性别:") == "男":
    gender = 1
else:
    gender = 0
print(gender)

gender = 1 if input("请输入性别:") == "男" else 0
print(gender)
# 1.在控制台中获取一个整数,如果是偶数则为变量state赋值"偶数",否则赋值为"奇数"
number = int(input("请输入一个整数:"))
state = "偶数" if number % 2 == 0 else "奇数"
print(state)

# step1:
number = int(input("请输入一个整数:"))
if number%2==1:
    state = "奇数"
else:
    state = "偶数"
print(state)

# step2:number%2==1转换为布尔值是True
number = int(input("请输入一个整数:"))
if number%2:
    state = "奇数"
else:
    state = "偶数"
print(state)

# step3:
number = int(input("请输入一个整数:"))
state = "奇数" if number%2 else "偶数"
print(state)
# 2.在控制台中录入一个月份,如果是闰年给变量day赋值29否则赋值28
year = int(input("请输入一个年份:"))
day = 29 if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 else 28
print(day)

# 这个代码简单但是可读性太差!代码最简有度,但是一定要有可读性
year = int(input("请输入一个年份:"))
day = 29 if not year % 4 and year % 100 or not year % 400 else 28
# 注意: ==0时转换为布尔值是False,!=0时转换为布尔值是True
print(day)

4.5循环语句

while

作用:可以让一段代码满足条件,重复执行。(break:退出循环体)

语法:

while 条件:
    满足条件执行的语句

死循环:循环条件永远都是满足的。

练习1:输入季节判断月份循环执行,按e键退出。

while True:
    season = input("请输入季节(春夏秋冬,e键退出):")
    if season == "春":
        print("一月、二月、三月")
    elif season == "夏":
        print("四月、五月、六月")
    elif season == "秋":
        print("七月、八月、九月")
    elif season == "冬":
        print("十月、十一月、十二月")
    elif season == "e":
        break
    else:
        print("季节输入有误")

练习2:执行三次后退出

count = 0
while count < 3:
    usd = float(input("请输入美元:"))
    print(usd * 6.9)
    count += 1

练习3:在控制台中输出0 1 2 3 4 5

i = 0
while i < 6:
    print(i, end=" ")
    i += 1

练习4:在控制台中输出2 3 4 5 6 7

i = 2
while i < 8:
    print(i, end=" ")
    i += 2

练习5:在控制台中输出0 2 4 6

i = 0

while i < 7:
    print(i, end=" ")
    i +=2

练习6:在控制台中获取年龄输出他的身份

age = float(input("请输入年龄:"))
if age <0:
    print("输入有误")
elif age < 2:
    print("婴儿")
elif age < 13:
    print("儿童")
elif age < 20:
    print("青少年")
elif age < 65:
    print("成年人")
elif age < 150:
    print("老年人")
else:
    print("不可能")

练习7:根据身高体重,参照BMI返回身体状况

height = float(input("请输入身高(单位:米):"))
weight = float(input("请输入体重(单位:kg):"))
BMI = weight / height ** 2
if BMI < 18.5:
    print("体重过低")
elif BMI < 24:
    print("正常范围")
elif BMI < 28:
    print("超重")
elif BMI < 30:
    print("I度肥胖")
elif BMI < 40:
    print("II度肥胖")
else:
    print("III度肥胖")

4.6跳转语句

break

练习

1.在控制台获取一个开始值,一个结束值,将之间的数字打印出来

例如:开始值3,结束值10,打印4 5 6 7 8 9

start_num = int(input("请输入开始值:"))
end_num = int(input("请输入结束值:"))
num = start_num + 1
while num < end_num:
    print(num, end=" ")
    num += 1

2.一张纸的厚度是0.01毫米,请计算对折多少次超过珠穆朗玛峰(8844.43m)

paper = 0.01 * 10 ** (-3)
num = 1
while paper * 2 ** num < 8844.43:
    num += 1
print(num)

# 老师讲解:
thickness = 0.01 * 0.001
count = 0  # 计数器
while thickness < 8848.43:
    count += 1
    thickness *= 2
print(count)

3.猜数字游戏,游戏运行产生一个1-100之间的随机数,让玩家重复猜测,直到猜对为止,提示:大了,小了,对了以及总共猜了多少次

import random	# 随机数工具(在开头只写一次)

target = random.randint(1, 100)	# 产生一个随机数
count = 0
flag = True
while flag:
    num = int(input("请输入一个数字"))
    count += 1
    if num < target:
        print("小了")
    elif num > target:
        print("大了")
    else:
        print("猜对了,总共猜了{}次".format(count))
        flag = False
print(count)

# 老师讲解
import random  # 随机数工具(在开头只写一次)

random_number = random.randint(1, 100)  # 产生一个随机数
count = 0
while True:
    count += 1
    input_number = int(input("请输入一个数字:"))
    if input_number > random_number:
        print("大了")
    elif input_number < random_number:
        print("小了")
    else:
        print("猜对了,总共猜了{}次".format(count))
        break

4.升级版猜数字游戏:最多猜三次(超过三次提示失败游戏结束)

# 这个版本不对,因为如果在三次以内猜对数字依旧会打印输出“失败游戏结束”
import random  # 随机数工具(在开头只写一次)

random_number = random.randint(1, 100)  # 产生一个随机数
count = 0
while count < 3:
    count += 1
    input_number = int(input("请输入一个数字:"))
    if input_number > random_number:
        print("大了")
    elif input_number < random_number:
        print("小了")
    else:
        print("猜对了,总共猜了{}次".format(count))
        break
print("失败了,游戏结束")

# 修改版
import random  # 随机数工具(在开头只写一次)

random_number = random.randint(1, 100)  # 产生一个随机数
count = 0
while count < 3:
    # 三次以内
    count += 1
    input_number = int(input("请输入一个数字:"))
    if input_number > random_number:
        print("大了")
    elif input_number < random_number:
        print("小了")
    else:
        print("猜对了,总共猜了{}次".format(count))
        break	# 退出循环体,不会执行while循环里的else语句
else:		# 这个else是与while对应的,此处的else与if处的else语义相同
    # 三次以外
    print("失败了,游戏结束")

5.根据成绩录入等级,如果录入空字符串则退出程序,如果成绩录入次数达到3,则退出程序并提示“成绩输入次数过多”

count = 0
while count<3:
    str_grade = input("请输入成绩:")
    if str_grade == "":
        break
    grade = float(str_grade)
    if grade < 0 or grade > 100:
        print("成绩输入有误")
        count += 1
    elif 85 < grade:
        print("优秀")
    elif 70 < grade:
        print("良好")
    elif 60 <= grade:
        print("及格")
    else:
        print("不及格")
else:
    print("成绩输入次数过多")

你可能感兴趣的:(Python教程1000节,python)