Reputation:
def main():
name=input("Enter your name: ") #just write our name nothin important
print (name, "is Swag")
value1=int(input("enter a value: ")) #takes in the number without doubt
print(value1)
value2=float(int("Enter a fraction: ")) #heres our problem but what?
print(value2)
main()
just a simple program I am playing about with but It shows this error since you all might want to know:
I write for example 1/2 an this shows
Traceback (most recent call last):
File "C:\Users\waliu\Documents\Waliur Uni stuff\Information
systems\Python Programs\Samples\apparently fractions.py", line 8, in
<module>
main()
File "C:\Users\waliu\Documents\Waliur Uni stuff\Information
systems\Python Programs\Samples\apparently fractions.py", line 6, in main
value2=float(input("Enter a fraction: "))
ValueError: could not convert string to float: '1/2'
Upvotes: 0
Views: 604
Reputation: 140266
python won't evaluate fractions, unless you're using eval
(which is unsafe so I cannot recommend it). There are other expression evaluators like simpleeval
, but in your case, if you're sure that a fraction is entered you could just split, convert to integer and divide:
>>> fraction = "1 / 2" # input("enter a fraction")
>>> f = [int(x) for x in fraction.split("/")]
>>> f[0]/f[1]
0.5
>>>
you could handle non-fractions by just checking len(f)==2
, otherwise it's either a simple integer (if len(f)==1
), or an error (if > 2).
one-liner using operator.truediv
& passing the args directly:
operator.truediv(*(int(x) for x in fraction.split("/")))
(no syntax check possible here obviously)
Upvotes: 2
Reputation: 55489
There's a fractions
module in the standard library. It can parse a string containing a representation of a fraction.
from fractions import Fraction
s = input("Enter a fraction: ")
val = Fraction(s)
print(val, float(val))
demo
Enter a fraction: 3/8
3/8 0.375
Note that the string can't contain internal spaces, but it can have spaces before or after the data.
If you want to do calculations with fractions it's a good idea to not convert them to floats, since that loses precision. And since Fraction objects use Python integers for the numerator & denominator there's no limit to how accurate they can be (apart from RAM limitations). Here's a short demo:
a = Fraction('2/3')
b = Fraction(3, 4)
c = a**2 + b**2
print(c)
print(c**10)
output
145/144
4108469075197275390625/3833759992447475122176
Upvotes: 2