使用Python实现一个简单的猜数字程序

使用Python实现一个简单的猜数字程序

  • 介绍
    • 猜数字代码
    • 运行过程
    • 代码解析
  • 感谢观看!

介绍

本文是作者学习Python的记录,初学上路,误撞勿怪,嘿嘿!
本文所有代码均已成功运行,如有错误,可能是编辑本文时误操作所致。
本文所有代码仅为完成任务,漏洞颇多,输入数据时请规范输入。

猜数字代码

代码如下:

import random
number_list = [number for number in range(1,21,1)]
answer = 'Yes'
while answer == 'Yes':
    ran_numb = random.randint(1,20)
    number = eval(input("Please type a number between 1 to 20 to guess a set number:\n"))
    while number != ran_numb:
        if number not in number_list:
            number = eval(input("Don't be naughty! Type again:\n"))
        elif number > ran_numb:
            number = eval(input("It's a little high! Type again:\n"))
        elif number < ran_numb:
            number = eval(input("It's a little low! Type again:\n"))
    else:
        print("You are right!")
        answer = input("Would you like to play again?(Yes/No)\n")
        while answer != 'Yes' and answer != "No":
            answer = input("I don't understand! Please type again!(Yes/No)\n")
else:
    print("\nThanks for playing!")

运行过程

1.先生成一个纠错列表:

number_list = [number for number in range(1,21,1)]

2.赋值answer,便于后面用户判断:

answer = 'Yes'

3.开始循环
先生成一个随机数:

ran_numb = random.randint(1,20)

4.开始输入:

 number = eval(input("Please type a number between 1 to 20 to guess a set number:\n"))

5.嵌套纠错循环:

while number != ran_numb:
        if number not in number_list:
            number = eval(input("Don't be naughty! Type again:\n"))
        elif number > ran_numb:
            number = eval(input("It's a little high! Type again:\n"))
        elif number < ran_numb:
            number = eval(input("It's a little low! Type again:\n"))

5.1第一个纠错:
提醒用户输入1到20的数字。

if number not in number_list:
    number = eval(input("Don't be naughty! Type again:\n"))

5.2第二个纠错:
提醒用户输入过大。

elif number > ran_numb:
    number = eval(input("It's a little high! Type again:\n"))

5.3第三个纠错:
提醒用户输入过小。

 elif number < ran_numb:
     number = eval(input("It's a little low! Type again:\n"))

6.循环结束反馈机制:

else:
        print("You are right!")
        answer = input("Would you like to play again?(Yes/No)\n")
        while answer != 'Yes' and answer != "No":
            answer = input("I don't understand! Please type again!(Yes/No)\n")

6.1是否想要replay输入:

answer = input("Would you like to play again?(Yes/No)\n")

6.2输入纠错机制:

while answer != 'Yes' and answer != "No":
    answer = input("I don't understand! Please type again!(Yes/No)\n")

7主循环:
输入Yes继续,No则结束。

while answer == 'Yes':
				.
				.
				.
else:
    print("\nThanks for playing!")

代码解析

这个代码的一个漏洞(目前所知)是在你输入数字的时候如果搞事情输入字符串,它就会出错,初学的我尚不能解决,如有大神路过可以给个建议,嘿嘿!
1.随机数生成:

import random
a = random.randint(1,20)#这里生成一个1到20的随机数并赋值给a

2.输入字符串转数字:
这里使用了eval()函数转换input()输入数据。

a = eval(input())#输入一个数字给a

3.本代码采用了多个循环语句和if语句来达到可多次play和纠错的目的,具体可运行代码一玩便知。

感谢观看!

你可能感兴趣的:(Python入门,python,开发语言)