Part of the series

Several example codes

~1 min read • Updated Sep 30, 2025

Program Overview

This Python program reads an integer from the user and calculates two values:
- The square of the number
- The sum of its digits
It then prints both results clearly and concisely.


Python Code:


# Read number from user
num = int(input("Enter a number: "))

# Calculate square
square = num ** 2

# Calculate digit sum
digit_sum = sum(int(digit) for digit in str(abs(num)))

# Display results
print("\n--- Result ---")
print(f"Square: {square}")
print(f"Digit sum: {digit_sum}")

Sample Output:


Enter a number: 432123  

--- Result ---  
Square: 186729129  
Digit sum: 15

Explanation:

- The number is read as an integer
- The square is calculated using exponentiation (** 2)
- The digit sum is computed by converting the number to a string, iterating over each digit, and summing them
- abs() ensures the logic works for negative numbers too


Written & researched by Dr. Shahin Siami