Glizzy Gobbler
Glizzy Gobbler

Reputation: 1

How to create a variable and assign another value later in a if statement?

I'm trying to make a program that draws a shape to a screen and I'm having problems trying to make the value of shapeAngles equal to a certain value if sides (which is an integer from 3 to 10) is x.

def shapeDrawer():
    # Gets the sum of the angle from the amounts of sides
    shapeAngles = 0
    if sides == 3:
        shapeAngles = 180
    elif sides == 4:
        shapeAngles = 360
    elif sides == 5:
        shapeAngles = 540
    elif sides == 6:
        shapeAngles = 720
    elif sides == 7:
        shapeAngles = 900
    elif sides == 8:
        shapeAngles = 1080
    elif sides == 9:
        shapeAngles = 1260
    elif sides == 10:
        shapeAngles = 1440
    print("Sum of angles in shape is " + str(shapeAngles))

shapeDrawer()

When I inputed 6, I was expecting 720 but I got 0.

Upvotes: 0

Views: 386

Answers (2)

Faraaz Kurawle
Faraaz Kurawle

Reputation: 1148

There might be 2 problems:

  • You said you have inputted the value, but input functions takes input in form of string. So you have to use int(input()) to convert it to a integer or you have check conditions with string i.e if side=='1': prin(1).
  • You haven't used global keyword to make changes or to read a global variable. If your variable is outside the function, you have to use global variable_name to access it inside the function.

I have noticed a pattern in your code that is angle=num_of_side-2*180. So intead of using all that if statements, use

print(f"Sum of angles in shape is {(int(sides)-2)*180}")

Upvotes: 0

Thanos Natsikas
Thanos Natsikas

Reputation: 156

You probably read a string-representation of a number, and you think it's a number.

In your input (wherever this might be), add this before the condition-checking:

input_number = int(input_number)

(standard input is by default string)

Upvotes: 2

Related Questions