user2669155
user2669155

Reputation: 87

Variables change values inside while cycle

I have started programming with python yesterday, so I'm quite a newbie!

I have this function, which must check

  1. if an inserted value is a number
  2. if the number is no greater than 31 (see code below)

During debugging, I have found out this bug I don't understand:

  1. I choose deliberately a number greater than 31, for example 45
  2. it prompts me again and I choose a correct number, for example 7
  3. In the code, I ask to print the voto variable twice (in the comments I call them 'POINT A' and 'POINT B')
  4. in the output I get:

    7

    45

and I'm again asked to type in a different number.

I don't understand why the variables changes its value just after the while loop has started.

Can you please explain it to me, using very simple words? (<- please, remember I'm a beginner! :D )

Thank you in advance!

def controlla_voto(voto_lett):
    flag=1
    while flag:
        for y in voto_lett:
            if (ord(y) in range(48,58))==0:
                voto_lett=raw_input("Invalid charachters, try again: ")
                flag=1
                break
            else: flag=0
    voto=int(voto_lett)
    print voto   # POINT A
    while (voto in range(32))==0:
       print voto #POINT B
       voto_lett=raw_input("Invalid number, try again: ")
       controlla_voto(voto_lett)
    return voto

Upvotes: 3

Views: 233

Answers (1)

Jiminion
Jiminion

Reputation: 5168

It's perfect! You just forgot the return on the recursive call.

def controlla_voto(voto_lett):
flag=1
while flag:
    for y in voto_lett:
        if (ord(y) in range(48,58))==0:
            voto_lett=raw_input("Invalid charachters, try again: ")
            flag=1
            break
        else: flag=0
voto=int(voto_lett)
print voto   # POINT A
while (voto in range(32))==0:
    print voto #POINT B
    voto_lett=raw_input("Invalid number, try again: ")
    return controlla_voto(voto_lett)
return voto

Another solution would be:

voto = controlla_voto(voto_lett)

but something is needed to break out of the while loop.

Upvotes: 2

Related Questions