Place for questions and studies
It’s good that you came to the Stack Exchange, even if you are an beginner.
It will help you learn more about Python, and any other programming languages you want.
It can be difficult at first, but keep looking for more information and you will get better over time.
Look also at Stack Overflow, which is for codes with errors.
Another version of the code with explanations.
This is a version of your program with explanations about functions and details that are basic and you can learn, so read it slow, don't rush.
program_run = True
#Dont put 1-letter or 1-word names on variables,
#it will be harder to remenber what
# it does on the code.
#and use "_" between words,
try:
#You use this function when knows this part
# can raise an Exception, so you can try fix.
#if you use an "try:", you need to use an "except:".
import random
except ImportError:
#There are many python defalt Exceptions, like:
# ImportError, ValueError, OverflowError, and many others.
print("Nescessary module(s) not found.\nNeeds: random.")
program_run = False
#This is something you can make, so if someone tries to run this code,
# but doesn't have the nescessary modules,
# the program dont sudenlly crash, and tells what modules it needs to run.
#allways try to make the functions up in the code, under the modules imported.
def dice_game_code(Dice_faces: int) -> int:
#When creating an function, it's good you make like this:
# 1. Name your function with an good explainer name.
# 2. When putting an Parameter (Like the Dice_faces),
# its good to write the Type that this parameter
# needs to be. In this example, Dice_faces
# needs to be an integer.
# 3. After the end of the () add an "-> 'return type'",
# telling the type of information this function returns.
# if it returns nothing:
# put "None"
# 4. Right under, but into, the function, add an Docstring:
# This is an comment text explaining the Parameters, what returns,
# and what this function do.
# You can make this using """..."""
"""Code for the dice game.
It runs till the dice is the same as the Dice_faces,
wich is the max value it can get.
Dice_faces: It's the total number of faces (in int Type) of the dice.
Return: Returns the number of attempts needed to reach max value (in int Type)."""
attempt = 0
while True:
dice = random.randint(1, Dice_faces)
attempt += 1
if dice == Dice_faces:
#The "return" function is used on User functions to:
# 1. To exit the function with value "None", when the
# "return" is alone.
# 2. To exit the function with some information
# from inside the function. Like this example:
return attempt
print(f"{attempt}º attempt: {dice}")
if __name__ == "__main__":
#This is an barrier that only alloys pass
#when the actual program is running.
#because, if you imports the dice_game_code()
#to an different code, the entire program is read an ran.
#but with this, only what is outside this indentation is read.
if program_run:
#Since the "program_run" has an boolean information,
# the actuall variable is an boolean test.
start_choice = input('Time to go gambling!\nPress [S]tart or [Q]uit!\n> ').lower().strip()
#".lower()", ".strip()", and ".upper()"
# are some methods that you can use on strings, to:
# 1. make all string lower-case
# 2. removes characters in the string
# (if let blank, it only removes all spaces in string)
# 3. make all string upper-case
if start_choice == "s":
while True:
#The dice_game_code() returns an value that i need outside,
# so, to get this value, i need to put it into an variable.
attempt = dice_game_code(20)
# since i have put an Parameter on the function,
# i need to give the information it needs to run.
# otherwise it will raise an exception.
end_text = "average." if attempt <= 5 else "embarrassing."
#you can put If...else statements into variables and lists
#to change then by the enviroment or set an rule to then.
replay_choice = input(f"""It took you {attempt} attempt(s) to get 20... {end_text}
\nWants to try again? (Y/N)\n> """).upper().strip()
if replay_choice == "Y":
continue
break
print("\nBye!\n")
You can copy and paste this code to see it working.
here is the code with no comments, so its better to read the actual code:
program_run = True
try:
import random
except ImportError:
print("Nescessary module(s) not found.\nNeeds: random.")
program_run = False
def dice_game_code(Dice_faces: int) -> int:
"""Code for the dice game.
It runs till the dice is the same as the Dice_faces,
wich is the max value it can get
Dice_faces: It's the total number of faces (in int Type) of the dice.
Return: Returns the number of attempts needed to reach max value (in int Type)."""
attempt = 0
while True:
dice = random.randint(1, Dice_faces)
attempt += 1
if dice == Dice_faces:
return attempt
print(f"{attempt}º attempt: {dice}")
if __name__ == "__main__":
if program_run:
start_choice = input('Time to go gambling!\nPress [S]tart or [Q]uit!\n> ').lower().strip()
if start_choice == "s":
while True:
attempt = dice_game_code(20)
end_text = "average." if attempt <= 5 else "embarrassing."
replay_choice = input(f"""It took you {attempt} attempt(s) to get 20... {end_text}
\nWants to try again? (Y/N)\n> """).upper().strip()
if replay_choice == "Y":
continue
break
print("\nBye!\n")