w3resource

Python NamedTuple example: Circle attributes


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
Circle = namedtuple('Circle', ['radius', 'center'])

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

# Print the attributes of the Circle instance
print("Circle-")
print("Radius:", circle_instance.radius)
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-
Radius: 5
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:

Flowchart: Python NamedTuple example: Circle attributes.

Previous: Python NamedTuple function: Calculate average grade.
Next: Python NamedTuple example: Triangle area calculation.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.