0

PYTHON: Trying to calculate the period it takes for a pendulum to swing on different planets, I'm extremely new at this so there may be an easy solution:

def main(): print('Period of a pendulum') Earth_gravity = 9.8 Mars_gravity = 3.7263 Jupiter_gravity = 23.12 print(' ') pen = float(input('How long is the pendulum (m)? ')) if pen < 0: print('illegal length, length set to 1') else: print(' ') main() 

What I want to do is if the value entered is negative for it to be set to "1" and display the message "illegal length, length set to 1" . If it is a positive number then I'll have it do the equation to find out the period of a pendulum swing. I am getting the syntax error message of " if pen < 0: builtins.NameError: name 'pen' is not defined" Thank you!

4
  • put the statement after the main() Commented Sep 16, 2017 at 21:55
  • 4
    Your indentation is off. The if and else need to be indented like the rest of the function body. Commented Sep 16, 2017 at 21:57
  • @MauricioCortazar that won't help, pen is a local variable. Commented Sep 16, 2017 at 22:00
  • @AlexHall you are right Commented Sep 16, 2017 at 22:02

2 Answers 2

2
def main(): print('Period of a pendulum') Earth_gravity = 9.8 Mars_gravity = 3.7263 Jupiter_gravity = 23.12 print(' ') pen = float(input('How long is the pendulum (m)? ')) if pen < 0: print('illegal length, length set to 1') else: print(' ') main() 

Try this: pen variable was outside the function therefore it was not accesible in if statement

Sign up to request clarification or add additional context in comments.

1 Comment

Just check the tick if your query is solved and if you understood your mistake :)
0

You first define a method in which pen is defined:

def main(): print('Period of a pendulum') Earth_gravity = 9.8 Mars_gravity = 3.7263 Jupiter_gravity = 23.12 print(' ') pen = float(input('How long is the pendulum (m)? ')) 

But according to the indentation, you're now trying to use pen outside of main method:

if pen < 0: print('illegal length, length set to 1') else: print(' ') main() 

You can move the if/else into main method or remove the main definition altogether.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.