Beginner Python - Expecting user input after true if statement

Viewed 77

I'm very new to coding and I'm looking to receive input from the user only after an if-statement returns true. However this doesn't seem to work, I get to enter just one input after entering either "rectangle" or "triangle" - What is wrong? Thank you in advance

type = input()
pi = 3.14159
area = 0

if type == "square" or "circle":
    side = float(input())
    if type == "square":
        area = side * side
    elif type == "circle":
        area = pi * side * side
elif type == "rectangle" or "triangle":
    side1 = float(input())
    side2 = float(input())
    if type == "rectangle":
        area = side1 * side2
    elif type == "triangle":
        area = (side1 * side2) / 2
print (f"{area:.3f}")    

P.S. - Code is properly indented in the IDE

3 Answers

This will be because of your use of if statments It's an easy error to make, especially if you are new to programing.

Where you have written

if type == "square" or "circle"

First, it will check for type == square. This is fine. However, should that return false, then it will check for the string "circle" being true, as you have not specified what to check it against. Therefore it will always return true and you will never progress to the rectangle / triangle part of the code

The way you can solve this is by changing the if statments to either

if type == "square" or type == "circle":

or

if type in ["square","circle"]:

The second is alot easier when you are checking for multiple values.

The final code should look something like this

type = input("> ")
pi = 3.14159
area = 0

if type in ["square","circle"]:
    side = float(input("> "))

    if type == "square":
        area = side * side
    elif type == "circle":
        area = pi * side * side

elif type in ["rectangle","triangle"]:
    side1 = float(input("> "))
    side2 = float(input("> "))
    
    if type == "rectangle":
        area = side1 * side2
    elif type == "triangle":
        area = (side1 * side2) / 2

print (f"{area:.3f}")    

Nice to see more people getting into programming and coding

Your code should like this

type = input()
pi = 3.14159
area = 0

if type == "square" or type == "circle":
    side = float(input())
    if type == "square":
        area = side * side
    elif type == "circle":
        area = pi * side * side
elif type == "rectangle" or type == "triangle":
    side1 = float(input())
    side2 = float(input())
    if type == "rectangle":
        area = side1 * side2
    elif type == "triangle":
        area = (side1 * side2) / 2
print (f"{area:.3f}")

I know the problem, he always enters the first if, because of the

if type == "square" or "circle":

Python interprets the logical value of "circle" as True. I think what you wanted would be

if type == "square" or type == "circle":

Same thing for the other if.

Related