扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
前言
创新互联公司是一家集网站建设,宁陵企业网站建设,宁陵品牌网站建设,网站定制,宁陵网站建设报价,网络营销,网络优化,宁陵网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。本文介绍如何使用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中,注释以#开头并一直持续到行结束。
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D # First, we need to import the 'random' module. # This module contains the functionality we need to be able to randomly select the winning number. import random # Now, we need to select a random number. # This line will set the variable 'correct' to be equal to a random integer between 1 and 10. correct = random.randint(1, 10) # Let's get the user's first guess using the 'input' function. guess = input("Enter your guess: ") # Right now, the user's input is formatted as a string. # We can format it as an integer using the 'int' function. guess = int(guess) # Let's start a loop that will continue until the user has guessed correctly. # We can use the '!=' operator to mean 'not equal'. while guess != correct: # Everything in this loop will repeat until the user has guessed correctly. # Let's start by giving the user feedback on their guess. We can do this using the 'if' statement. # This statement will check if a comparison is true. # If it is, the code inside the 'if' statement will run. if guess > correct: # This code will run if the user guessed too high. # We can show a message to the user using the 'print' function. print("You've guessed too high. Try guessing lower.") else: # The 'else' statement adds on to an 'if' statement. # It will run if the condition of the 'if' statement is false. # In this case, it will run if the user guessed too low, so we can give them feedback. print("You've guessed too low. Try guessing higher.") # Now we need to let the user guess again. # Notice how I am combining the two lines of guessing code to make just one line. guess = int(input("Enter your guess: ")) # If a user's guess is still incorrect, the code in the 'while' loop will be repeated .# If they've reached this point in the code, it means they guessed correctly, so let's say that. print("Congratulations! You've guessed correctly.")
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流