您的位置:首页 > 编程语言 > Python开发

零基础学习Python 作业 第5章

2018-03-05 17:59 330 查看
———-CH05 homework———-

0 在 Python 中,int 表示整型,那你还记得 bool、float 和 str 分别表示什么吗?

Answer: bool表示逻辑类型(True-1, False-0);

float表示浮点数类型;

str表示字符串类型。

1 你知道为什么布尔类型(bool)的 True 和 False 分别用 1 和 0 来代替吗?

Answer: 计算机使用2进制表示,其中只有0和1。可以理解为实物的两个状态,真假。

2 使用 int() 将小数转换为整数,结果是向上取整还是向下取整呢?

Answer: 向下取整

3 我们人类思维是习惯于“四舍五入”法,你有什么办法使得 int() 按照“四舍五入”的方式取整吗?

Answer: int(a + 0.5)

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

Answer: isinstance() Python3 推荐

5 Python3 可以给变量命名中文名,知道为什么吗?

Answer: 因为中文编码方式是UTF-8,而Python 支持UTF-8编码

6 【该题针对零基础的鱼油】你觉得这个系列教学有难度吗?

Answer: NO

Practice

针对视频中小甲鱼提到的小漏洞,再次改进我们的小游戏:

当用户输入错误类型的时候,及时提醒用户重新输入,防止程序崩溃。

s.isalnum() 所有字符都是数字或者字母,为真返回 Ture,否则返回 False。

s.isalpha() 所有字符都是字母,为真返回 Ture,否则返回 False。

s.isdigit() 所有字符都是数字,为真返回 Ture,否则返回 False。

s.islower() 所有字符都是小写,为真返回 Ture,否则返回 False。

s.isupper() 所有字符都是大写,为真返回 Ture,否则返回 False。

s.istitle() 所有单词都是首字母大写,为真返回 Ture,否则返回 False。

s.isspace() 所有字符都是空白字符,为真返回 Ture,否则返回 False。

code:

import random
secret = random.randint(1, 100)
print('----------Talk to me wow----------')
guess = 0
count = 7

while guess != secret and count > 0:
print('All 7 times, and You still have ', count, ' chances')
temp  = input('Please enter a number(1~100):')
while temp.isdigit() != 1:
print('Sorry! INPUT ERROR')
temp = input('Please enter a number again:')
guess = int(temp)
count = count - 1
if guess == secret:
print('Wonderful! Congration!')
else:
if guess > secret:
print('You guess bigger!')
else:
print('You guess smaller!')
if count > 0:
print('You can continue!')
else:
print('No chances! Bye')
print('Game Over')


TEST result

----------Talk to me wow----------
All 7 times, and You still have  7  chances
Please enter a number(1~100):q
Sorry! INPUT ERROR
Please enter a number again:10
You guess bigger!
You can continue!
All 7 times, and You still have  6  chances
Please enter a number(1~100):5
You guess bigger!
You can continue!
All 7 times, and You still have  5  chances
Please enter a number(1~100):3
Wonderful! Congration!
Game Over


1 写一个程序,判断给定年份是否为闰年。(注意:请使用已学过的 BIF 进行灵活运用)

这样定义闰年的:能被4整除但不能被100整除,或者能被400整除都是闰年。

code:

print('=-------------闰年计算器-------------=')
print('注意:输入查询的年份,格式:XXXX,如2014')
temp = 1
while temp != '110':
temp = input('请输入查询的年份: ')
while temp.isdigit() != 1:
temp = input('对不起,输入格式为正数!重新输入:')
year = int(temp)
if year / 400 == int(year / 400):
print('公元', temp, '年是闰年!')
else:
if (year / 4 == int(year / 4)) and (year / 100 == int(year / 100)):
print('公元', temp, '年是闰年!')
else:
print('公元', temp, '年是平年!')
#temp = 110
print('GameOver')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息