Printing fractions in Python is a crucial skill for those who work with mathematical expressions in their code.

Fractions are essential in many mathematical operations and equations, and using them in Python programming enhances the accuracy and precision of the results. In this tutorial, we will show you how to print fractions in Python.

## Steps:

### 1. Import the fractions module:

Fractions are not built into Python; therefore, we need to import the fractions module first. To do that, copy and paste the following code into your Python environment:

1 |
import fractions |

### 2. Create a fraction:

We can create a fraction using the Fraction() function of the fractions module. We can pass in the numerator and denominator values as parameters. For example, to create the fraction ¾, we can use the following code:

1 |
f1 = fractions.Fraction(3, 4) |

### 3. Print the fraction:

Once we have created the fraction, we can print it on the console using the print() function. We can simply pass the fraction variable as a parameter to the print() function. For example, to print the fraction ¾, we can use the following code:

1 |
print(f) |

This will print the fraction ¾ on the console.

### 4. Convert a float to a fraction:

We can also convert a float value to a fraction. To do that, we can use the from_float() function of the Fraction() class. For example, to convert the float value 1.5 to a fraction, we can use the following code:

1 |
f2 = fractions.Fraction.from_float(1.5) |

### 5. Convert a string to a fraction:

We can also convert a string that contains a fraction to a fraction object. To do that, we can use the from_string() function of the Fraction() class. For example, to convert the string ‘2/3’ to a fraction, we can use the following code:

1 |
f3 = fractions.Fraction.from_string('2/3') |

## Conclusion:

Printing fractions in Python is an important skill for those who work with mathematical expressions.

We can use the fractions module to create and print fractions in Python. We can also convert float values and string values to fractions using the Fraction() class. With the knowledge gained from this tutorial, you can confidently use fractions in your Python programs.

## Full code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import fractions # Create a fraction f1 = fractions.Fraction(3, 4) # Print the fraction print(f1) # Convert a float to a fraction f2 = fractions.Fraction.from_float(1.5) print(f2) # Convert a string to a fraction f3 = fractions.Fraction('2/3') print(f3) |