first_number = input('First number: ')
second_number = input('Second number: ')
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0 !")
else:
print(answer)
# 年龄不满4岁,入场为0
age = 12
if age < 4: # 年龄不满4岁,入场为0,跳过余下测试
print('Your admission cost is $0.')
elif age < 18: # elif仅在if语句为False时才能运行
print('Your admission cost is $5.')
else: # 如果if和elif都未通过,else语句才被运行
print('Your admission cost is $10.')
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else: # while循环被设置为< 5,当count> 5时,便执行else语句
print count, " is not less than 5"
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
import random
class GuessGame():
def __init__(self, min_num, max_num, choice):
'''
:param min_num:
:param max_num:
:param choice:
:return:
'''
self.min_num = min_num
self.max_num = max_num
self.choice = choice
self.target = random.randint(min_num, max_num)
def guess(self):
'''
:return:
'''
choice = self.choice
while choice > 0:
choice -= 1
try:
num = int(input('输入数字: '))
except:
print('输入有效数字')
continue # 跳出这次循环
if num == self.target:
print('恭喜你猜中了')
break # 退出循环
elif num <= self.target:
print('你猜的数字太小了,还剩%d次机会' % choice) # 运用字符串格式化表达式
else:
print('你猜的数字太大了,还剩%d次机会' % choice)
else:
print('很遗憾,%d 次机会都用完了,只差一点点就猜中了,正确答案是 %d' % (self.choice, self.target))
if __name__ == '__main__':
game = GuessGame(1, 100, 5) # 创建实例
game.guess()
你猜的数字太小了,还剩4次机会
输入数字: 1
你猜的数字太小了,还剩3次机会
输入数字: 100
你猜的数字太大了,还剩2次机会
输入数字: 90
你猜的数字太大了,还剩1次机会
输入数字: 0
你猜的数字太小了,还剩0次机会
很遗憾,5 次机会都用完了,只差一点点就猜中了,正确答案是 70
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |