0% found this document useful (0 votes)
4 views19 pages

Module 1 - Question and Answer Python

The document provides an introduction to Python programming, covering basic data types, variable scope, comparison operators, flow control statements, and built-in functions. It explains the differences between local and global variables, the use of comparison operators, and the structure of flow control statements like if, while, and for loops. Additionally, it discusses user-defined functions and how to pass arguments to them, along with examples for better understanding.

Uploaded by

nvedhashree05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

Module 1 - Question and Answer Python

The document provides an introduction to Python programming, covering basic data types, variable scope, comparison operators, flow control statements, and built-in functions. It explains the differences between local and global variables, the use of comparison operators, and the structure of flow control statements like if, while, and for loops. Additionally, it discusses user-defined functions and how to pass arguments to them, along with examples for better understanding.

Uploaded by

nvedhashree05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Introduction to Python Programming: Module 1 Question and Answer

1. Explain basic data types like int, float, double and string with an example: ….…Jan, 2025

The basic data types in python are int, float and str:

1. Integer (int)
o Represents whole numbers (positive, negative, or zero) without decimals.
o Example: 4,7,3,-5,-2
o num = 10
o print(type(num)) # Output: <class 'int'>
2. Floating Point (float)
o Represents real numbers with decimal points.
o Example: 0.25, 4.5,-2.50
o price = 99.75
o print(type(price)) # Output: <class 'float'>
3. Double (double)
o Python does not have a separate double type. Instead, float in Python covers both single
and double precision floating-point numbers.
o Example:
o pi = 3.141592653589793
o print(type(pi)) # Output: <class 'float'>
4. String (str)
o Represents a sequence of characters enclosed in quotes.
o Example: “Alice”, “Bob”, “42”, “5.25”, “-4.5”
o name = "Alice"
o print(type(name)) # Output: <class 'str'>

These data types are fundamental in Python programming. Integers are used for whole numbers, floats for
decimal values, and strings for text. Python automatically assigns the correct type based on the value.

2. Explain local and global scope of variable with suitable example …Jan, 25, Jan, 2024, July 24,
July 23

In Python, a variable's scope defines where it can be accessed. There are two main types of variable
scope:
1. Local Scope – Variables declared inside a function.
2. Global Scope – Variables declared outside a function, accessible throughout the program.

Local Scope (Function-Level Variable)


A variable declared inside a function is called a local variable. It can only be used within that function
and cannot be accessed outside of it.

Example of Local Scope:


def my_function():
x = 10 # Local variable
print("Inside function, x =", x)

my_function()
# print(x) # ❌ This will cause an error because x is not accessible outside the function

Page No. 1
Introduction to Python Programming: Module 1 Question and Answer

Output:
Inside function, x = 10

Key Points:
 x is defined inside my_function(), so it is local to that function.
 Trying to access x outside the function results in an error.

Global Scope (Program-Level Variable)


A variable declared outside a function has global scope. It can be accessed anywhere in the program,
including inside functions.

Example of Global Scope:

y = 20 # Global variable

def my_function():
print("Inside function, y =", y) # Accessing global variable

my_function()
print("Outside function, y =", y) # Global variable is accessible anywhere

Output:

Inside function, y = 20
Outside function, y = 20

Key Points:
 y is a global variable and can be accessed inside and outside the function.
 Functions can read global variables but cannot modify them directly unless explicitly specified.

Using global Keyword


To modify a global variable inside a function, use the global keyword.

Example:
z=5 # Global variable

def modify_global():
global z # Declaring z as global
z = 15 # Modifying global variable
print("Inside function, modified z =", z)

modify_global()
print("Outside function, z =", z) # Global variable value changed

Output:

Inside function, modified z = 15


Outside function, z = 15

Page No. 2
Introduction to Python Programming: Module 1 Question and Answer

Key Points:
 Without global, assigning a value to z inside the function would create a new local variable, not
modify the global one.

Difference Between Local and Global Variables


Feature Local Variable Global Variable
Defined Inside a function Outside a function
Scope Only inside the function Entire program
Access outside function ❌ Not possible ❌ Possible
Modification inside function Allowed Use global keyword to modify
Conclusion
 Local variables exist inside functions and cannot be accessed outside.
 Global variables are available throughout the program.
 Use the global keyword to modify global variables inside functions.
 Understanding scope is crucial for writing error-free programs.

