Joe Doe
Joe Doe

Reputation: 193

Importing function in python

I am trying to create menu where user can choose which part of the program he/she wants to run. When I am importing function computer automatically runs it rather to wait for user input. What shall I do to run function only when called? My code:

    import hangman

    menu = raw_input("""Welcome to Menu, please choose from the following options: 
    1. Hangman game
    2.
    3. 
    4. Exit
    """)

    if menu == 1: 
        hangman()
    elif menu == 2:
        "Something"
    elif menu == 3:
        "Something"
    elif menu == 4:
        print "Goodbye"
    else:
        print "Sorry, invalid input" 

The code for hangman.py looks like that:

import random

words = ["monitor", "mouse", "cpu", "keyboard", "printer",]  

attempts = [] # Stores user input

randomWord = random.choice(words) # Computer randomly chooses the word

noChar = len(randomWord) # Reads number of characters in the word

print randomWord , noChar
print "Hello, Welcome to the game of Hangman. You have to guess the given word. The first word has", noChar, " letters."

def game():    
    guess = raw_input ("Please choose letter")
    attempts.append(guess) # Adds user input to the list
    print (attempts)

    if guess in randomWord: 
        print "You have guessed the letter" 
    else: 
        print "Please try again"


while True:
    game()
    chance = raw_input ("Have a guess")
    if chance == randomWord:
        print "Congratulations, you have won!"
        break

Upvotes: 0

Views: 441

Answers (2)

p99will
p99will

Reputation: 250

So here is the start menu:

import hangman
option = raw_input('1) Start Normal\n2) Quick Start\n3) Default') # '\n' is a new line
if option == '1':
    hangman.main()
elif option == '2':
    hangman.run_hangman('SKIP')
elif option == '3':
    handman.run_hangman('Default User')

Inside your hangman code you want to have it modulated. You should have somthing like this:

def main():
    stuff = raw_input('Starting new game. Please enter stuff to do things')
    run_hangman(stuff)


def run_hangman(options):
    if options == 'SKIP':
        important_values = 5
        vales_set_by_user = 'Player 1'
    else:
        values_set_by_user = options

    rest_of_code()

Upvotes: 0

Lukas Graf
Lukas Graf

Reputation: 32590

Without seeing hangman.py, I would assume that it directly contains the code for running the hangman game, not wrapped in a function. If that's the case, you created a module, no function (yet).

Wrap that code in

def run_hangman():
    # Your existing code, indented by 4 spaces
    # ...

import it like this:

from hangman import run_hangman

and finally call the function like this:

run_hangman()

Upvotes: 1

Related Questions