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())].
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('你猜的数小了!') elif guess > secretNumber: print('你猜的数大了!') else: break if guess == secretNumber: print('猜对了!') else: print('很遗憾,秘密数字是:', str(secretNumber))
Running effect:
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!