Computer Science Canada

Help needed

Author:  Leela [ Mon Apr 20, 2009 10:23 am ]
Post subject:  Help needed

Can someone help me with this little beginner's program, please?
It works when I try it without the input part - just writing the definition and calling the function in the editor:

Python:
def check_fermat (a,b,c,n):
        if a**n + b**n == c**n and n > 2:
                print "Fermat was wrong!"
        else:
                print "Fermat was correct"
       
check_fermat (3,4,6,3)



But when I try to work with an input, and making it an actual program, it evaluates:


code:
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'str'


This is the version that doesn't work:

Python:
def check_fermat (a,b,c,n):   
    if a**n + b**n == c**n and n > 2:
        print "Fermat was wrong!"
    else:
        print "Fermat was correct"
x=raw_input ("Enter x: ")
y=raw_input ("Enter y: ")
z=raw_input ("Enter z: ")
n=raw_input ("Enter n: ")
check_fermat (x,y,z,n)


I also tried it like this (without definitions or function calls):

Python:
a=raw_input ("Enter a: ")
b=raw_input ("Enter b: ")
c=raw_input ("Enter c: ")
n=raw_input ("Enter n: ")

if a**n + b**n == c**n and n > 2:
        print "Fermat was wrong!"
else:
        print "Fermat was correct"



Same error.

Any advice will be greatly appreciated.

Mod Edit: Remember to use syntax tags! Thanks Smile
code:
[syntax="python"]Code Here[/syntax]

Author:  Leela [ Mon Apr 20, 2009 11:15 am ]
Post subject:  Re: Help needed

I think I've got it. I should have converted the input to integers. Here's my (finally!) working version:
Python:
a = raw_input ("Enter a: ")
b = raw_input ("Enter b: ")
c = raw_input ("Enter c: ")
n = raw_input ("Enter n: ")   

if int(a)**int(n)+int(b)**int(n)==int(c)**int(n):
    print "Holy smokes, Fermat was wrong!"
else:
    print "Yep, Fermat was correct"

raw_input('press Return>')


Any suggestion to make it neater?

Author:  Alexmula [ Mon Apr 20, 2009 12:16 pm ]
Post subject:  RE:Help needed

use a = input("Enter a: ") instead of the raw_input. raw_input expects string values

Author:  Leela [ Mon Apr 20, 2009 1:16 pm ]
Post subject:  Re: RE:Help needed

Alexmula @ Mon Apr 20, 2009 12:16 pm wrote:
use a = input("Enter a: ") instead of the raw_input. raw_input expects string values

Oh, that's why Python interpreted my assignments as strings! Well, this is how my textbook taught me to enter inputs; I will know better from now on.
Huge thanks!

Author:  wtd [ Mon Apr 20, 2009 2:32 pm ]
Post subject:  RE:Help needed

Especially with Python, you will need to use code tags to preserve indentation.

Author:  Leela [ Mon Apr 20, 2009 7:54 pm ]
Post subject:  Re: RE:Help needed

wtd @ Mon Apr 20, 2009 2:32 pm wrote:
Especially with Python, you will need to use code tags to preserve indentation.

Thanks, I can see now how it should be posted.


: