Erstellen Sie einen Würfelwurfsimulator in Python
Najwa Riyaz
18 Juli 2021
Python
Python Number

Um einen Würfelwurfsimulator in Python zu erstellen, verwenden wir die Funktion random.randint()
, die Zufallszahlen im Zahlenbereich von 1 bis 6 wie folgt generiert.
random.randint(1, 6)
Erstellen Sie einen Würfelwurfsimulator in Python mit random.randint(1,6)
Mit der Funktion random.randint()
können wir in Python einen Würfelwurfsimulator erstellen. Die Syntax der Funktion ist wie folgt.
random.randint(x, y)
Dementsprechend generiert es eine zufällige ganze Zahl zwischen x
und y
. Im Beispiel des Würfelsimulators
x
ist 1 und y
ist 6.
Unten ist ein Beispiel.
import random
print("You rolled the following number", random.randint(1, 6))
Damit der Benutzer wählen kann, ob er weiter würfelt oder nicht, können wir random.randint(1,6)
wie folgt in eine while
-Schleife setzen.
from random import randint
repeat_rolling = True
while repeat_rolling:
print("You rolled the following number using the Dice -", randint(1, 6))
print("Do you wish to roll the dice again?")
repeat_rolling = ("y" or "yes") in input().lower()
Wenn der Benutzer das Würfeln beenden möchte, sollte er die while
-Schleife verlassen.
Ausgabe:
You rolled the following number using the Dice - 2
Do you wish to roll the dice again?
y
You rolled the following number using the Dice - 4
Do you wish to roll the dice again?
y
You rolled the following number using the Dice - 5
Do you wish to roll the dice again?
n
Genießen Sie unsere Tutorials? Abonnieren Sie DelftStack auf YouTube, um uns bei der Erstellung weiterer hochwertiger Videoanleitungen zu unterstützen. Abonnieren