# Python TensorFlow graph and session

## Python TensorFlow Basic: Exercise-7 with Solution

Write a Python program that creates a TensorFlow graph and run it inside a session to compute the result of a basic mathematical operation.

**Sample Solution:**

**Python Code:**

```
import tensorflow as tf
# Define a computational graph
graph = tf.Graph()
with graph.as_default():
# Define TensorFlow constants
x = tf.constant(5.0)
y = tf.constant(3.0)
# Define a mathematical operation
result = tf.multiply(x, y)
# Create a TensorFlow session
with tf.compat.v1.Session(graph=graph) as session:
# Run the session to compute the result
output = session.run(result)
# Print the result
print("Result of the operation (within a session):", output)
```

Output:

Result of the operation (within a session): 15.0

**Explanation:**

In the exercise above -

- We define a TensorFlow graph using tf.Graph() and use graph.as_default() to set it as the default graph.
- Inside the graph context, we define TensorFlow constants a and b and a multiplication operation (tf.multiply(x, y)).
- Create a TensorFlow session (tf.compat.v1.Session()) and pass the graph to it.
- Within the session context, we run the session using session.run(result) to compute the operation result.

**Python Code Editor:**

**Previous:** Python TensorFlow eager execution.

**Next:** Python TensorFlow matrix initialization and print.

**What is the difficulty level of this exercise?**

**Weekly Trends**- 100 Python Projects for Beginners with solution
- Mastering NumPy: 100 Exercises with solutions
- SQL Tutorial
- SQL Inner Join
- Python Exercises, Practice, Solution
- Python Interview Questions and Answers: Comprehensive Guide
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript HTML Form Validation
- Java Collection Exercises