聪明办法学python(2)

发布时间 2023-11-25 23:25:15作者: 真的还没想好什么名字

聪明办法学python(2)

TASK03:数据类型与操作

一.常用内置类型:

1.1整数integer (int)
1.2浮点数Float
print(0.1 + 0.1 == 0.2) # True
print(0.1 + 0.1 + 0.1 == 0.3) # False!
print(0.1 + 0.1 + 0.1) # 0.30000000000000004
print((0.1 + 0.1 + 0.1) - 0.3) # 特别小,5.551115123125783e-17,不是0
1.3布尔值Boolen
  • True,用于表示布尔
  • False,用于表示布尔
  • None,代表 ,用于空值
1.4类型Type(类型也是一种类型!)
1.5math库中的一些数学常量
  • pi,数学常量π=3.141592..........
  • e,数学常量e=2.718281............
  • tau,数学常量tau=6.283185.........
  • inf,浮点正无穷大,等价于float('int'),负无穷大使用-math.inf
2.1常用内置运算符
  • 算术:+,-,*,/,@,//,**,%
  • 关系:<,>,>= ,<= ,== ,!=
  • 赋值:+=,-=,*=,/=,//=,**=,%=
  • 逻辑:and,or,not
3.1短路求值
  • and
    格式:操作数1 and 操作数2
    如果操作数1的值为True, 那么运算结果就等于操作数2。
    如果操作数1的值为False, 那么运算结果就等于操作数1

    print(no() and crash())#成功运行
    print(crash() and no())#程序崩溃
    
  • or
    格式:操作数1 or 操作数2
    如果操作数1的值为Tru,那么运算结果就等于操作数1。
    如果操作数1的值为False0,那么运算结果就等于操作数2

    print(yes() or crash())#成功运行
    print(crash() or yes())#程序崩溃
    
    4.1任务
    • 任务:编写代码,判断x是不是数字

      def is_number(x):
          rweturn((type(x) == int) or 
          	   (type(x) == float))
          
       print(is_number(1),is_number(1.1),is_number(1+2i),is_number("p2s"))
      #True  True   Flase   Flase
      

TASK04:条件

一.if语句

1.1一个栗子
def f(x):
    print("A",end="")
    if x == 0:
        print("B",end="")
        print("C",end="")
    print("D")
   f(0)   #结果是ABCD
        
1.2另一个栗子
#abs()用于绝对值计算
#任务:实现一个函数,返回输入数字的绝对值
def abs1(n):
    if n < 0:
        n = -n
    return n
1.3一元二次方程的实数解
def number(a,b,c):
    d = b**2 - 4*a*c
    if d > 0:
        return 2
    elif d == 0:
        return 1
    else:
        return 0
print("y = 4*x**2 + 5*x + 1 has",number(4,5,1),"root(s).") 
#y = 4*x**2 + 5*x +1 has 2 root(s)
print("y = 4*x**2 + 4*x + 1 has",number(4,4,1),"root(s).")  
#y = 4*x**2 + 4*x +1 has 1 root(s)
print("y = 4*x**2 + 2*x + 3 has",number(4,2,3),"root(s).") 
#y = 4*x**2 + 2*x +3 has 0 root(s)

二.MATCH-CASE语句

1.1示例
match subject:
    case <pattern_1>;
    	 <action_1>
    case <pattern_2>;
    	 <action_2>
    case <pattern_3>;
    	 <action_3>
    case _:
          <action_wildcard>
1.2随堂练习
#根据四六级成绩判断是否可以毕业
def is_graduate(cet4,cet6):
    if cet4 >= 425:
        if cet6 >= 425:
            return "yes"
        else:
            return "NO"
        
cet4,cet6 = input(),split()
cet4 = float(cet4)
cet6 = float(cet6)
print(is_graduate(cet4,cet6))
1.3好的代码习惯
#if部分尽可能为真,else为假


'''b = Flase
if not b:
    print('no')   清晰'''




'''b = Flase
if b:
	pass
else:
    print('no    不清晰
'''