난수 게임 - Python
목차
Imports
Writing the code
Finishing results
수입품
The only module you need to import is random
, which will help the computer choose the random number at the start of the game.
To import it, just do the code below, at the start of the game:
import random
코드 작성
We can start off by creating a variable called number
, which holds the random number the user has to try to figure out.
You can do that by using the function random.randint()
with the two inputs: 1,100, which is the range of the random number.
That is equivalent to the code below:
number = random.randint(1,100)
Then, you have to get the first integer input the user has done, to guess the number, and save the input under a variable called guess
. Around the input, you could use the function int()
, to convert the string input to an integer, so later when comparing guess
to number
, it won’t show an error. Comparing a string and an integer creates an error.
guess = int(input("Guess a number from 1-100:\n"))
Next, you want the program to keep on asking you what the number is until you get it right, so you use a while
loop, and make it run while guess
is not equal to number
.
So you do:
while guess != number:
Now you want to tell the user if the guess they have done is higher or lower than the actual number, so you use if
and elif
statements.
First you check if guess
is greater than number
, and if that is True
, then it will tell the user that the number is smaller than their guess.
If the first statement is False
, then you check if number
is greater than guess
, and if that is True, then it will tell the user that the number is larger than their guess.
Both of these statements will be inside the while
loop, so they run until the user figures out what the number is.
Make sure that when printing guess
with a string, you convert guess
to a string as you cannot print a string with an integer on the same line.
if guess > number:
print(f"The number is smaller than {str(guess)}")
elif number > guess:
print(f"The number is bigger than {str(guess)}")
If you run the code altogether and enter the input as an integer which isn't equal to number
, the code will keep on running, and it won't stop.
The loop is coded to keep on running while guess
is not equal to number
, and as the data held in the variable guess
isn't changed, the loop will keep on running.
After the if
and elif
statements, you have to add another line of code so the user can input what they think the guess is after they have received the high or low clue.
guess = int(input("Guess the number:\n"))
Right now, the program doesn't tell the user when they have guessed the correct number.
So after the while
loop, make the program tell the user that they have guessed the correct number and what the correct number is.
print(f"You guessed the number correctly! It was {str(number)}")
Now, to make it a bit more fun, we can add a variable to count the amount of guesses it takes for the user to guess the number.
At the start of the code after the import, create a variable called count
and set it as 1.
count = 1
Now, before the input in the while
loop, make count
increase by one.
count += 1
So the user knows at the end how many guesses it took them to figure out the correct number, tell them on the last line of code.
print(f"You guessed the correct number in {str(count)} guesses!")
You've written the whole code!
마무리 결과
The full code is:
import random
count = 1
number = random.randint(1,100)
guess = int(input("Guess a number from 1-100:\n"))
while guess != number:
if guess > number:
print(f"The number is smaller than {str(guess)}")
elif number > guess:
print(f"The number is bigger than {str(guess)}")
count += 1
guess = int(input("Guess the number:\n"))
print(f"You guessed the number correctly! It was {str(number)}")
print(f"You guessed the correct number in {str(count)} guesses!")
It looks like this when it is run:
읽어 주셔서 감사합니다. 여기서 새로운 것을 배웠기를 바랍니다.
Reference
이 문제에 관하여(난수 게임 - Python), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/vulcanwm/random-number-game-python-476g텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)