Hi
I thought iI would try to teach myself how to program, so sorry if this has been asked before but I could find it.
What I am trying to do is limit an input to of an int to 50 or less with out the program throwing up an error. This is what i have so far :-

#start of input loop
while True:
try:
deep = int(raw_input('Enter Depth in meters :- ',))
break
except ValueError:
print 'Enter whole meters only!(round up if needed!)'
#end of loop

I want deep <= 50 and if it not to loop back to the input line.
Thanks

Edited 5 Years Ago by ali13: n/a

I would do something like:

depth=int(input('Depth: '))
def depther():
    global depth
    try:
        if depth <=50 and depth>0:
            print(depth)
        else:
            while depth>50 or depth<0:
                print('Incorrect range')
                depth=int(input('Depth: '))
            print(depth)
    except:
        print('Invalid input')
        depth=int(input('Depth: '))
        if depth <=50 and depth>0:
            print(depth)
        else:
            while depth>50 or depth<0:
                print('Incorrect range')
                depth=int(input('Depth: '))
            print(depth)

I defined depth test as a function so it can be reused. Also I used except to cover any error, you may not wish to do this, it's just my preference in cases like this. Now that you know this how do you suppose you would prevent the user from entering a negative depth?

Edited 5 Years Ago by pyguy62: n/a

my code only allows the user to mess up by entering an incorrect value once, how would you make it more?

Here is another way

def raw_inputs(msg):
    while True:
        yield raw_input(msg)
        

def ask_depth():
    for attempt in raw_inputs("Enter depth in meters:- "):
        try:
            d = int(attempt)
            if d < 0 or d > 50:
                raise ValueError
            return d
        except ValueError:
            print("Invalid value: depth is a number in [0, 50]")

if __name__ == "__main__":
    depth = ask_depth()
    print(depth)

""" my output -->
Enter depth in meters:- sldfsdf
Invalid value: depth is a number in [0, 50]
Enter depth in meters:- sdfsdf
Invalid value: depth is a number in [0, 50]
Enter depth in meters:- -5
Invalid value: depth is a number in [0, 50]
Enter depth in meters:- 57
Invalid value: depth is a number in [0, 50]
Enter depth in meters:- 65
Invalid value: depth is a number in [0, 50]
Enter depth in meters:- 35
35
"""

Use raw_input() in python 2 and input() in python 3

Edited 5 Years Ago by Gribouillis: n/a

@Gribouillis how does it give more than one attempt after the value error was raised with yours? I'm just curious, I've never seen it that way before.

Edited 5 Years Ago by pyguy62: n/a

@Gribouillis how would he give more than one attempt after the value error was raised with yours? I'm just curious, I've never seen it that way before.

Because my generator raw_input[b]s[/b]() asks indefinitely the same question and generates the sequence of user answers.

okay, I understand, I've just yet to use the yield function. Is it essentially the same as return? Also, how would it be possible to be done otherwise?

okay, I understand, I've just yet to use the yield function. Is it essentially the same as return? Also, how would it be possible to be done otherwise?

You can do it otherwise with

while True:
    attempt = raw_input("...")
    etc

but I like to use generators.

Generators are very nice and powerful. There are a few great articles by David Beazley on generators, see here for a starting point http://www.dabeaz.com/generators/

preferred method:

okay=False
depth=0
def dcheck():
    global depth
    global okay
    while not okay:
        try:
            depth=int(input('Enter depth in range(0,50): '))
            if depth in range(0,51):
                print(depth)
                okay=True
                return okay
            else:
                print('Invalid Depth')
                okay=False
        except:
            print('Invalid input')
    
dcheck()
Comments
Common.... terrible code, to be honest.

Hi
I thought iI would try to teach myself how to program, so sorry if this has been asked before but I could find it.
What I am trying to do is limit an input to of an int to 50 or less with out the program throwing up an error. This is what i have so far :-

#start of input loop
while True:
try:
deep = int(raw_input('Enter Depth in meters :- ',))
break
except ValueError:
print 'Enter whole meters only!(round up if needed!)'
#end of loop

I want deep <= 50 and if it not to loop back to the input line.
Thanks

Ali I see you messed up with the code button, just hit it once and

'you\'ll be able to' input('your code here: ')

this will make it easier to read. Hope we were able to help you.

Edited 5 Years Ago by pyguy62: n/a

preferred method:

dcheck()

Thanks for your helping spirit, but now you are giving terrible example, and as this is present in most of your code I think you need some beating to learn the do of Python.

So I will analyse this piece of code (changing it better), take this in positive advice. I want to just make you stop doing these stupid things.

  1. Do not use global variables if you are not forced to
  2. return the real result from function instead of global variable
# these two definitions are not global constants, they should go to main routine at end
#okay=False # Yes this code is not okay
#depth=0 # and what would this statement accomplish

# it is good to put empty line between definitions
def dcheck():
    #global depth # NOT
    #global okay  # OKAY
    while True: # return takes us out of loop
        try:
            depth = int(input('Enter depth in range(0,50): '))
            if 0 <= depth < 51: # comparision is clearer and more efficient
                # separate output from the processing, not correct place here (prompt is Ok, however)
                #print(depth)
                #okay=True
                return depth # changed from okay
            else:
                print('Invalid Depth')
                #okay=False
        except ValueError: # without type is NOT OKAY: you stop for example ctrl-C breaking of the program
            print('Invalid input')

print('Correct input was: %i' % dcheck())

For my way of doing thing, with not magic numbers in functions see my code snippet on "Jail Input Functions"

Edited 5 Years Ago by pyTony: n/a

if you return depth from this function, although it's not a global variable, can it still be used elsewhere in the code? I've never seen the function being called to show the value from it as you did at the end.
also, ouch, my ego :-o

Edited 5 Years Ago by pyguy62: n/a

@pyguy62: You use the return value from other function or main code for value of variable or return value is printed like in my edited post.

Must wait until your bruises go away to start bashing those instance referring classes of yours :S

I'm working on those instance referring classes, I'm just not sure how to access methods otherwise, I guess my learning material is poor. Whenever I try to refer to another classes methods without the instance I get an error claiming the Class has no such method.

I'm working on those instance referring classes, I'm just not sure how to access methods otherwise, I guess my learning material is poor. Whenever I try to refer to another classes methods without the instance I get an error claiming the Class has no such method.

Choose some prep up from tasks from beginners sticky thread of Vegaseat, maybe it hurts your pride, but I warmly recommend it. Or you can do math code for projecteuler.net (I am tonyjv there, inactive for some months).

Choose some prep up from tasks from beginners sticky thread of Vegaseat, maybe it hurts your pride, but I warmly recommend it. Or you can do math code for projecteuler.net (I am tonyjv there, inactive for some months).

How should I invoke another classes methods without using the instance?

thanks for the help.I've got loads to learn (the last time I thought about trying to program was with a dragon 32 and it used basic!).
but I am having fun learning.

@Gribouillis thanks your code seems to work best as you it seems to be what I was trying to achive as you can only enter whole numbers(int) and doesn't crash when a letter is entered.

This question has already been answered. Start a new discussion instead.