Stumbleine75
Stumbleine75

Reputation: 401

Tell me whats wrong with this python code?

I'm relatively new to coding so please help me out here. The code will only run until the 5th line. This code may be a total babel, but please humor me.

EDIT: There is no exception, nothing happens. After asking me to choose between 1 and 2, the code just stops.

print('This program will tell you the area some shapes')
print('You can choose between...')
print('1. rectangle')
print('or')
print('2. triangle')

def shape():
    shape = int(input('What shape do you choose?'))

    if shape == 1: rectangle
    elif shape == 2: triangle
    else: print('ERROR: select either rectangle or triangle')

def rectangle():
    l = int(input('What is the length?'))
    w = int(input('What is the width?'))
    areaR=l*w
    print('The are is...')
    print(areaR)

def triangle():
    b = int(input('What is the base?'))
    h = int(input('What is the height?'))
    first=b*h
    areaT=.5*first
    print('The area is...')
    print(areaT)

Upvotes: 0

Views: 240

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251166

A better coding style will be putting everything inside functions:

def display():
    print('This program will tell you the area some shapes')
    print('You can choose between...')
    print('1. rectangle')
    print('or')
    print('2. triangle')

def shape():
    shap = int(input('What shape do you choose?'))
    if shap == 1: rectangle()
    elif shap == 2: triangle()
    else:
        print('ERROR: select either rectangle or triangle')
        shape()


def rectangle():
    l = int(input('What is the length?'))
    w = int(input('What is the width?'))
    areaR=l*w
    print('The are is...')
    print(areaR)


def triangle():
    b = int(input('What is the base?'))
    h = int(input('What is the height?'))
    first=b*h
    areaT=.5*first
    print('The area is...')
    print(areaT)

if __name__=="__main__":
    display() #cal display to execute it 
    shape() #cal shape to execute it 

Upvotes: 0

Gareth Latty
Gareth Latty

Reputation: 89097

Your problem is that you have put your code into functions, but never call them.

When you define a function:

def shape():
    ...

To run that code, you then need to call the function:

shape()

Note that Python runs code in order - so you need to define the function before you call it.

Also note that to call a function you always need the brackets, even if you are not passing any arguments, so:

if shape == 1: rectangle

Will do nothing. You want rectangle().

Upvotes: 11

Related Questions