Python Number Guessing
In this article, we are going to make another basic python project on "Number guessing"
Our assumptions:
Now let's begin with the coding part:
1stly we need python's "random" library to choose a number randomly from the given range
import random
Now we will print the total number of changes we want to give the user
print("Total Chances 3")
Now we will generate a random number. For this inbuilt function "randint" is used from a random library. Here rand = random & int = integer number. So, the output will be a random integer number under a given range.
num = random.randint(0,100)
Here the range (0,100) will include the values from 0 to 100 including both 0 & 100.
Let's print the random number for our convenience:
print(num)
Now we will go in the loop for the range of total chances we want to give
for i in range (2,-1,-1):
Here, we have specified 2 because "i" will iterate from 2 to 0 i.e., a total of 3 times and after 1st input is the wrong user will have remaining chances of 2. this can be seen easily in the output
Inside The Loop:
领英推荐
x = int(input("\nGuess the number between 0 to 100: "))
if x > num:
print("Fortunately, you guessed it bigger")
print("Number of chances left: ",i)
elif x == num:
print("Yep, you guess it correct. Congo!!")
else:
print("Nope, you guessed it smaller")
print("Number of chances left: ",i)
End of Loop
Furthermore, if the user fails to guess the number, the system will give output:
if x!=num:
print("The Secret Number is: ",num)
print("Number of chances left: ",i)
break
(OPTIONAL) Some Designing in the beginning:
print("*********************************")
print(" WELCOME")
print(" The Number Guessing Game")
print("*********************************")
Our complete code looks like this:
print("*********************************")
print(" WELCOME")
print(" The Number Guessing Game")
print("*********************************")
import random
print("Total chances 3")
num = random.randint(0,100)
print(num)
for i in range (2,-1,-1):
x = int(input("\nGuess the number between 0 to 100: "))
if x > num:
print("Fortunately, you guessed it bigger")
print("Number of chances left: ",i)
elif x == num:
print("Yep, you guess it correct. Congo!!")
print("Number of chances left: ",i)
break
else:
print("Nope, you guessed it smaller")
print("Number of chances left: ",i)
if x!=num:
print("The Secret Number is: ",num)
Output:
Here is the link to my Github Profile
Hope you all find the content useful. Have a good time
Quality Engineer @IBM | AWS Certified | Azure Certified | SAFe 6 Certified | ISTQB Agile Tester Certified | Salesforce AI Certified | Salesforce Associate Certified | Lean Six Sigma & RPA Dynamics Certified
3 年Great work buddy??