Python Forum
Fundamental understanding-problem regards to while-loops
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Fundamental understanding-problem regards to while-loops
#1
Hi!

Following code is correct and executes without any problems:

while True:
    age = input('Enter your age:\n')
    if age.isdecimal():
        break
    print("Please enter a number for your age.")

while True:
    print("Select a new password (letters and numbers only):")
    password = input()
    if password.isalnum():
        break
    print('Passwords can only have letters and numbers.')
But I want to understand why?
I mean, the while-statements says ' while True', it will loop, as I understand it.
Now regards to this example, the program is supposed to break, when the if-statement is evaluating to the boolean value 'True' and loop if it should evaluate to the boolean value 'False'?
Basically, I would get it when the code at line 1 would say 'while not True'.
Has it maybe to do that regards to boolean algebra following is true:
if a = false and b = true, then a -> b is true?

Or why is it the the prrogram is looping in this case, while the input will be evaluated to 'False'?

regards,
Placebo

Update:

Or maybe i do get the while loops fundamentally wrong and it is like following:
When a while-statement is set to True, the program will execute the code as long as all is evaluated to true.
Only when something is evaluated to False, the code-execution will stop and loop at instructional position where it got stuck (have been evaluated to false), until the input will be evaluated to True.
Only then the program will resume and proceed the execution of the code.
Is it like that, in general?

This example also illustrates well me confusion:
https://gyazo.com/4bf66ea00cd4a5d76842dfb2224830fc

why does the program right away assume that everything is true, without any input?
Reply
#2
The construct while True essentially creates an endless loop - which you may terminate by the break statement. This is a common pattern, e.g., to wait on user input for the properly entered string.

In real life scenarios like that, number of attempts are usually limited, and then for loop is more suitable

for attempts in range(5):
    age = input('Enter your age:\n')
    if age.isdecimal():
        break
    print("Please enter a number for your age.")
else:
    raise Exception('Wrong age in 5 attempts')
Endless loops may also serve to create permanent process/tasks.

(Oct-09-2018, 12:08 PM)Placebo Wrote: Basically, I would get it when the code at line 1 would say 'while not True'.

Oops, missed that statement - loop while not True will be nevere executed, since - as you yourself have stated, while loop is executed till its condition is True
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#3
Hi, thanks a lot for replying - it helps me already quite a lot^^

I would have 2 questions as for your code:
1.) Regards to the first line: 'How on earth python knows what 'attempts' are?
My guess, it cannot know it and it does not matter, since due to the range() methode it will just iterate 5 times, whatever the keyword is, right?

2.) the output of your code after 5 iterations does look like that:

Output:
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> RESTART: C:/Users/kr-ga/AppData/Local/Programs/Python/Python37-32/BOOK_automate_the/Chapter 6/test.py Enter your age: hs Please enter a number for your age. Enter your age: sh Please enter a number for your age. Enter your age: hs Please enter a number for your age. Enter your age: hs Please enter a number for your age. Enter your age: sh Please enter a number for your age. Traceback (most recent call last): File "C:/Users/kr-ga/AppData/Local/Programs/Python/Python37-32/BOOK_automate_the/Chapter 6/test.py", line 7, in <module> raise Exception('Wrong age in 5 attempts') Exception: Wrong age in 5 attempts >>>
Can we somehow change the code, so that python prints ot fpr the user a nice message, such as 'Sorry, too many attempts' before breaking with an 'ugly' error-message after 5 falied attempts?
Reply
#4
If there is question of fundamental understanding then it's always worth to have a look how it's explained in Python documentation:

How while-statement works:

Documentation >>> The Python Language Reference >>> 8. Compound Statements >>> 8.2. The while-statement

How truth-values are tested:

Documentation >>> The Python Standard Library >>> Built-in Types >>> Truth Value Testing
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
(Oct-10-2018, 05:40 AM)Placebo Wrote: Hi, thanks a lot for replying - it helps me already quite a lot^^

I would have 2 questions as for your code:
1.) Regards to the first line: 'How on earth python knows what 'attempts' are?
My guess, it cannot know it and it does not matter, since due to the range() methode it will just iterate 5 times, whatever the keyword is, right?
attempts is a variable assinged by looping over the values returned by range

There's a highly recommended "Loop like a native" video - if standard Python docs are not sufficient for you

(Oct-10-2018, 05:40 AM)Placebo Wrote: 2.) the output of your code after 5 iterations does look like that:

Output:
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ... Enter your age: sh Please enter a number for your age. Traceback (most recent call last): File "C:/Users/kr-ga/AppData/Local/Programs/Python/Python37-32/BOOK_automate_the/Chapter 6/test.py", line 7, in <module> raise Exception('Wrong age in 5 attempts') Exception: Wrong age in 5 attempts >>>
Can we somehow change the code, so that python prints ot fpr the user a nice message, such as 'Sorry, too many attempts' before breaking with an 'ugly' error-message after 5 falied attempts?
Of course; I used raise Exception (nasty habit Tongue of a professional ) - you may just use print
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#6
Thanks both of you - I am already watching the recommended video on looping.
Thanks volcano63 for that hint:)

Right away in the video is an example shown which raises for me a likely very simple
question, but the answer might help my further fundamental understanding.

https://gyazo.com/c3d15731bb33355ef932d49146082646

Basically, I do wonder how and why Python can know that 'i' is a single value from the list?
Is it because a range was targeted at a collection of date (in this case at a list)?
Reply
#7
The example has a couple extra steps that I'll explain at the end.

At the beginning of the loop, we declare a variable:

my_list = ["ketchup", "chicken", "potatoes", "veggies"]

for i in my_list:
Within the body of the loop, we can then reference the variable we declared:

my_list = ["ketchup", "chicken", "potatoes", "veggies"]

for i in my_list:
    print(i)
The variable does not have to be "i"; we can just as easily call it "x", "n", "bobsYourUncle", or "each". In any case, the variable is assigned to the value of the next item in the sequence. For the first iteration over "my_list", "i" is assigned to "ketchup"; when that iteration is done, "i" is reassigned to "chicken" and so forth.

In other languages, you can only perform a for loop with numbers (e.g. in Java: for i := 0; i < 10; i ++ {...} would loop 10 times) and then use the variable "i" as an index (hence "i" often being used) to an array object. So, to iterate over a sequence in Java (or another language), you have to do something like this (though written in Python):

for i in range(len(eww_Java)):
    value = eww_Java[i]
    print(value)
Python simplifies this by iterating over the sequence itself (the list, tuple, etc.) and assigning the variable to the next value in the sequence.
Reply
#8
Thanks, helped a lot!:)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Exporting Stock Fundamental Data to a CSV file with yahoo_fin DustinKlent 2 4,637 Aug-01-2022, 06:08 PM
Last Post: paulyan
  problem with for loops? Darbandiman123 1 1,980 Sep-26-2018, 06:35 PM
Last Post: nilamo
  Need help with understanding for/while loops! WombatHat42 2 2,318 Sep-26-2018, 11:46 AM
Last Post: ThiefOfTime

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020