数据类型的分类

数值可以分为:整型、浮点型(小数)、布尔类型、e记法(科学计数法)

其中比较特别的就是布尔类型,其只有True和False两种值,布尔类型可以看作是另类的数字,False为0,True为1。
作为判断真假的赋值表现形式,选择0和1,是因为计算机芯片最基础的运算就是由0和1构成,而在应用层,选择0和1能够达到最快的运算速度。

复习:Python把0、空字符串’’和None看成 False,其他数值和非空字符串都看成 True

查看数据类型,可以用type()来确认。

课后习题

0.在 Python 中,int 表示整型,那你还记得 bool、float 和 str 分别表示什么吗?
int 整形、bool 布尔型、float(浮点型)、str(字符串)

1.你知道为什么布尔类型(bool)的 True 和 False 分别用 1 和 0 来代替吗?
因为0和1是cpu的运算单元,这样最快,不浪费时间在转换过程中。

  1. 使用 int() 将小数转换为整数,结果是向上取整还是向下取整呢?
    向下取整(5.5=5)负数则向上取整(-5.5=-5)
    换个理解,即是以小数点为截断点,之后的数全部舍弃,即可。

  2. 我们人类思维是习惯于“四舍五入”法,你有什么办法使得 int() 按照“四舍五入”的方式取整吗?
    利用中位数0.5来达到强制升位的结果
    5.4 “四舍五入”结果为:5,int(5.4+0.5) == 5
    5.6 “四舍五入”结果为:6,int(5.6+0.5) == 6

  3. 取得一个变量的类型,视频中介绍可以使用 type() 和 isinstance(),你更倾向于使用哪个?
    type()但建议使用 isinstance()

  4. Python3 可以给变量命名中文名,知道为什么吗?
    能,Pyhton3 源码文件默认使用utf-8编码(支持中文)

    1. >>> 你是谁啊 = "大笨蛋"
    2. >>> print(你是谁啊)
    3. 大笨蛋

对游戏的进一步改进,增加输入错误的提示。

  1. import random
  2. times = 3
  3. secret = random.randint(1,10)
  4. print('----------Blue Studo-----------------')
  5. #这里给guess赋值,赋值不能等于secret的值
  6. guess=0
  7. #print()默认打印完字符自动添加换行符,end=“ ”参数参数告诉#print()用空格代替(空格也可为其它类型)
  8. print('猜数字Can you konw my LK number:',end="") #如果用end="HH"会将HH打印至输入框,不影响输入结果,但是在这不好看
  9. while (guess != secret) and (times>0):
  10. temp = input()
  11. if temp.isdigit(): #本次新加的课业
  12. guess = int(temp)
  13. times =times - 1 #每输入一次,机会少一次
  14. if guess == secret:
  15. print('good')
  16. print('nice')
  17. else:
  18. if guess > secret:
  19. print('big,big:')
  20. else:
  21. print('little,little:')
  22. if times > 0:
  23. print('come on,again:',end="")
  24. else:
  25. print("no again")
  26. else: #本次新加的
  27. print("Please input int")
  28. print('game over')

判断年份是否是闰年?
提示:这样定义闰年的:能被4整除但不能被100整除,或者能被400整除都是闰年。
精简版PY

  1. print("Determine Leap Year")
  2. temp = int(input())
  3. year = temp / 400
  4. if year == int(year):
  5. print("Leap Year")
  6. else:
  7. print("not Leap Year")
  8. print("thanks")

image.png
能够实现判定需求,但是和之前有明显的问题,即是输入不满足预期的数据,输入非正整数,输入字符串会报错以及错误的继续运行。
以下为改进版(输入中文,直接提示非int)

  1. print("Determine Leap Year")
  2. temp = int(input())
  3. if temp >= 0:
  4. year = temp / 400
  5. if year == int(year):
  6. print("Leap Year")
  7. else:
  8. print("Average year")
  9. else:
  10. print("请输入数字")
  11. print("thanks")

image.png
最终答案(输入中文,提示输入错误,但是会循环,估计后期作业会解决)

  1. print("Determine Leap Year")
  2. temp = input()
  3. while not temp.isdigit():
  4. print("Please input a year number")
  5. year = int (temp)
  6. if year/400 == int(year/400):
  7. print(temp+"is Leap Year")
  8. else:
  9. if year/4 == int(year/4) and year/100 != int(year/100):
  10. print(temp + "is Leap Year")
  11. else:
  12. print(temp + " is Average year")