Number Guessing Game Using Python Streamlit Library
Last Updated :
25 Apr, 2024
The game will pick a number randomly from 1 to 100 and the player needs to guess the exact number guessed by calculating the hint. The player will get 7 chances to guess the number and for every wrong guess game will tell you if the number is more or less or you can take a random hint to guess the number like (2+2=?, 3*3=?) to guess the number. In this article, we will create a number-guessing game using the Python Streamlit Library
Number Guessing Game Using Python Streamlit Library
Below, is the explanation by which we can make a number guessing game using Python Streamlit Library:
Install Necessary Library
First, we need to install the streamlit library, for creating the Number Guessing Game so to install the streamlit library use the below command:
pip install streamlit
Writing Python Code
Below, are the step-by-step implementation of the number-guessing game.
Step 1: Import Libraries and Define Functions
Below, code imports the Streamlit library as 'st' and the random module. It defines a function called 'get_secret_number()' that returns a randomly generated integer between 1 and 100.
Python3
import streamlit as st
import random
def get_secret_number():
return random.randint(1, 100)
Step 2: Generate Secret Number and Initialize Game State
In below code the 'initial_state()' function initializes session variables for the game, setting 'input' to 0, generating the secret number, and initializing attempt count and game over status
Python3
def initial_state(post_init=False):
if not post_init:
st.session_state.input = 0
st.session_state.number = get_secret_number()
st.session_state.attempt = 0
st.session_state.over = False
Step 3: Restarting the Game
In below code 'restart_game()' function resets the game state by calling 'initial_state()' with 'post_init' set to True, then increments the input counter.
Python3
def restart_game():
initial_state(post_init=True)
st.session_state.input += 1
Step 4: Generating a Hint
In below code 'get_hint(number)' function generates a hint for the player based on the secret number provided, utilizing addition, subtraction, or multiplication operations to create a related calculation.
Python3
def get_hint(number):
operation_list = ["+", "-", "*"]
operation = random.choice(operation_list)
if operation == "+":
op1 = random.randint(1, number-1)
op2 = number-op1
return f"{op1}+{op2}=?"
elif operation == "-":
op1 = random.randint(number+1, 100)
op2 = op1-number
return f"{op1}-{op2}=?"
else:
for op1 in range(100, 0, -1):
for op2 in range(1, 101):
if op1*op2 == number:
return f"{op1}*{op2}=?"
Step 5: Main Function
In below code 'main()' function controls the game's flow, displaying the title and interface, managing user input for guessing numbers and hints, and providing feedback on guesses. It terminates the game when the player exhausts attempts or guesses the correct number
Python3
def main():
st.write(
"""
# Guess The Number !!
"""
)
if 'number' not in st.session_state:
initial_state()
st.button('New game', on_click=restart_game)
placeholder, debug, hint_text = st.empty(), st.empty(), st.empty()
guess = placeholder.number_input(
f'Enter your guess from 1 - {100}',
key=st.session_state.input,
min_value=0,
max_value=100,
)
col1, _, _, _, col2 = st.columns(5)
with col1:
hint = st.button('Hint')
with col2:
if not guess:
st.write(f"Attempt Left : 7")
if guess:
st.write(f"Attempt Left : {6-st.session_state.attempt}")
if hint:
hint_response = get_hint(st.session_state.number)
hint_text.info(f'{hint_response}')
if guess:
if st.session_state.attempt < 6:
st.session_state.attempt += 1
if guess < st.session_state.number:
debug.warning(f'{guess} is too low!')
elif guess > st.session_state.number:
debug.warning(f'{guess} is too high!')
else:
debug.success(
f'Yay! you guessed it right ?'
)
st.balloons()
st.session_state.over = True
placeholder.empty()
else:
debug.error(
f'Sorry you Lost! The number was {st.session_state.number}'
)
st.session_state.over = True
placeholder.empty()
hint_text.empty()
if __name__ == '__main__':
main()
Complete Code Implementation
main.py
Python3
import streamlit as st
import random
def get_secret_number():
return random.randint(1, 100)
def initial_state(post_init=False):
if not post_init:
st.session_state.input = 0
st.session_state.number = get_secret_number()
st.session_state.attempt = 0
st.session_state.over = False
def restart_game():
initial_state(post_init=True)
st.session_state.input += 1
def get_hint(number):
operation_list = ["+", "-", "*"]
operation = random.choice(operation_list)
if operation == "+":
op1 = random.randint(1, number-1)
op2 = number-op1
return f"{op1}+{op2}=?"
elif operation == "-":
op1 = random.randint(number+1, 100)
op2 = op1-number
return f"{op1}-{op2}=?"
else:
for op1 in range(100, 0, -1):
for op2 in range(1, 101):
if op1*op2 == number:
return f"{op1}*{op2}=?"
def main():
st.write(
"""
# Guess The Number !!
"""
)
if 'number' not in st.session_state:
initial_state()
st.button('New game', on_click=restart_game)
placeholder, debug, hint_text = st.empty(), st.empty(), st.empty()
guess = placeholder.number_input(
f'Enter your guess from 1 - {100}',
key=st.session_state.input,
min_value=0,
max_value=100,
)
col1, _, _, _, col2 = st.columns(5)
with col1:
hint = st.button('Hint')
with col2:
if not guess:
st.write(f"Attempt Left : 7")
if guess:
st.write(f"Attempt Left : {6-st.session_state.attempt}")
if hint:
hint_response = get_hint(st.session_state.number)
hint_text.info(f'{hint_response}')
if guess:
if st.session_state.attempt < 6:
st.session_state.attempt += 1
if guess < st.session_state.number:
debug.warning(f'{guess} is too low!')
elif guess > st.session_state.number:
debug.warning(f'{guess} is too high!')
else:
debug.success(
f'Yay! you guessed it right ?'
)
st.balloons()
st.session_state.over = True
placeholder.empty()
else:
debug.error(
f'Sorry you Lost! The number was {st.session_state.number}'
)
st.session_state.over = True
placeholder.empty()
hint_text.empty()
if __name__ == '__main__':
main()
# this code is contibuted by shraman jain
Run the Server
To run the server using the below command
streamlit run "script_name.py"
Output:

Video Demonstration
Similar Reads
Number Guessing Game Using Python Tkinter Module
Number Guessing Game using the Python Tkinter module is a simple game that involves guessing a randomly generated number. The game is developed using the Tkinter module, which provides a graphical user interface for the game. The game has a start button that starts the game and a text entry field wh
5 min read
Number guessing game in Python 3 and C
The objective of this project is to build a simple number guessing game that challenges the user to identify a randomly selected number within a specified range. The game begins by allowing the user to define a range by entering a lower and an upper bound (for example, from A to B). Once the range i
4 min read
Create Interactive Dashboard in Python using Streamlit
An interactive and Informative dashboard is very necessary for better understanding our data sets. This will help a researcher for getting a better understanding of our results and after that, a researcher can make some necessary changes for better understanding. Visual Reports is must better than i
6 min read
Turtle Race Game Using Python - Turtle Graphics Library
Turtle graphics is a popular way to introduce programming concepts to beginners. It's a fun and interactive module in Python that lets you create simple drawings and animations using a "turtle" that moves around the screen. In this tutorial, we'll create an exciting turtle race game where you can be
4 min read
Snake Game in Python - Using Pygame module
Snake game is one of the most popular arcade games of all time. In this game, the main objective of the player is to catch the maximum number of fruits without hitting the wall or itself. Creating a snake game can be taken as a challenge while learning Python or Pygame. It is one of the best beginne
15+ min read
PyQt5 - Number Guessing Game
In this article we will see how we can create a number guessing name using PyQt5. The Number guessing game is all about guessing the number randomly chosen by the computer in the given number of chances. Below is how game will look like GUI implementation steps 1. Create a head label to show the gam
4 min read
Streamline Plots in Plotly using Python
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization libra
2 min read
Tic Tac Toe Game using PyQt5 in Python
In this article , we will see how we can create a Tic Tac Toe game using PyQt5. Tic-tac-toe, noughts, and crosses, or Xs and Os is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3Ã3 grid. The player who succeeds in placing three of their marks in a horizonta
5 min read
Typing Speed Test Project Using Python Streamlit Library
Typing Speed Test Project involves typing content with the input field displayed on the screen where we need to type the same content also a timer of 30 seconds runs continuously, and when it reaches zero, our typing speed is displayed on the screen in words per minute (WPM). This article will guide
2 min read
Automatic Tic Tac Toe Game using Random Number - Python
Tic-Tac-Toe is a simple and fun game. In this article, weâll build an automatic version using Python. The twist is that the game plays itself, no user input needed! Players randomly place their marks on the board and the winner is declared when three in a row is achieved.Weâll use:NumPy for managing
3 min read