3. Define comparison operator and list its type. Give the difference between == and = opereator in
python. July, 2024

Comparison Operators in Python


Definition:
Comparison operators in Python are used to compare two values. These operators evaluate conditions and
return a Boolean result (True or False). They are commonly used in decision-making statements such as
if, while, and loops.

Types of Comparison Operators in Python


Operator Name Description Example Output
== Equal to Checks if two values are equal 5 == 5 True
!= Not equal to Checks if two values are different 5 != 3 True
> Greater than Checks if the left operand is greater than the right operand 10 > 5 True
< Less than Checks if the left operand is smaller than the right operand 3<8 True
Greater than or equal Checks if the left operand is greater than or equal to the right
>= 7 >= 7 True
to operand
Checks if the left operand is smaller than or equal to the
<= Less than or equal to 4 <= 6 True
right operand

Difference Between = and == Operator in Python


Operator Type Purpose Example Explanation
Assignment Assigns a value to a
= x = 10 Assigns the value 10 to x
Operator variable
Comparison Checks if x is equal to 10, returns True or
== Compares two values x == 10
Operator False

Example Code:
# Using the assignment operator (=)
x = 10 # Assigns the value 10 to x

Page No. 3
Introduction to Python Programming: Module 1 Question and Answer

print(x) # Output: 10

# Using the comparison operator (==)


y = 20
print(y == 20) # Output: True (checks if y is equal to 20)
print(y == 15) # Output: False (y is not equal to 15)

Differences:
1. = is used for variable assignment, while == is used for value comparison.
2. x = 5 means assigning the value 5 to x, whereas x == 5 checks if x is equal to 5.
3. Using = inside an if condition will cause an error, but == works correctly.

 Comparison operators are used to compare values and return True or False.
 Python provides six comparison operators: ==, !=, >, <, >=, <=.
 The assignment operator (=) is different from the equality operator (==), where = assigns
values and == checks equality.

4. Explain flow control statement in detail with if, else, elif, while loop and for loop…July 2024,
Jan 24

Flow Control Statements in Programming

Flow control statements determine the execution flow of a program based on conditions and loops. They
help in making decisions and repeating tasks efficiently. The key flow control statements include if, else,
if-else, while loop, and for loop.

1. if Statement

The if statement is used to execute a block of code only if a


specified condition is true.

 if……. key word


 A condition
 Colon
 Indentation for block of code

Syntax:
if condition:
# Code to execute if condition is true

Example:
name = ‘Alice’
if name==’Alice’:
print("You are eligible to vote.")

Output:

Output is ‘Hi, Alice.’

Page No. 4
Introduction to Python Programming: Module 1 Question and Answer

if-else Statement

The if-else statement allows executing one block of code when the condition is true and another when it is
false.

 if……. key word


 A condition
 Colon
 Indentation for block of code
 Else …key workd
 Colon
 Indentation for block of code

Syntax:
if condition:
# Code to execute if condition is true
else:
# Code to execute if condition is false

Example:
name = ‘Alice’
if name== ‘Alice’:
print("Hi, Alice.")
else:
print("Hello,stranger.")

Output:

If name is Alice output is “Hi, Alice”


else
Out put is “Hello, stranger.”

if-elif-else Statement

The if-elif-else statement allows checking multiple conditions


sequentially.
 if……. key word
 A condition
 Colon
 Indentation for block of code
 elif……. key word
 A condition
 Colon
 Indentation for block of code
 Else …key word
 Colon
 Indentation for block of code

Page No. 5
Introduction to Python Programming: Module 1 Question and Answer

Syntax:
if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition2 is true
else:
# Code to execute if all conditions are false

Example:

while Loop

A while loop executes a block of code repeatedly as long as the given condition remains true.

 While ….key word


 Condition
 Colon
 Indentation for block of code

Syntax:
while condition:
# Code to execute in loop

Example:
spam = 0
while spam <= 5:
print(‘Hello, world.’)
spam=spam + 1
Output:
‘Hello, world.’
‘Hello, world.’
‘Hello, world.’
‘Hello, world.’
‘Hello, world.’

