0
点赞
收藏
分享

微信扫一扫

Python猜数字游戏

伊人幽梦 2022-02-07 阅读 146

猜数字

导出随机模块

import random

设置循环范围【1-20】

num = random.randint(1, 20)

请用户输入猜的数字

print(‘Hello,What’s your name?’)
name = input(’’)

字符串用+号的组合整字符串

print(‘Well,’ + name + ‘,I am thinking a number between 1 and 20.’)

设置猜数次数

i = 0

while循环结构、if…elif语句和break的使用

while i < 6:
# 每次循环都进行再来一次提示
print(‘Take a guess’)
num1 = int(input(’’))
i += 1
if num1 > num:
print(‘you guess is too high.’)
elif num1 < num:
print(‘you guess is too low.’)
else:
print(f’Great,{name},you guess my number in {i} guesses!’)
# 终止程序,不继续执行下方代码
break

次数大于6次时,输出游戏结束

else:
print(f’Sorry,{name},you didn’t guess my answer.’)

举报

相关推荐

0 条评论