-1

When I run the following code, it skips to the end and simply prints "Thanks for playing!"

I'm sure it's something super obvious that I've missed, any ideas? I am using Python 2.7.6.

Thanks.

import random

def roll (sides = 6):
    numberRolled = random.randint(1,sides)
    return numberRolled

def main():
    sides = 6
    rolling = True
    while rolling:
        roll_again = raw_input("Press Enter to roll, or Q to quit.")
        if roll_again.lower() != "q":
            numberRolled = roll(sides)
            print ("You rolled a " + numberRolled)

        else:
            rolling = False
print ("Thanks for playing!")
asz
  • 9
  • 1

3 Answers3

1

Python in itself has no concept of a main method. When it reads your code, it imports random, defines a method named roll, defines another method named main, then prints "Thanks for playing". It does nothing else, unless you tell it to

If you want to call main(), you'll need to do this yourself. Traditionally (to work with other code that might want to import yours as a module), it would look like this:

import random

def roll():
    ...

def main():
    ...

if __name__ == '__main__':
    main()
    print("Thanks for playing")

That will check if the module name is __main__ (which is true for the main script) and call your main method

3Doubloons
  • 2,088
  • 14
  • 26
0

You need to add if __name__ == '__main__:', and call main() from there:

import random

def roll (sides = 6):
    numberRolled = random.randint(1,sides)
    return numberRolled

def main():
    sides = 6
    rolling = True
    while rolling:
        roll_again = raw_input("Press Enter to roll, or Q to quit.")
        if roll_again.lower() != "q":
            numberRolled = roll(sides)
            print ("You rolled a " + numberRolled)

        else:
            rolling = False

if __name__ == '__main__':
    main()
    print ("Thanks for playing!")

For details as to why and how it works, please see:
- what-does-if-name-main-do
- tutorial name == main
- python documentation

Community
  • 1
  • 1
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
0

You need to run main

if __name__ == "__main__":
        main()
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223