Explanation: The loop runs until spam becomes greater than 5.

Page No. 6
Introduction to Python Programming: Module 1 Question and Answer

for Loop

A for loop is used to iterate over a sequence (list, tuple, string, range, etc.).

Syntax:
for variable in sequence:
# Code to execute in loop

Example:
for i in range(5):
print(i)

Output:

0
1
2
3
4
Explanation: The for loop iterates through the numbers from 0 to 5 using the range() function.

Conclusion:

Flow control statements like if, if-else, if-elif-else, while, and for loops help in making decisions and
executing code repeatedly.

5. Explain while, break and continue statements in python with examples for each…July 23

In Python, loops help in executing a block of code multiple times based on a condition. The while loop,
along with break and continue statements, allows better control over the flow of a loop.

while Loop

A while loop executes repeatedly as long as the condition remains True.

Syntax:
while condition:
# Code to execute in the loop

Example:
count = 1
while count <= 5:
print(count)
count += 1

Output:
1
2
3

Page No. 7
Introduction to Python Programming: Module 1 Question and Answer

4
5

Explanation: The loop runs while count is less than or equal to 5. The value of count increases in each
iteration.

break Statement

The break statement terminates the loop immediately when executed.

Syntax:
while condition:
if some_condition:
break

Example:
count = 1
while count <= 5:
if count == 3:
break # Loop stops when count reaches 3
print(count)
count += 1

Output:
1
2

Explanation: When count becomes 3, break stops the loop execution immediately.

continue Statement

The continue statement skips the current iteration and moves to the next one.

Syntax:
while condition:
if some_condition:
continue

Example:
count = 0
while count < 5:
count += 1
if count == 3:
continue # Skips printing 3
print(count)

Output:
1
2
4

Page No. 8
Introduction to Python Programming: Module 1 Question and Answer

5
Explanation: When count is 3, continue skips the print() statement and moves to the next iteration.
Conclusion

 while executes a block of code repeatedly as long as a condition is True.


 break terminates the loop when encountered.
 continue skips the current iteration and continues with the next.

6. Explain with example print(), input() and len() in python..…July 2024, Jan 24,July 23

Python provides built-in functions for handling input, output, and string operations. Three commonly
used functions are:

print() Function (Output Function)


 The print() function is used to display output on the screen.
 It can print strings, numbers, variables, and expressions.

Example:
name = "Alice"
age = 25
print("Name:", name)
print("Age:", age)
print("Sum of 5 and 3 is:", 5 + 3)

Output:
Name: Alice
Age: 25
Sum of 5 and 3 is: 8

Usage: Displays messages, debugging, and showing results.

input() Function (User Input Function)

 The input() function allows users to enter values during program execution.
 The input is always received as a string.

Example:
name = input("Enter your name: ")
print("Hello,", name)

Input & Output:


Enter your name: John
Hello, John

Usage: Taking user input in programs.

Type Conversion Example:

age = int(input("Enter your age: ")) # Converts input string to integer

Page No. 9
Introduction to Python Programming: Module 1 Question and Answer

print("Next year, you will be", age + 1)

Input & Output:

Enter your age: 20


Next year, you will be 21

len() Function (Length Function)

 The len() function returns the length (number of characters/elements) of a string, list, or tuple.

Example (String Length):


word = "Python"
print(len(word)) # Output: 6

Example (List Length):


fruits = ["Apple", "Banana", "Cherry"]
print(len(fruits)) # Output: 3

Usage: Finding string length, counting elements in lists/tuples.

 print() displays output.


 input() takes user input as a string.
 len() finds the length of a string or collection.

