[Tutor] Issue w/ while loops
Hej there, I want to use a while loop in a program (version used: Python 3.3.0), and I expect it to loop unless the user enters an integer or a floating-point number instead of a string. print("TIME TRACKING") hours_worked = input("How many hours did you work today? ") while hours_worked != str() or int(): hours_worked = input("Can't understand you. Please enter a number! ") print("you worked " + str(hours_worked) + " hours today.") When I run the program, it keeps looping even if the condition is met. How do I need to modify the program on the 3rd line so that it stops looping when the user enters a floating-point number or an integer? Thank you! Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue w/ while loops
Rafael Knuth wrote: > Hej there, > > I want to use a while loop in a program (version used: Python 3.3.0), > and I expect it to loop unless the user enters an integer or a > floating-point number instead of a string. > > print("TIME TRACKING") > hours_worked = input("How many hours did you work today? ") > while hours_worked != str() or int(): > hours_worked = input("Can't understand you. Please enter a number! ") > > print("you worked " + str(hours_worked) + " hours today.") > > When I run the program, it keeps looping even if the condition is met. > How do I need to modify the program on the 3rd line so that it stops > looping when the user enters a floating-point number or an integer? Let's have a look at what input() gives: >>> input("How many hours did you work today? ") How many hours did you work today? 1234 '1234' A human being would understand that I was either very busy or that I lied, but from Python's point of view this is just a str containing some digits, not an actual number. Now let's see str() actually is: >>> str() '' An empty string. Now int(): >>> int() 0 The integer 0. So your loop is while "1234" != "" or 0: ... and following Python's precedence rules it is evaluated as while ("1234" != "") or 0: ... With that information, can you work out with what input your script would terminate (or not enter) the while loop? Now how can we find out if the string can be converted to a valid (non- negative) float? You have to check the characters and verify that there are at most one ".", at least one digit and no other non-digits. While it would be a good exercise for you to try and implement the above check there is a simpler approach: just try the conversion and catch the potential error: valid = True # we are optimists try: hours_worked = float(hours_worked) except ValueError: valid = False # only executed when the string is not a valid float Try to integrate this into your script and come back here if you run into problems. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue w/ while loops
On Thu, 21 Nov 2013 12:00:31 +0100, Rafael Knuth wrote: hours_worked = input("How many hours did you work today? ") while hours_worked != str() or int(): hours_worked = input("Can't understand you. Please enter a number! ") There are two problems with your conditional expression. First is your use of "or" Suppose you were trying to loop until the user entered "7" or "X". You couldn't use while value == "7" or "X": You would need while value == "7" or value == "X": The "or" operator is used to combine two boolean expressions, and since "X" is truthie, the entire expression would be true. The second problem is that str() and int() are used to convert values, not somehow analyze them. WIthout arguments to convert, they produce default values. Int() will produce a zero integer, and I assume str() will produce the empty string. Neither is what you want to compare. What you need instead is a technique that'll analyze a string to see whether it'll convert to an int or float. Best way to do that is to try to convert it, and see if an exception is thrown. while True: try: hw = float(hours_worked) except xxx as ex: hours_worked = input("try again") -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue w/ while loops
On Thu, Nov 21, 2013 at 9:00 PM, Rafael Knuth wrote: > Hej there, > > I want to use a while loop in a program (version used: Python 3.3.0), > and I expect it to loop unless the user enters an integer or a > floating-point number instead of a string. > > print("TIME TRACKING") > hours_worked = input("How many hours did you work today? ") > while hours_worked != str() or int(): > hours_worked = input("Can't understand you. Please enter a number! ") > > print("you worked " + str(hours_worked) + " hours today.") > > When I run the program, it keeps looping even if the condition is met. > How do I need to modify the program on the 3rd line so that it stops > looping when the user enters a floating-point number or an integer? There are two fundamental mistakes in your program: 1. The input() function always returns a string. So, there is no way to check directly whether the user has entered a number or a string. 2. hours_worked != str() or int() does not do what you want to do. In Python, str() creates a new string object and similarly int() creates an integer object, 0. So, to check whether the input is an integer or float, here is an idea: >>> def check_input(user_input): ... try: ... user_input = float(user_input) ... except ValueError: ... return 'Invalid input' ... else: ... return user_input ... >>> check_input('a') 'Invalid input' >>> check_input('1.5') 1.5 >>> check_input('1') 1.0 The idea above is basically, you convert the input (a string) to a float. If the input is a number, 1.5 or 1, the check_input() function will return the numeric equivalent. However, if the number is a string, it returns invalid input. You could make use of this in your program above. Hope that helps. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there a package to "un-mangle" characters?
On 21/11/2013 20:04, Albert-Jan Roskam wrote: Hi, Today I had a csv file in utf-8 encoding, but part of the accented characters were mangled. The data were scraped from a website and it turned out that at least some of the data were mangled on the website already. Bits of the text were actually cp1252 (or cp850), I think, even though the webpage was in utf-8 Is there any package that helps to correct such issues? (I tried looking for one but it doesn't really help that there is such a thing as name mangling! ;-) This comes pretty close though: https://gist.github.com/litchfield/1282752 1) Would something like this help https://pypi.python.org/pypi/charset/1.0.1 ? 2) Surely this topic is too advanced for a tutor mailing list? -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue w/ while loops
Hej there, @David @Peter @Amit: Thank you so much - you guys helped me understand my misconceptions and I learned a couple new things. On Thu, Nov 21, 2013 at 12:44 PM, Amit Saha wrote: > On Thu, Nov 21, 2013 at 9:00 PM, Rafael Knuth wrote: >> Hej there, >> >> I want to use a while loop in a program (version used: Python 3.3.0), >> and I expect it to loop unless the user enters an integer or a >> floating-point number instead of a string. >> >> print("TIME TRACKING") >> hours_worked = input("How many hours did you work today? ") >> while hours_worked != str() or int(): >> hours_worked = input("Can't understand you. Please enter a number! ") >> >> print("you worked " + str(hours_worked) + " hours today.") >> >> When I run the program, it keeps looping even if the condition is met. >> How do I need to modify the program on the 3rd line so that it stops >> looping when the user enters a floating-point number or an integer? > > There are two fundamental mistakes in your program: > > 1. The input() function always returns a string. So, there is no way > to check directly whether the user has entered a number or a string. > 2. hours_worked != str() or int() does not do what you want to do. In > Python, str() creates a new string object and similarly int() creates > an integer object, 0. Got you, thank you for the clarification. def check_input(user_input): > ... try: > ... user_input = float(user_input) > ... except ValueError: > ... return 'Invalid input' > ... else: > ... return user_input > ... check_input('a') > 'Invalid input' check_input('1.5') > 1.5 check_input('1') > 1.0 > > The idea above is basically, you convert the input (a string) to a > float. If the input is a number, 1.5 or 1, the check_input() function > will return the numeric equivalent. However, if the number is a > string, it returns invalid input. You could make use of this in your > program above. > > Hope that helps. It definitely does! I am completely new to programming, and I am taking a Python course at Codecademy. In addition to that, I write tiny, little throw-away programs along the way in order to get more practice. The concept of try/except/else was new to me and it's extremely valuable to know how make use of it. I'm only stuck at one point: How do I loop back to the beginning in case the user input is invalid? I want the program to loop until the user enters a value that is either a float or an int. None of my code modifications gave me the desired result. In case the user input is correct, I can move on and analyze it as I figured out, for example: print("TIME TRACKING") hours_worked = input("How many hours did you work today? ") try: hours_worked = float(hours_worked) except ValueError: print ("Invalid input") if hours_worked < 24: print("You must be a human.") else: print("You must be a cyborg.") All the best, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue w/ while loops
On 21/11/13 13:17, Rafael Knuth wrote: I'm only stuck at one point: How do I loop back to the beginning in case the user input is invalid? Look at Peter's example. He set a variable to false when the input was wrong. You can check that value in your while loop. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there a package to "un-mangle" characters?
On Thu, Nov 21, 2013 at 3:04 PM, Albert-Jan Roskam wrote: > > Today I had a csv file in utf-8 encoding, but part of the accented > characters were mangled. The data were scraped from a website and it > turned out that at least some of the data were mangled on the website > already. Bits of the text were actually cp1252 (or cp850), I think, > even though the webpage was in utf-8 Is there any package that helps > to correct such issues? The links in the Wikipedia article may help: http://en.wikipedia.org/wiki/Charset_detection International Components for Unicode (ICU) does charset detection: http://userguide.icu-project.org/conversion/detection Python wrapper: http://pypi.python.org/pypi/PyICU http://packages.debian.org/wheezy/python-pyicu Example: import icu russian_text = u'Здесь некий текст на русском языке.' encoded_text = russian_text.encode('windows-1251') cd = icu.CharsetDetector() cd.setText(encoded_text) match = cd.detect() matches = cd.detectAll() >>> match.getName() 'windows-1251' >>> match.getConfidence() 33 >>> match.getLanguage() 'ru' >>> [m.getName() for m in matches] ['windows-1251', 'ISO-8859-6', 'ISO-8859-8-I', 'ISO-8859-8'] >>> [m.getConfidence() for m in matches] [33, 13, 8, 8] ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Is there a package to "un-mangle" characters?
Hi, Today I had a csv file in utf-8 encoding, but part of the accented characters were mangled. The data were scraped from a website and it turned out that at least some of the data were mangled on the website already. Bits of the text were actually cp1252 (or cp850), I think, even though the webpage was in utf-8 Is there any package that helps to correct such issues? (I tried looking for one but it doesn't really help that there is such a thing as name mangling! ;-) This comes pretty close though: https://gist.github.com/litchfield/1282752 Thanks in advance! Regards, Albert-Jan ~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor