St.write not working properly

entered_otp remains empty even after antering a value and it goes with thta empty value why?

Generate and send OTP

if st.button("Generate OTP"):
    if roll_number:
        otp = random.randint(1000, 9999)
        # send_otp(email, otp)
        st.success("OTP has been sent to your email!")

        entered_otp = st.text_input(
            "Enter OTP",

        if st.button("rgre"):

Hi @souvenger

Looking at the code, there appears to be a button nested in a button which would trigger an app rerun (i.e. every widget interaction would cause an app rerun).

In order to prevent this, you can assign values to a session state variable so that it would persist across app reruns.

Hope this helps!

Cant we stop the app re run? Ok so i have to apply some other technique.

Hello @souvenger,

Here’s a revised approach:

import streamlit as st
import random

# Initialize session state variables if they don't exist
if 'otp' not in st.session_state:
    st.session_state.otp = None
if 'otp_sent' not in st.session_state:
    st.session_state.otp_sent = False

# Function to simulate sending an OTP
def send_otp(email, otp):
    # Placeholder for sending OTP logic
    print(f"Sending OTP {otp} to {email}")

roll_number = "YourRollNumber"  # Assuming roll_number is defined or obtained elsewhere

# Generate and send OTP
if st.button("Generate OTP"):
    if roll_number:
        st.session_state.otp = random.randint(1000, 9999)
        # Assuming you have a variable email to send OTP to
        # send_otp(email, st.session_state.otp)
        st.success("OTP has been sent to your email!")
        st.session_state.otp_sent = True
        print(st.session_state.otp)  # For debugging purposes

# If OTP has been sent, display the input field and verify button
if st.session_state.otp_sent:
    entered_otp = st.text_input("Enter OTP", placeholder="XXXX")

    if st.button("Verify OTP"):
        if entered_otp == str(st.session_state.otp):
            st.success("OTP verification successful!")
            st.error("Incorrect OTP, please try again.")

Kind Regards,
Sahir Maharaj
Data Scientist | AI Engineer

P.S. Lets connect on LinkedIn!

➀ Website:
➀ Email:
➀ Want me to build your solution? Lets chat about how I can assist!
➀ Join my Medium community of 30k readers! Sharing my knowledge about data science and AI
➀ 100+ FREE Power BI Themes: Download Now