Python Forum

Full Version: Creating class - name not defined error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I am trying to learn how to create a class by following the toss coin exercise from a textbook but I kept getting the error (NameError: name Coin is not defined). I copied exactly as shown in the texbook and I am using the latest IDLE 3.65. Wonder if anyone could advise me what I did wrong or is it a version compatibility problem. Thanks.
import random

class Coin:

     def __init__(self):
          self.sideup = 'Heads'

     def toss(self):
          if random.ranint(0,1) ==0:
               self.sideup = 'Heads'
          else:
               self.sideup  = 'Tails'

     def get_sideup(self):
          return self.sideup

     def main():
          mycoin = Coin()

          print ('This side is up: ', my_coin.get_sideup())
          print ('I am tossing the coin...')
          my_coin.toss()
          print ('This side is up: ', my_coin.get_sideup())
          
     main()

Noted, thanks.
Pay attention at indentation of you main() function, it must be outside of the Coin class.

import random


class Coin:

    def __init__(self):
        self.sideup = 'Heads'

    def toss(self):
        # Changed to randrange(interval)
        if random.randrange(2) == 0:
            self.sideup = 'Heads'
        else:
            self.sideup = 'Tails'

    def get_sideup(self):
        return self.sideup


def main():
    # Changed to my_coin, like you call after
    my_coin = Coin()

    print('This side is up: ', my_coin.get_sideup())
    print('I am tossing the coin...')
    my_coin.toss()
    print('This side is up: ', my_coin.get_sideup())


main()
Smile thank you so much. Was never aware that indent has an effect.
(Jun-30-2018, 01:30 PM)python_alex Wrote: [ -> ]I am using the latest IDLE 3.65
Can show some small changes,get method removed as is not needed in Python,and trow in f-string as you use 3.6.
I don't like the function name main() i know it's used everywhere in Python,just give a name that fit code better.
import random

class Coin:
    def __init__(self):
        self.sideup = 'Heads'

    def toss(self):
        if random.randrange(2) == 0:
            self.sideup = 'Heads'
        else:
            self.sideup = 'Tails'

def toss_result():
    my_coin = Coin()
    print(f'This side is up: {my_coin.sideup}')
    print('I am tossing the coin...')
    my_coin.toss()
    print(f'This side is up: {my_coin.sideup}')

if __name__ == '__main__':
    toss_result()