0

Good night, I have some idea about while functionality but I want to understand the why the variables inside its body refresh new values for the variables outside while body. Is something intrinsic of python? It was designed to be like that?

    num = int(input("Type a number: "))
    while (num != 9999):
       add = 0
       counter = 0
       while (num != 0):
          add = add + num
          counter += 1
          num = int(input("Type another value: "))
       print(round(soma/contador,3))
       num = int(input("Next sequence of values. Type a number: "))
b4hand
  • 9,550
  • 4
  • 44
  • 49
milbol
  • 13
  • 2
  • It's not clear to me what you mean by *"why the variables inside its body refresh new values for the variables outside while body"* – Felix Kling May 29 '15 at 04:33
  • By what I've understood of python's while in the code if I put 3, it will go through the first while then the second one, inside the second the variable "add" will become "3" and if the next iteration I put another value and so on the "add" will become another value, so if I put 0 the iteration will stop and go to the first while which will print "add/counter" but its values are from inside the second while body, so it's like the values inside the second while were transferred to the first while body @FelixKling – milbol May 29 '15 at 04:38
  • *"but its values are from inside the second while body, so it's like the values inside the second while were transferred to the first while body"* There is only a single variable `num`. It's declared at the very beginning of the code. Any occurrence of `num`, be it reading or writing, refers to that single variable. And of course once the value of the variable changes, anything else that reference the variable gets the new value. There is nothing Python specific about this, it would work the same way in many languages, JavaScript, PHP, Java, C, etc. – Felix Kling May 29 '15 at 04:41
  • Maybe what you want/have to learn about is the concept of **scope**: https://en.wikipedia.org/wiki/Scope_%28computer_science%29 – Felix Kling May 29 '15 at 04:43
  • Aaah! I thought that the variables "respect" the body they belong, I mean, if "add" is inside a block, only inside that block that "add" has such value even if has another variable in the code with the same name. Thank you mate. @FelixKling – milbol May 29 '15 at 04:49

2 Answers2

1

Local variables in python are just like a dict, each has whatever value was most recently assigned. So in the following code:

if c:
   a = 1
print(a)

is legal if c was true, a was assigned so in the print it is 1. If c was not true then a was never assigned and the print is an error. Python is not like C where a variable's scope ends at the end of the variable's block. If it were a would vanish at the end of the if, but no such thing happens. This is one of the ways that python is a dynamic language.

  • Exactly! Thank you o/ – milbol May 29 '15 at 04:51
  • This has nothing to do with Python's "dynamic" nature, Python actually has static scope for the most part. The relevant difference between Python and C here is that in C, the body of a nested statement has its own scope, while in Python, it does not. – augurar May 29 '15 at 05:04
  • I C there are more scopes, and at each point of them you can compute the variables that are in scope, it will be the same every time thru. Variables in C cannot 'not exist' on some executions, but then be there next time. In Python the existence a type of a variable depends on the programs history, not just the structure of the surrounding source code . That's was I was calling dynamic. – Christopher Ian Stern May 29 '15 at 05:24
1

Borrowing from Short Description of the Scoping Rules? Python's scoping rules are really quite simple to remember:

  • Local -- Any local scope; e.g: a function
  • Enclosing -- Any enclosing scope, ee.g: def g(): inside def f()
  • Global -- Any declared "globals", e.g: global x
  • Builtin -- Any builtin function(s), `.eg: max()

In your example code: (assuming a function)

def foo():
    num = int(input("Type a number: "))             # ^
    while (num != 9999):                            # |
       add = 0                                      # |
       counter = 0                                  # |
       while (num != 0):                            # |
          add = add + num                           # |
          counter += 1                              # LOCAL
          num = int(input("Type another value: "))  # |
       print(round(soma/contador,3))                # |
       num = int(                                   # |
          input((                                   # |
              "Next sequence of values. "           # |
              "Type a number: "                     # |
          ))                                        # |
       )                                            # V
Community
  • 1
  • 1
James Mills
  • 18,669
  • 3
  • 49
  • 62