This is a simple Python program that generate a random number and you have to guess that random number correctly. The Final result will show your number of attempts
Firstly you have to install the Python random module using the command:
This random module can generate random numbers in Python. To use this module you have to import it into your program.
you can import it using a single line of code.
import random
Then, you have to set flag = True for a while condition.
flag = True
In while, we will take a number input from the user to set an upper bound for the game. Even we have to make sure that the input we take from the user is only a numeric value. we will check it using the isdigit() function.
while flag: print("'Welcome to guess game'") num = input(" Type a number for an upper bound:- ") if num.isdigit(): print("Lets Play!") num = int(num) flag = False else: print("invalid input! plases enter number")
We will use the random function by passing two parameters 1. starting point, 2. ending point
secret = random.randint(1,num)
We need to initialize two variable:
1. guess:- "to take input from the user",
2. count:- "to count the number of attempts".
Then, we will check the input given by the user is in numeric format or not. for that, we will use the isdigit() function again.
guess = None count = 1 while guess != secret: guess = input('please type a number between 1 and'+str(num)+" :-") if guess.isdigit(): guess = int(guess)
Finally, we will write a code to check the guess number is correct or not? and how many attempts we need to guess the correct number.
if guess==secret: print("you got it!") else: print('please try again!') count+=1 print('you took = ',count,'guess')
Submitted by Shubham Suresh Chavan (schavanshubham)
Download packets of source code on Coders Packet
Comments