国内最专业的IT技术学习网

UI设计

当前位置:主页 > UI设计 >

用Python开发一个简单的猜数字游戏

发布时间:2019/09/23标签:   数字    点击量:

原标题:用Python开发一个简单的猜数字游戏
本文先容怎样应用Python制造一个简略的猜数字游戏。游戏规矩玩家将推测一个数字。假如推测是准确的,玩家赢。假如不准确,顺序会提醒玩家所猜的数字与现实数字比拟是“大(high)”仍是“小(low)”,如斯来去直到玩家猜对数字。预备好Python3起首,须要在盘算机上装置Python。能够从Python官网下载并装置。本教程须要应用最新版的Python 3(版本3.x.x)。确保选中将Python增加到PATH变量的框。假如不如许做,将很难运转该顺序。当初,在装备上翻开文本/代码编纂器。就团体而言,我偏好应用Brackets。 Windows上预装了Notepad, Mac OS包括TextEdit,而Linux用户能够应用Vim。翻开文本编纂器后,保留新文件。我将它定名为main.py,但你能够随便定名,只有它以.py开头便可。编码本教程的阐明将作为解释包括在代码中。 在Python中,解释以#扫尾并始终连续到行停止。fromkeras.layersimportConv2D,MaxPooling2D,GlobalAveragePooling2D#First,weneedtoimportthe'random'module.#Thismodulecontainsthefunctionalityweneedtobeabletorandomlyselectthewinningnumber.importrandom#Now,weneedtoselectarandomnumber.#Thislinewillsetthevariable'correct'tobeequaltoarandomintegerbetween1and10.correct=random.randint(1,10)#Let'sgettheuser'sfirstguessusingthe'input'function.guess=input("Enteryourguess:")#Rightnow,theuser'sinputisformattedasastring.#Wecanformatitasanintegerusingthe'int'function.guess=int(guess)#Let'sstartaloopthatwillcontinueuntiltheuserhasguessedcorrectly.#Wecanusethe'!='operatortomean'notequal'.whileguess!=correct:#Everythinginthisloopwillrepeatuntiltheuserhasguessedcorrectly.#Let'sstartbygivingtheuserfeedbackontheirguess.Wecandothisusingthe'if'statement.#Thisstatementwillcheckifacomparisonistrue.#Ifitis,thecodeinsidethe'if'statementwillrun.ifguess>correct:#Thiscodewillruniftheuserguessedtoohigh.#Wecanshowamessagetotheuserusingthe'print'function.print("You'veguessedtoohigh.Tryguessinglower.")else:#The'else'statementaddsontoan'if'statement.#Itwillruniftheconditionofthe'if'statementisfalse.#Inthiscase,itwillruniftheuserguessedtoolow,sowecangivethemfeedback.print("You'veguessedtoolow.Tryguessinghigher.")#Nowweneedtolettheuserguessagain.#NoticehowIamcombiningthetwolinesofguessingcodetomakejustoneline.guess=int(input("Enteryourguess:"))#Ifauser'sguessisstillincorrect,thecodeinthe'while'loopwillberepeated.#Ifthey'vereachedthispointinthecode,itmeanstheyguessedcorrectly,solet'ssaythat.print("Congratulations!You'veguessedcorrectly.")别的,能够随便变动顺序中的任何内容。比方,能够将准确的数字设置为1到100而不是1到10,能够变动顺序在print()函数中所说的内容。你的代码想怎样写都能够。运转顺序依据你的操纵体系,翻开下令提醒符(Windows / Linux)或终端(Mac)。 按次序实验以下每个下令。 假如准确装置Python,此中最少有一个应当能够运转。pythonC:/Users/username/Desktop/main.pypyC:/Users/username/Desktop/main.pypython3C:/Users/username/Desktop/main.py

版权信息Copyright © 银河官网 版权所有    ICP备案编号:鲁ICP备09013610号