5

I'm attempting to write a simple python script that will calculate the squareroot of a number. heres the code i've come up with and it works. but i would like to learn how to use fractional exponents instead.

var1 = input('Please enter number:') var1 = int(var1) var2 = var1**(.5) print(var2) 

thanks for the help

1
  • You mean you get exponent input in the form of string 1/4 etc? Commented Jun 19, 2011 at 7:34

2 Answers 2

11

You can use fractional exponents with the help of fractions module.

In this module there is a class Fraction which works similar to our inbuilt int class.
Here is a link to the documentation of the class - http://docs.python.org/library/fractions.html (just go through its first few examples to understand how it works. It is very simple.)

Heres the code that worked for me -

from fractions import Fraction var1 = input('Please enter number:') var1 = Fraction(var1) expo = Fraction('1/2') //put your fractional exponent here var2 = var1**expo print var2 
Sign up to request clarification or add additional context in comments.

2 Comments

The best thing about using the class Fraction is that it does not matter whether the input (var1) is of type int, float, fraction, decimal or a string (a proper string), the above code snippet would always work.
Fraction(1, 243)**Fraction(1, 5) produces 0.3333333, though, not Fraction(1, 3)
6
numerator, denominator = [float(s) for s in raw_input().strip().split("/")] print 2 ** (numerator/denominator) 

I strip whitespace from the input, split it into parts, then convert the parts to numbers with a list comprehension.

This will fail if the input isn't in fractional form. To check and behave appropriately...

line = raw_input().strip() if "/" in line: numerator, denominator = [float(s) for s in line.split("/")] exponent = numerator/denominator else: exponent = float(line) print 2 ** exponent 

If you had tried using 2 ** (1/2) and it had failed, that is because 1 and 2 are integers, so Python 2 uses integer division and ignores the fractional part. You could fix this by typing 1.0/2 into your script or input().

1 Comment

or you could use exponent = numerator/(float(denominator)) rather than forcing the odd "1.0/2" input.