﻿ Python NamedTuple example: Circle attributes

# Python NamedTuple example: Circle attributes

## Python NamedTuple Data Type: Exercise-7 with Solution

Write a Python program that defines a NamedTuple named "Circle" with fields 'radius' and 'center' (a Point NamedTuple representing the coordinates of the center of the circle). Create an instance of the "Circle" NamedTuple and print its attributes

Sample Solution:

Code:

``````from collections import namedtuple

# Define a Point NamedTuple
Point = namedtuple('Point', ['x', 'y'])

# Define a Circle NamedTuple

# Create an instance of the Circle NamedTuple
center = Point(x=4, y=4)  # Center at (0, 0)

# Print the attributes of the Circle instance
print("Circle-")
print("Center:", circle_instance.center)
print("Value of x-coordinate:", circle_instance.center.x)
print("Value of y-coordinate", circle_instance.center.y)
``````

Output:

```Circle-
Center: Point(x=4, y=4)
Value of x-coordinate: 4
Value of y-coordinate 4
```

In the exercise above, we declare a "Point" NamedTuple to represent the coordinates of a point. Next, we define a "Circle" NamedTuple with 'radius' and 'center' fields, where 'center' is an instance of the "Point" NamedTuple. Finally, we create a "Circle" NamedTuple instance and print its attributes, including the radius and the center.

Flowchart:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