7. List and explain the use of comparison orator in python. Write the step by step execution of the
following expression in python (5-1)*((7+1)/(3-1)

Comparison Operators in Python

Comparison operators are used to compare two values and return a Boolean result (True or False).
They are commonly used in decision-making statements (if-else) and loops.

List of Comparison Operators in Python

Operator Description Example Output

== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 7>4 True
< Less than 3<8 True
>= Greater than or equal to 6 >= 6 True
<= Less than or equal to 2 <= 5 True

Page No. 10
Introduction to Python Programming: Module 1 Question and Answer

8. What are user defined function? How can we pass the arguments to the functions? Explain with
suitable examples…Dec 23

A User-Defined Function (UDF) is a function created by the programmer to perform a specific task.
Instead of repeating code, functions help in modular programming by allowing reuse and better
organization.

Defining a Function in Python

A function in Python is defined using the def keyword, followed by the function name and parentheses ()
containing optional parameters.

Syntax:
def function_name(parameters):
# Function body
return value # (optional)

Example: Simple Function Without Parameters


def greet():
print("Hello! Welcome to Python.")

greet() # Calling the function

Output:
Hello! Welcome to Python.

Passing Arguments to Functions

Arguments are values passed to a function when calling it. These values are used inside the function.

1. Positional Arguments

Arguments are passed in order and must match the function's parameters.

Example:
def add_numbers(a, b):
print("Sum:", a + b)

add_numbers(5, 3)

Output:
Sum: 8

Page No. 11
Introduction to Python Programming: Module 1 Question and Answer

2. Default Arguments

A parameter can have a default value, which is used if no argument is provided.

Example:
def greet(name="Guest"):
print("Hello,", name)

greet("Alice") # Passes "Alice"


greet() # Uses default value "Guest"

Output:
Hello, Alice
Hello, Guest

3. Keyword Arguments

Arguments are passed using parameter names, making order unimportant.

Example:
def student_info(name, age):
print("Name:", name)
print("Age:", age)

student_info(age=21, name="John") # Order changed

Output:
Name: John
Age: 21

Conclusion

User-defined functions help in structuring the code efficiently. Arguments can be passed using positional,
default, keyword, and variable-length arguments, making functions flexible and reusable. ❌

9. With Return Statement………..Jan 2025

A User-Defined Function (UDF) is a function created by the programmer to perform a specific task. It
helps in code reusability and modular programming by grouping related operations.

Using return Statement in Functions

The return statement is used to send a value back from a function to the caller.

Syntax:

def function_name(parameters):
# Perform operations
return value # Returns result to the caller

Page No. 12
Introduction to Python Programming: Module 1 Question and Answer

Passing Arguments and Using return

Function with Positional Arguments and return

def add_numbers(a, b):


return a + b # Returns the sum

result = add_numbers(5, 3)
print("Sum:", result)

Output:
Sum: 8

Explanation: The function add_numbers() returns the sum of a and b, which is stored in result and
printed.

Function with Default Arguments and return

def power(base, exponent=2):


return base ** exponent # Returns base raised to exponent

print("Square:", power(4)) # Uses default exponent (2)


print("Cube:", power(4, 3)) # Uses given exponent (3)

Output:
Square: 16
Cube: 64

Explanation: If no exponent is provided, the default value 2 is used.

Function with Multiple Return Values

def calculate(a, b):


sum_value = a + b
product = a * b
return sum_value, product # Returns multiple values as a tuple

s, p = calculate(5, 3)
print("Sum:", s)
print("Product:", p)

Output:
Sum: 8
Product: 15

Explanation: The function returns two values (sum and product), which are unpacked into s and p.

Page No. 13
Introduction to Python Programming: Module 1 Question and Answer

Conclusion

 The return statement is used to send results from a function.


 Functions can return single or multiple values.

10. Explain string concatenation and replication…Jan 24, July 23

Strings in Python are sequences of characters. Python provides operations like concatenation (joining
strings) and replication (repeating strings) to manipulate string data.

String Concatenation (+ Operator)

String concatenation means joining two or more strings into one. It is done using the + operator.

Example:

str1 = "Hello"
str2 = "World"
result = str1 + " " + str2 # Adding a space between words
print(result)

Output:

Hello World

Points to Remember:

 The + operator can only be used between strings.


 If you try to concatenate a string with a number, you need to convert the number into a string
using str().

Example (Incorrect & Correct Usage):

age = 25
# print("My age is " + age) # ❌ This will cause an error

print("My age is " + str(age)) # ❌ Correct way

Output:
My age is 25

String Replication (* Operator)


String replication means repeating a string multiple times using the * operator.
Example:
word = "Hello "
print(word * 3) # Repeats the string 3 times

Output:
Hello Hello Hello

Page No. 14
Introduction to Python Programming: Module 1 Question and Answer

Example (Using Replication for Patterns):


print("*" * 10) # Prints a line of 10 stars
Output:

**********
Points to Remember:

 The * operator works with a string and an integer (not two strings).
 Negative numbers (-n) will result in an empty string.

Example (Incorrect & Correct Usage):

# print("Hello" * "3") # ❌ Error (Cannot multiply string by string)

print("Python " * 0) # ❌ Output: (empty string)

Combining Concatenation and Replication


Both operations can be used together to create structured outputs.
Example:
word1 = "Python"
word2 = "Rocks"
print((word1 + " ") * 3 + word2)

Output:
Python Python Python Rocks

Conclusion:
 Concatenation (+) joins two or more strings.
 Replication (*) repeats a string multiple times.

11. What is exception? How exception are handled in python? Write a program to solve divide by
zero exception….Jan.2025, July 24

What is an Exception?

An exception in Python is an unexpected error that occurs during program execution, which disrupts the
normal flow of the program. Common exceptions include:

 ZeroDivisionError – Division by zero


 ValueError – Invalid input type
 TypeError – Incorrect data type usage
 FileNotFoundError – File not found

How Are Exceptions Handled in Python?

Python handles exceptions using the try-except block. The try block contains code that may cause an
exception, while the except block handles the error gracefully.

Page No. 15
Introduction to Python Programming: Module 1 Question and Answer

Syntax:

try:
# Code that may cause an exception
except ExceptionType:
# Code to handle the exception

Example: Handling Divide by Zero Exception

try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2 # May cause ZeroDivisionError
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input! Please enter numbers only.")

Output 1 (Valid Input):


Enter numerator: 10
Enter denominator: 2
Result: 5.0

Output 2 (Divide by Zero Error):


Enter numerator: 10
Enter denominator: 0
Error: Cannot divide by zero!

Output 3 (Invalid Input Error):


Enter numerator: ten
Enter denominator: 2
Error: Invalid input! Please enter numbers only.

Conclusion

 An exception is an error that occurs during execution.


 Python uses try-except blocks to handle exceptions and prevent crashes.
 The divide by zero exception (ZeroDivisionError) can be handled using except.

12. Write a python program to guess the secret number between 1 to 25 within 5 guess if the
number is same then it is right guess else wrong guess………..Dec 23

import random
# Generate a random secret number between 1 and 25
secret_number = random.randint(1, 25)

# Maximum number of attempts


attempts = 5
print("Guess the secret number between 1 and 25. You have 5 attempts.")

Page No. 16
Introduction to Python Programming: Module 1 Question and Answer

for i in range(attempts):
guess = int(input(f"Attempt {i+1}: Enter your guess: "))
if guess == secret_number:
print("Right guess! ❌ You guessed the secret number.")
break # Exit the loop if the guess is correct
else:
print("Wrong guess! Try again.")

# If all attempts are used and the guess was incorrect


else:
print(f"Sorry! You've used all {attempts} attempts. The secret number was {secret_number}.")

13. Develop a program to calculate factorial of a number. Program to compute binomial coefficient
(Given N and R)……….Jan.25, July 24, July 23
try:
# coefficient (Given N and R). # Calculate Factorial
N = int(input("Enter a number to calculate its factorial: "))
Source Code: if N < 0:
print("Factorial is not defined for negative numbers.")
def binomialCoefficient(n, k): else:
# since C(n, k) = C(n, n - k) fact_n = 1
if(k > n - k): for i in range(2, N + 1):
k=n-k fact_n *= i
# initialize result print("Factorial:", fact_n)
res = 1 # Compute Binomial Coefficient
# Calculate value of N = int(input("Enter N for binomial coefficient: "))
# [n * (n-1) *---* (n-k + 1)] / [k * (k-1) *----* 1] R = int(input("Enter R for binomial coefficient: "))
for i in range(k): if R > N or N < 0 or R < 0:
res = res * (n - i) print("Invalid inputs! Ensure N >= R >= 0.")
else:
res = res // (i + 1) fact_n = 1
return res for i in range(2, N + 1):
fact_n *= i
Output: fact_r = 1
for i in range(2, R + 1):
# Driver program to test above function fact_r *= i
n=8 fact_n_r = 1
k=2 for i in range(2, N - R + 1):
res = binomialCoefficient(n, k) fact_n_r *= i
print("Value of C(% d, % d) is % d" %(n, k, res)) binomial_coefficient = fact_n // (fact_r * fact_n_r)
print("Binomial Coefficient (C(N, R)):", binomial_coefficient)
Value of C( 8, 2) is 28 except ValueError:
print("Invalid input! Please enter an integer.")

14. Develop a program to generate Fibonacci sequence of length (N). Read N from the
console…Jan. 25, July 24, Jan 24

try:
N = int(input("Enter the length of the Fibonacci sequence: "))
if N <= 0:
print("Please enter a positive integer.")
else:

Page No. 17
Introduction to Python Programming: Module 1 Question and Answer

fibonacci_sequence = [0, 1]
for i in range(2, N):
fibonacci_sequence.append(fibonacci_sequence[-1] + fibonacci_sequence[-2])
print("Fibonacci Sequence:", fibonacci_sequence)

except ValueError:
print("Invalid input! Please enter an integer.")

Output:
Enter the length of the Fibonacci sequence:9
Fibonacci sequence:[0,1,1,2,3,5,8,13,21]

15. Develop a program to read the name and year of birth of a person and to display whether the
person is a senior citizen or not………..July.24, Jan 24, July 23,

import datetime

today = datetime.date.today()
year = today.year

name=input("Enter the Name of the Person:") Output:


birth=int(input("Enter the Year of Birth:"))
Enter the Name of the Person:Abhiskek
age=(year)-(birth) Enter the Year of Birth:2004
if age>59: Abhiskek is not Senior Citizen
print(name,"is Senior Citizen")
else:
print(name,"is not Senior Citizen")
16. Develop a python program to calculate the area and circumference of a circle input the value of
radius and print the results………….Jan 24

import math # Import math module for π (pi) value


# Input: User enters the radius of the circle
radius = float(input("Enter the radius of the circle: "))

# Calculate area and circumference


area = math.pi * radius ** 2 # Area formula: πr²
circumference = 2 * math.pi * radius # Circumference formula: 2πr
Output:
# Output: Print the results Enter the radius of the circle: 5
print(f"Area of the circle: {area:.2f}") Area of the circle: 78.54
print(f"Circumference of the circle: {circumference:.2f}") Circumference of the circle: 31.42

Page No. 18
Introduction to Python Programming: Module 1 Question and Answer

17. Develop a program to read the student details like Name, USN and Marks in three subjects.
Display the student details total marks and percentage with suitable messages……..Jan 24

name=input("Enter the Name of the Student:") Output:


USN=input("Enter the USN of the Student:")
m1=float(input("Enter the marks in the first subject:")) Enter the Name of the Student:ABCD
m2=float(input("Enter the marks in the Second subject:")) Enter the USN of the Student:XXXX
m3=float(input("Enter the marks in the Third subject:")) Enter the marks in the first subject:80
total_marks=m1+m2+m3 Enter the marks in the Second subject:73
per=(total_marks/300)*100 Enter the marks in the Third subject:69
Studetns details are:
print("Studetns details are:") Name is: ABCD
print("Name is:", name) USN is: XXXX
print("USN is:", USN) Marks in First Subject: 80.0
print("Marks in First Subject:", m1) Marks in Second Subject: 73.0
print("Marks in Second Subject:", m2) Marks in First Subject: 69.0
print("Marks in First Subject:", m3) Total Marks Obtained: 222.0
print("Total Marks Obtained:", total_marks) Percentage of Marks: 74.0
print("Percentage of Marks:", per)

18. Write a python program to check whether a given number is Armstrong or Not…….Dec 23.

# Input: Get number from user


num = int(input("Enter a number: "))
# Convert number to string to find the number of digits
num_str = str(num)
num_digits = len(num_str)
# Calculate Armstrong sum
armstrong_sum = 0
for digit in num_str:
armstrong_sum += int(digit) ** num_digits

# Check if Armstrong number


if armstrong_sum == num:
print(f"{num} is an Armstrong number! ❌")
else:
print(f"{num} is NOT an Armstrong number. ❌")
Output:
Enter a number: 153
153 is an Armstrong number!

What is format in Python:


Format is used for better readability in python. Example
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

Output:
My name is Alice and I am 25 years old.

Page No. 19

You might also like