New user needs help
omission9
omission9 at invalid.email.info
Sat Feb 21 00:32:50 EST 2004
John wrote:
> I am new to using Python. Everytime I run this program it prints "The lowest
> common factor is 0", no matter what numbers I use. Can anybody see anything
> wrong with my program? Thanks in advance.
>
>
>
> def getnum1(a):
> a = input("What is the first number?")
> if a == 0:
> getnum1(a)
> def getnum2(b):
> b = input("What is the second number?")
> if b == 0:
> getnum2(b)
> def euclid(num1, num2, num3, num4):
> if num1 < num2:
> num3, num4 = num1, num2
> num1, num2 = num4, num3
> euclid(num1, num2, num3, num4)
> elif num2 != 0:
> num3, num4 = num1, num2
> num1 = num4
> num2 = num3 % num4
> euclid(num1, num2, num3, num4)
> else:
> print "The lowest common factor is: ", num1
> a = 0
> getnum1(a)
> b = 0
> getnum2(b)
> x, y = 2, 100
> euclid(a, b, x, y)
This is a nice simple example of what is called "scope" and how it can
trick a beginner.
Put as simply as possible,"a" and "b" are actually defined twice. Once
"locally" in the getnum functions and another time "globally" . When you
set a and b to the user input in the functions the other a and b have no
idea about this assignment. Below is a slight revision which return the
a and b set by the user back to where they are called. By putting a
simple print statement in the script you can see where the values are
set and that can help you.
I hope that helps. There is probbaly a couple of other changes you could
make as well but nothing too major, in my opinion.
def getnum1(a):
a = input("What is the first number?")
if a == 0:
getnum1(a)
return a
def getnum2(b):
b = input("What is the second number?")
if b == 0:
getnum2(b)
return b
def euclid(num1, num2, num3, num4):
print num1, num2, num3, num4
if num1 < num2:
num3, num4 = num1, num2
num1, num2 = num4, num3
euclid(num1, num2, num3, num4)
elif num2 != 0:
num3, num4 = num1, num2
num1 = num4
num2 = num3 % num4
euclid(num1, num2, num3, num4)
else:
print "The lowest common factor is: ", num1
a = 0
b = 0
a=getnum1(a)
b=getnum2(b)
x, y = 2, 100
euclid(a, b, x, y)
More information about the Python-list
mailing list