零基础学习Python 作业 第4章
这节课主要学习了if else和 while的用法
重要的是:
1.别忘记加冒号了
2.“缩进”是Python的灵魂
习题:
0. 请问以下代码会打印多少次“我爱鱼C!”
- while 'C':
- print('我爱鱼C!') ----------------无限次,因为’C’ = 67 == truth,满足while的循环条件
1.请问以下代码会打印多少次“我爱鱼C!”
- i = 10
- while i:
- print('我爱鱼C!')
- i = i - 1 -----------------------------10次
2. 请写出与 10 < cost < 50 等价的表达式
10<cost and cost<50
3.Python3 中,一行可以书写多个语句吗?
>>> print(‘I love you’);print(5)
4.Python3 中,一个语句可以分成多行书写吗?
反斜杠’\’ 或者 括号’()’
>>> 5>4 and
\ 6>3
>>> (3>2 and
2>1)
5.请问Python的 and 操作符 和 C语言的 && 操作符 有何不同?【该题针对有C或C++基础的朋友】
Answer:
C && test
C语言中 && 操作符是逻辑运算符,备注:C语言中 & 是位操作符
and 是逻辑预算符,同时也是bool运算符,>>> (3>2 and 2>1) 返回 True
6. 听说过“短路逻辑(short-circuit logic)”吗?
逻辑操作符有个有趣的特性:在不需要求值的时候不进行操作。这么说可能比较“高深”, ‘不做无用功’
e.g.表达式 x and y,需要 x 和 y 两个变量同时为真(True)的时候,结果才为真。
因此,如果当 x 变量得知是假(False)的时候,表达式就会立刻返回 False,而不用去管 y 变量的值。
这种行为被称为短路逻辑(short-circuit logic)或者惰性求值(lazy evaluation)
动手习题
1.(为用户提供三次机会尝试,机会用完或者用户猜中答案均退出循环)并改进视频中小甲鱼的代码。
import random
i = 3
temp = random.randint(1,9)
print(temp)
while i > 0 :
temp1 = raw_input("请输入你猜测的数字:")
while not temp1.isdigit():
temp1 = raw_input("输入错误,请重新输入:")
i -=1
temp2 = int(temp1)
if temp2 == temp:
print("猜对了""\n" "恭喜!")
break
elif temp2 < temp:
print("小了,请重新输入")
else:
print("输入大了,请重新输入")
print("游戏结束!")
Python 2.7版本中提示输入 raw_input
Python 3 版本中提示输入修改为 input
import random
times = 3
secret = random.randint (1,10)#随机函数
print(secret)
#先给出guess赋值(赋一个绝对不等于secret的值)
#print()默认是打印完字符串会自动添加一个换行符,end=" "参数告诉print()用空格代替换行
while times > 0:
temp = raw_input('猜猜我心里想的是什么数字?')
#输入语句要放到循环语句之内,当输入信息与随机生成信息不一致时可再次循环输入!
while not temp.isdigit():
temp = raw_input('输入错误,请再次输入:')
guess = int (temp)
times = times - 1#每输入一次,可用机会就-1
if guess == secret:
print('wtf,你是我心里的蛔虫吗?猜对了!')
break
else:
if guess > secret:
print('大了大了!!')
else:
print('小了小了!!')
if times > 0:
print ('再试一次吧:')
else:
print('机会用完了,退下吧。')
print('游戏结束,又被坑了吧!!')
2.Python3 中,一行可以书写多个语句吗?
str1 = "ddd";str2 = "ccc";print(str1 + str2)
3.Python3 中,一个语句可以分成多行书写吗?
str1 = (""" sjlkjljkj lkjasjdlkjflkd klejkljkla """)