优化这段代码:print("猜数游戏") import random a=random.randrange(1, 100) b=int(input("请猜测并输入一个 0~100 的整数:")) i=0 while a!=b: if b>a: print("你猜大了") b=int(input("请再次输入:")) i+=1 elif b<a: print("你猜小了") b=int(input("请再次输入:")) i+=1 else: print("恭喜你猜中了,共猜测",i,"次")
时间: 2023-05-31 15:02:41 浏览: 51
print("猜数游戏")
import random
a = random.randint(1, 100)
i = 0
while True:
b = int(input("请猜测并输入一个 0~100 的整数:"))
i += 1
if b > a:
print("你猜大了")
elif b < a:
print("你猜小了")
else:
print("恭喜你猜中了,共猜测", i, "次")
break
相关问题
编写python程序,实现下面描述的猜数游戏。 首先,程序随机生成一个0-9之间的整数。之后,让用户通过键盘输入所猜的数。如果大于预设的数字,显示“遗憾,太大了!”;如果小于预设的数字,则显示“遗憾,太小了!”;如此循环,直至猜中该数,显示“预测N次,你猜中了!”。 以下是部分代码: import random secret = random.randint(0,9) #程序随机生成一个0-9之间的整数 guess = 10 #表示用户输入的猜测数 N=1 #记录猜测的次数
while True:
guess = int(input("请输入你猜的数字:"))
if guess > secret:
print("遗憾,太大了!")
elif guess < secret:
print("遗憾,太小了!")
else:
print("预测{}次,你猜中了!".format(count))
break
用python实现.猜数小游戏(1到100之间) 3次之内猜对,输出:恭喜你,猜对了:太牛B了 4到7次猜对,输出:恭喜你,猜对了:哎呦,不错呦! 7次内都没猜对,结束游戏,输出:太笨了,7次都没猜对! 运行效果如下: ================ 猜数小游戏(1到100之间) ================= 请输入数字:【30】 太小了 请输入数字:【60】 太小了 请输入数字:【90】 太大了 请输入数字:【80】 太小了 请输入数字:【85】 太大了 请输入数字:【82】 恭喜你,猜对了:哎呦,不错呦!
好的,以下是代码实现:
```python
import random
def guess_number():
num = random.randint(1, 100)
count = 0
while count < 7:
guess = int(input("请输入数字:"))
count += 1
if guess < num:
print("太小了")
elif guess > num:
print("太大了")
else:
if count <= 3:
print("恭喜你,猜对了:太牛B了")
else:
print("恭喜你,猜对了:哎呦,不错呦!")
return
print("太笨了,7次都没猜对!")
print("================= 猜数小游戏(1到100之间) =================")
guess_number()
```
运行效果如下:
```
================= 猜数小游戏(1到100之间) =================
请输入数字:50
太小了
请输入数字:75
太大了
请输入数字:60
太大了
请输入数字:55
太小了
请输入数字:57
恭喜你,猜对了:哎呦,不错呦!
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)