Bottom Page

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?
Quote
#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.
Quote
#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?
Quote
#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
Placebo likes this post
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
Quote
#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
Placebo likes this post
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.
Quote
#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)?
Quote
#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.
Placebo likes this post
Quote
#8
Thanks, helped a lot!:)
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  For loops, strings and printing words with even characters Drone4four 8 210 Oct-05-2018, 09:23 AM
Last Post: volcano63
  Nesting loops more than 20 RtjShreyD 2 74 Oct-05-2018, 08:07 AM
Last Post: Larz60+
  Old brain - New Language - Question on loops sailingbikeruk 6 141 Oct-03-2018, 08:27 PM
Last Post: nilamo
  problem with for loops? Darbandiman123 1 62 Sep-26-2018, 06:35 PM
Last Post: nilamo
  Need help with understanding for/while loops! WombatHat42 2 94 Sep-26-2018, 11:46 AM
Last Post: ThiefOfTime
  Cursors and loops Clark 1 66 Sep-26-2018, 04:45 AM
Last Post: Clark
  nested for loops glob devenuro 3 143 Sep-20-2018, 09:54 PM
Last Post: ODIS
  Time based loops Owenix 4 104 Sep-20-2018, 05:37 PM
Last Post: Owenix
  Using for loops and indexing to read and string and print only select words Drone4four 3 119 Sep-13-2018, 02:51 PM
Last Post: buran
  Help in understanding scope of dictionaries and lists passed to recursive functions barles 2 143 Aug-11-2018, 06:45 PM
Last Post: barles

Forum Jump:


Users browsing this thread: 1 Guest(s)