3 Replies - 1240 Views - Last Post: 17 July 2009 - 04:12 PM Rate Topic: -----

#1 brianmen  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 39
  • Joined: 14-June 09

Having Loop Trouble

Posted 16 July 2009 - 03:53 PM

Hello, I am having trouble with my loop and I cannot figure out how to fix it. Basically, I want the user to enter a number between 1 and 4999. I have attempted to set up a loop that will prevent the user from entering negative numbers, 0, and other invalid entries, but my loop only works once and does not repeat if the user continually enters invalid answers. Does anyone know how to fix this please?

Here is my code:

 ###Collecting start number range
start_number=raw_input("Please enter a starting number no greater than 50,000.")
###Verifying number is between 1 and 5000
start_number= int(start_number)
print start_number
while start_number <1 or start_number >5000:
		if start_number <1 or start_number >5000:
				start_number=raw_input("""Please enter a number greater than 1, but
							   less than 5000.""")
		else: print "You have entered" ,start_number, "as your number."
		break
	
#print "You have entered," ,start_number,"as your start number."

raw_input("Press enter to exit")


Is This A Good Question/Topic? 0
  • +

Replies To: Having Loop Trouble

#2 FreezingDigits  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 24
  • Joined: 17-July 09

Re: Having Loop Trouble

Posted 17 July 2009 - 01:25 AM

Hello brianmen, I stumbled upon your post and decided to help with your program. Unfortunately I am also a beginner so my explanation might not be the best or too accurate for that matter, hopefully a more experienced python programmer can correct any of my mistakes.

So I see you want to make a program which tells the user to input a number and then print out the number, but you want this number to be between 1 and 5000. If the user goes under 1 or over 5000 you want the loop to go back and ask the user to input the number correctly, and this repeats until the user finally decides to input a correct value.

This is what is currently working for me:
def startingNumber():
	start_number=int(input("Please enter a number between 1 and 5000: "))

	while 1:
		if start_number < 1 or start_number > 5000:
			startingNumber()

		else: print("You have entered: %d" % start_number)
		break

if __name__ == "__main__":
	startingNumber()



Sorry if the syntax confuses you as I am using the syntax required for Python 3.x.

K so as you can see from my code I defined a function called "startingNumber()", this function asks the user to input a number between 1 and 5000 which then proceeds to the "while 1:" loop.

In the while loop the program checks if the user entered a valid digit and then prints what they have entered. If the user did not enter a valid digit the program then calls the "startingNumber()" function again which basically makes the whole program start again from the top.

I do not understand
if __name__ == "__main__"
completely yet but what I do know is that it is calling the "startingNumber()" function right when you start the program.

Well I hope that helped at least a little and please correct me if I'm wrong fellow python programmers.

This post has been edited by FreezingDigits: 17 July 2009 - 11:39 AM

Was This Post Helpful? 0
  • +
  • -

#3 code_m  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 24
  • View blog
  • Posts: 202
  • Joined: 21-April 09

Re: Having Loop Trouble

Posted 17 July 2009 - 12:52 PM

To be honest you have a lot to learn yet.

1. You need to learn function defintions ( def )
2. You also need to learn Error handling, unlike other languages, this is very quite basic and used a lot.

Here's what I'd write (I'll try to explain later)
#!/usr/bin/env python

def main():
     start_number = get_int("Input number between 1 and 5000: ", min=1, max=5000)
     ... # now you can do what you want with the number

def get_int(msg, min=0, max=0):
     while True:
          line = input(msg)
          try:
               i = int(line)
               if min <= i <= max: # this catchs when the user inputs anything out of range
                    return i
               else:
                    print "Error: {0} is not between {1} and {2}".format(i, min, max)
          except ValueError: # this catches when the user inputs anything other than an integer number
               print "Error: {0} is not an iteger".format(i)
               continue

if __name__ == "__main__":
     main() #execute the code within main


I'm sure your saying "wow"... but it really isn't that hard, just I introduced you to a lot all at once.

First off functions, you didn't know it, but you did this already. Any code you write outside of a fuction is consider "global" and therefore is part of main()... which is the code that is executed first. there's a lot to functions, but don't worry about it yet. It will make sense once you learn the skill. The avantage here is now your input is completely handling outside of main(), which is nice since you can now evolve your other functions without worring about messing things up totally (there are several reasons, just learn)

Error handling is used for many things, but really is just a special object comparision (everything is an object in python!) that makes sure an object contains something of some type. (in this case you want to force an integer, or a whole number, which raise a ValueError.) Again, this is something you will learn along the way.

I can see you have not learned the magic of format, this is really useful for placing a value (of any type) inside of a string. (a string is always what you want to the user to see). As python is developed, format is modified to make things easier! The basic usage is "string {0} here".format(variable) which will place your variable where index "0" is.

Hope that helps ! (phew...)
Was This Post Helpful? 1
  • +
  • -

#4 brianmen  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 39
  • Joined: 14-June 09

Re: Having Loop Trouble

Posted 17 July 2009 - 04:12 PM

Thanks everyone!!! There is still a lot I don't understand, but I'll get the hang of it eventually. Thank you thank you thank you!!!!!!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1