1

I have a while loop like so:

while True:
    try:
        h = int(raw_input("Please Enter your altitude in metres > "))
        if h > 0 and h < 11000:
            phase = 'Troposphere'
            break
    except ValueError:
            print 'Your entered value contained letters or punctuation. Please enter a numerical value.'

and later I want to use the values for h and phase but my IDE is telling me it cannot be defined. The values are being used in a calculation and the phase is printed.

2
  • Do you want to store all the 'h'/phase values while looping, or just the last one ? Commented Feb 28, 2015 at 22:29
  • What is the exception you see in IDE? Commented Feb 28, 2015 at 22:33

1 Answer 1

1

Define your variables outside the while block so they can be used outside such block:

h = 0
phase = 0
while True:
    try:
        h = int(raw_input("Please Enter your altitude in metres > "))
        if h > 0 and h < 11000:
            phase = 'Troposphere'
            break
    except ValueError:
            print 'Your entered value contained letters or punctuation. Please enter a numerical value.'
Sign up to request clarification or add additional context in comments.

6 Comments

phase should be a string ''.
The execution will not pass the loop unless h is defined
Python is weak typed so phase can be initialized with a value of any type.
I think you mean dynamically typed
What I meant is that there's mo need to define h before the loop - it is redundant
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.