Python Forum

Full Version: [Help] Beginner's code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey there, started learning today and i'm currently trying to make an '8 ball' from a challenge online.
I'm trying to make it so when the player says NOT to terminate the program, and keep the game going, it will return to the starting point.
Also, would love to get some advice on how to get the code more efficient and tidy for the future :)

import random
import time

list = ["It is certain",
           "It is decidedly so",
           "Without a doubt",
           "Yes definitely",
           "You may rely on it",
           "As I see it", " yes",
           "Most likely",
           "Outlook good",
           "Yes",
           "Signs point to yes",
           "Reply hazy try again",
           "Ask again later",
           "Better not tell you now",
           "Cannot predict now",
           "Concentrate and ask again",
           "Don't count on it",
           "My reply is no",
           "My sources say no",
           "Outlook not so good",
           "Very doubtful"]
int = 1
def Interface():
    print("Calculating..")
    time.sleep(3)
    return ("\n" + random.choice(list) + "\n")

while True:
    if int == 1:
        print("Start a new game by and ask a question")
        user_input = input("> ")
        if user_input[-1] != "?":
            print("You should ask in a form of a question..")
        else:
            print(Interface())
            int += 1
    if int != 1:
        print("Finish the game? (Yes/No)")
        user_answer = input("> ")
        if (user_answer.lower() == "yes"):
            print("Goodbye")
            break;
        if (user_answer.lower() == "no"):
            int == 1 
            
You can control the flow better if you write a higher level code structure, for example
def play_game():
    while True:
        display_welcome_to_the_new_game()
        while True:
            process_one_question()
            if we_want_to_quit():
                say_goodbye()
                return
play_game()
Now you have smaller independent functions to write.

About the style: don't use well known words from the python library such as 'int' or 'list' for variable names. Use your own names, for example all_answers = [...]
Thanks dude! helped alot
Note that if (user_answer.lower() == "yes"): is equivalent to if user_answer.lower() == "yes":. I only use parentheses in conditions if they get complicated. Same with return ("\n" + random.choice(list) + "\n").