Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
Sichere ProgrammierungFirst-touch attribution on a cookieless static Nuxt site(21.09.2026 um 02:51 Uhr)
Sichere ProgrammierungWho Is the Customer? It Might Not Be Who Uses the Product(21.09.2026 um 02:57 Uhr)
Sichere ProgrammierungOn My Japanese Team, We Greet Each Other by Saying "You Must Be Tired"(21.09.2026 um 03:06 Uhr)
Sichere ProgrammierungRedis vs Memcached: Complete Comparison(21.09.2026 um 03:16 Uhr)
Sichere ProgrammierungHow Databricks Serverless Compute Cost My Team $14k in One Weekend(21.09.2026 um 03:20 Uhr)
Sichere ProgrammierungStop trying to make Airflow work for Medallion pipelines(21.09.2026 um 03:21 Uhr)
Sichere ProgrammierungI built an app that turns workout videos into actual workouts(21.09.2026 um 03:39 Uhr)
Sichere ProgrammierungFirst-touch attribution on a cookieless static Nuxt site(21.09.2026 um 02:51 Uhr)
Sichere ProgrammierungWho Is the Customer? It Might Not Be Who Uses the Product(21.09.2026 um 02:57 Uhr)
Sichere ProgrammierungOn My Japanese Team, We Greet Each Other by Saying "You Must Be Tired"(21.09.2026 um 03:06 Uhr)
Sichere ProgrammierungRedis vs Memcached: Complete Comparison(21.09.2026 um 03:16 Uhr)
Sichere ProgrammierungHow Databricks Serverless Compute Cost My Team $14k in One Weekend(21.09.2026 um 03:20 Uhr)
Sichere ProgrammierungStop trying to make Airflow work for Medallion pipelines(21.09.2026 um 03:21 Uhr)
Sichere ProgrammierungI built an app that turns workout videos into actual workouts(21.09.2026 um 03:39 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

How to Create a Number-Guessing Game in Python

Reagiere als Erste:r — dein Feedback zählt!

Hello there! 👋

In this guide, you will learn how to build a number-guessing game using basic Python concepts, such as loops, if-else statements, handling inputs, and more. This is inspired by the Number guessing game project in the Roadmap projects section.

Let’s get started! 😎

Creating the game’s function

We would need to create a function to handle the generation of the random number for the user to guess using Python’s random module.

Start by importing the module then create the function using random.randint() within the module to generate a random number between 1 - 100, this is the number the player has to guess and it will be stored in a variable, number_to_guess.

Next, set guessed_correctly var to false to stop the game once the player guessed the right number and set an attempts_limit to make the game more difficult.

import random

def number_guessing_game(attempts_limit=7):
  number_to_guess = random.randint(1, 100)
  guessed_correctly = False
  attempts = 0

Next, use a print statement to welcome your player with some messages and instructions on how to play the game. You can customize this to your preference.

NB: This should be within the function.

  print("Welcome to Number guessing game")
  print("I have selected a number from 1-100, can you guess it?")

Creating the guessing loop

Next, we need to create the core of the game. This will manage the loop that continues until the player guesses the number correctly or reaches their guess limit.

Start by using a while loop to increase the attempt count with each try. If the player doesn't guess correctly, they should be given another turn to guess as long as they haven't exceeded their limit.

  while attempts < attempts_limit and not guessed_correctly:
     guess = int(input("Please add your guess: "))
     attempts +=1

Next, use an if-else statement to compare the player's guess with the random number and provide feedback. If the guess is lower than the correct number, print "too low." If it's too high, print "too high." If it matches the correct number, set guessed_correctly to True, break the loop, and print a congratulations message.

if guess < number_to_guess:
    print("Too low!")
elif guess > number_to_guess:
    print("Too high")
else:
    guessed_correctly = True
    print(f"Congratulations, you guessed the number in {attempts} attempts")

Next, let's add an extra layer of error handling. Users can be unpredictable, and many might try to break your program. For example, if a player decides to use a letter or a decimal number to guess, the program will stop unexpectedly. That's why we need this extra layer.

Using the try-except block, we can catch such an error. It should only accept whole numbers and should send an error message and stop if the player decides to use something else.

  while attempts < attempts_limit and not guessed_correctly:
    try:
      guess = int(input("Please add your guess: "))
      attempts +=1

      if guess < number_to_guess:
        print("Too low!")
      elif guess > number_to_guess:
        print("Too high")
      else:
        guessed_correctly = True
        print(f"Congratulations, you guessed the number in {attempts} attempts")

    except ValueError:
      print("Oops! This is not a valid number, please a whole number")

Once that's done, we move on to the final step. If the player runs out of guesses and hasn't guessed the correct number, display a message saying "Game over" and inform them that they are out of guesses.

  if not guessed_correctly:
    print(f"You are out of guesses, the correct guess was {number_to_guess}")

  print("Game over, Thanks for playing!")

Testing your game

Now that’s all done! Let’s test our game and see if it works. Also, remember to call your function at the bottom of your program to run your program.

number_guessing_game()

Image description

Conclusion

And there you have it! A simple yet fun game in Python that you can create as a beginner. I hope this helps you become more comfortable with key programming concepts like loops, conditionals, and random numbers.

The source code can be found here. If you prefer the video version of this guide, check it out:

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten How to Create a Number-Guessing Game in Python

Thematisch verwandte Begriffe: Create, NumberGuessing, Game, Python · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-93974 | A flaw has been found in SourceCodester Online Reviewer Management Syste…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick