How to implement a guessing number game in Python

coldplay.xixi
Release: 2020-10-29 11:08:25
Original
8893 people have browsed it

How to implement the number guessing game in python: use conditional statements to implement judgment, the code is [print('Guess an integer between 1-20.');print('Start guessing:');for i in range(1, 7):try:guess = int(input())].

How to implement a guessing number game in Python

Related free learning recommendations: python video tutorial

How to implement the number guessing game in Python:

gives you 6 chances to guess a pre-generated integer between 1-20. Cover some knowledge points:

  • Conditional statement

  • Control statement

  • random function

  • Read input

  • Exception handling

Code:

"""
猜数字
"""
from random import *
secretNumber = randint(1, 20)
# print(secretNumber)
print('猜一个1-20之间的整数。')
print('开始猜:')
for i in range(1, 7):
 try:
 guess = int(input())
 except ValueError:
 print('输入有误!')
 continue
 if guess < secretNumber:
 print(&#39;你猜的数小了!&#39;)
 elif guess > secretNumber:
 print(&#39;你猜的数大了!&#39;)
 else:
 break
  
if guess == secretNumber:
 print(&#39;猜对了!&#39;)
else:
 print(&#39;很遗憾,秘密数字是:&#39;, str(secretNumber))
Copy after login

Running effect:

How to implement a guessing number game in Python

The above is the detailed content of How to implement a guessing number game in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!