Testing for a number input while loop condition

This is the place for queries that don't fit in any of the other categories.

Testing for a number input while loop condition

Postby sc25893 » Thu Jun 27, 2013 8:39 pm

Hi everyone,

I am messing around with try/except and have come up with this:

Code: Select all
def print_user_input(your_number):
    print("You entered {0}".format(your_number))

a_number = input("Please enter a number: ")

while True:
    try:
        num = int(a_number)
        print_user_input(num)
        break
    except ValueError:
        print("You need to enter a number")
        a_number = input("Please try again: ")

print("Exit program...")


My question is, instead of using the break statement, what condition can I use in the loop itself in order to exit when a number has been entered? My info source says there are always ways to do this without break/continue, I can't seem to find a way though.

Any pointers are much appreciated. Thanks.
sc25893
 
Posts: 23
Joined: Sat May 18, 2013 2:51 pm

Re: Testing for a number input while loop condition

Postby metulburr » Thu Jun 27, 2013 8:53 pm

Code: Select all
def print_user_input(your_number):
    print("You entered {0}".format(your_number))

a_number = input("Please enter a number: ")

run = True
while run:
    try:
        num = int(a_number)
        print_user_input(num)
        #break
        run = False
    except ValueError:
        print("You need to enter a number")
        a_number = input("Please try again: ")

print("Exit program...")

run will be true and make the loop continue, untill it is False. The only time is becomes false is if the try block is fully executed without exception, which in this case has to convert a_number to int()
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1476
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Testing for a number input while loop condition

Postby sc25893 » Thu Jun 27, 2013 9:06 pm

I had considered doing it this way but I thought it was a bit long winded compared to using break. However, if this is how it's done the python way, then so be it.

Thanks for the speedy reply :)
sc25893
 
Posts: 23
Joined: Sat May 18, 2013 2:51 pm

Re: Testing for a number input while loop condition

Postby metulburr » Thu Jun 27, 2013 10:32 pm

I always use while True: and break out of it. In fact i avoid using conditions in while loops if i can.
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1476
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Testing for a number input while loop condition

Postby sc25893 » Fri Jun 28, 2013 4:27 pm

metulburr wrote:I always use while True: and break out of it. In fact i avoid using conditions in while loops if i can.


That's interesting to know, an explanation as to why would be helpful (whether it's performance or just personal preference), but of course it's up to you whether to reply or not. Thanks for the info.
sc25893
 
Posts: 23
Joined: Sat May 18, 2013 2:51 pm

Re: Testing for a number input while loop condition

Postby metulburr » Fri Jun 28, 2013 4:53 pm

I am not aware of any performance increase between the two. I do it for the purpose of keeping away of the C-like structure of while i < 10: kind of stuff. In that case i wouldnt use a while loop anyways, Normally the while loops with counters can be replaced in python with for loops and range()

for example if your using a while loop like this:
Code: Select all
i = 0
while i < 10:
    print(i)
    i += 1

i would replace it with:
Code: Select all
for i in range(10):
    print(i)
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1476
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Testing for a number input while loop condition

Postby sc25893 » Fri Jun 28, 2013 5:13 pm

I am enjoying python a lot and tbh, I'm also getting a whole lot more learning done compared to my painfully slow progress in c++.

Code: Select all
for i in range(10):
    print(i)


The python for loop is beautifully to the point!

Code: Select all
#include <iostream>

int main()
{
    for(int i = 0; i < 10; ++i)
    {
        std::cout << i << std::endl;
    }
}


Now that's long winded!

Thanks.
sc25893
 
Posts: 23
Joined: Sat May 18, 2013 2:51 pm

Re: Testing for a number input while loop condition

Postby ochichinyezaboombwa » Fri Jun 28, 2013 9:16 pm

Note that although Python's for loops are usually shorter that's not a big difference.
a) you don't need the inner {}s in your C++ example;
b) I personally think that cout is a sick idea and always use printf instead.
c) you cheated because you have main() in C++ but not in Python.
So the actual difference is just two {} lines surrounding main()'s code.

Also note that the construct
Code: Select all
for i in range(N)

means three things:
a) create a list of length N;
b) populate it with numbers 0...N-1;
c) iterate through the list.

At least it's the way Python 2.x works.

So it is going to be very, very-very inefficient for a big N.

___
On a higher level: if you can, learn both languages. You will appreciate them both later. Also, knowing C++ will show you how Python actually works.
ochichinyezaboombwa
 
Posts: 200
Joined: Tue Jun 04, 2013 7:53 pm

Re: Testing for a number input while loop condition

Postby sc25893 » Sat Jun 29, 2013 9:43 am

Hi, thanks for the extra info. I am doing Java in October for a year as part of my degree. With this in mind, I put C++ on a back burner because I just wasn't learning the basics with any haste whatsoever. Python has been perfect for that and hoping the OO stuff will set me up better for Java. Also, I'm a mature student so I'm pretty behind on the programming compared to some of the younger people out there. Of course I will go back to C++ as I have read it plays quite nicely with Python.

Only time (and a bucket load of practice) will tell ;)
sc25893
 
Posts: 23
Joined: Sat May 18, 2013 2:51 pm

Re: Testing for a number input while loop condition

Postby ochichinyezaboombwa » Sat Jun 29, 2013 5:49 pm

Ok, good luck, and take care of your fingers (I have reasons to hate Java:-)). BTW, here's my answer to your original question:
Code: Select all
def get_int():
    while True:
        a_number = raw_input("Please enter an int: ")
        # raw_input because I don't use Python 3.x (...)
        try:
            return int(a_number)
        except ValueError:
            print("You need to enter an int")
ochichinyezaboombwa
 
Posts: 200
Joined: Tue Jun 04, 2013 7:53 pm

Re: Testing for a number input while loop condition

Postby sc25893 » Sat Jun 29, 2013 8:04 pm

Thanks :)
sc25893
 
Posts: 23
Joined: Sat May 18, 2013 2:51 pm


Return to General Coding Help

Who is online

Users browsing this forum: conor100, W3C [Linkcheck] and 3 guests