0% found this document useful (0 votes)
2 views81 pages

Python Programming - Unit 1

The document provides a comprehensive overview of Python programming concepts, focusing on variables, operators, control flow, and loops. It covers the rules for variable naming, types of operators (arithmetic, assignment, comparison, logical, identity, membership, and bitwise), and the use of conditional statements such as if, if-else, and nested if statements. Additionally, it explains operator precedence and expressions in Python, illustrating these concepts with examples.
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)
2 views81 pages

Python Programming - Unit 1

The document provides a comprehensive overview of Python programming concepts, focusing on variables, operators, control flow, and loops. It covers the rules for variable naming, types of operators (arithmetic, assignment, comparison, logical, identity, membership, and bitwise), and the use of conditional statements such as if, if-else, and nested if statements. Additionally, it explains operator precedence and expressions in Python, illustrating these concepts with examples.
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

Unit II

Variables and Operators: Understanding Python variables, multiple variable


declarations, Operators in Python: Arithmetic operators, Assignment operators,
Comparison operators, Logical operators, Identity operators, Membership operators,
Bitwise operators, Precedence of operators, Expressions.

Control Flow and Loops: Indentation, if statement, if-else statement, chained


conditional ifelif -else statement, Loops: While loop, for loop using ranges, Loop
manipulation using break, continue and pass.
Variables
• Variables are nothing but reserved memory locations to store values. It
means , when you create a variable you reserve some space in memory.

• Based on the data type of a variable, the interpreter allocates memory


and decides what can be stored in the reserved memory. Therefore, by
assigning different data types to variables, you can store integers,
decimals or characters in these variables.
Understanding Python variables:
Rules for Python variables:

• A variable name must start with a letter or the underscore character

• A variable name cannot start with a number

• A variable name can only contain alpha-numeric characters and underscores


(A-z, 0-9, and _ )

• Variable names are case-sensitive (age, Age and AGE are three different
variables)
Assigning Values to Variables:

• Python variables do not need explicit declaration to reserve memory space.


The declaration happens automatically when you assign a value to a variable.
The equal sign (=) is used to assign values to variables.

• A = 100 # An integer assignment

• B = 1000.0 # A floating point

• C = "John" # A string
Multiple Assignment:
• Python allows you to assign a single value to several variables simultaneously.

• Eg:
a=b=c=1
a=1; b=2

Here, an integer object is created with the value 1, and all three variables are assigned to
the same memory location. You can also assign multiple objects to multiple variables.

• You can also assign multiple objects to multiple variables.

Eg:
a,b,c = 1,2,"mrcet”

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.
Output Variables:
• The Python print statement is often used to output variables. Variables do not
need to be declared with any particular type and can even change type after they
have been set.
Example:
x=5 # x is of type int
x = "mrcet " # x is now of type str
print(x)

• To combine both text and a variable, Python uses the “+” character:
Example :
x = "awesome"
print("Python is " + x) OutPut : Python is awesome
Operators in Python
Operators are used to perform operations on variables and values. Python divides the
operators in the following groups:

•Arithmetic operators
•Assignment operators
•Comparison operators
•Logical operators
•Identity operators
•Membership operators
•Bitwise operators
Arithmetic operators

1 Arithmetic Operators + Add two operands or unary plus


>>2+3
5
>>+2
2 Assignment Operators

3 Comparison Operators
- Subtract two operands or unary
>>3-1
2
subtract >>-2
4 Logical Operators

5 Bitwise Operators
* Multiply two operands >>2*3
6

6 Identity Operators
/ Divide left operand with the right >>6/3
7 Membership Operators and result is in float 2.0
Arithmetic operators

1 Arithmetic Operators ** Left operand raised to the power of


right
>>2**3
8
2 Assignment Operators

3 Comparison Operators % Remainder of the division of left >>5%2


4 Logical Operators operand by the right 1

5 Bitwise Operators
//
Division that results into whole number >>7//3
6 Identity Operators adjusted to the left in the number line 2

7 Membership Operators
Arithmetic operators

1 Arithmetic Operators Arithemetic Operators


n1=5
2 Assignment Operators n2=3
Print(n1+n2)
3 Comparison Operators
Print(n1-n2)
4 Logical Operators Print(n1*n2)
Print(n1/n2)
5 Bitwise Operators Print(n1**n2)
Print(n1%n2)
6 Identity Operators Print(n1//n2)

7 Membership Operators
Assignment Operators
Assignment operators are used to assign value to a variable
Assignment operators
>>x=5

1 Arithmetic Operators
Arithmetic Operators
+= >>x+=3
x=x+3 >>print(x)
8
2 Assignment Operators
-= x=x-5
>>x-=5
3 Comparison Operators >>print(x)
0
4 Logical Operators
*= >>x*=2
5 Bitwise Operators x=x*2 >> print(x)
10
6 Identity Operators
>> x/=2
/= x=x/3 >> print(x)
7 Membership Operators 2.5
Comparison operators

1 Arithmetic Operators
Arithmetic Operators
> True if left operand is greater than >>2>3
the right False
2 Assignment Operators

3 Comparison Operators
< True if left operand is less than the >>2<3
right True

4 Logical Operators
==
>>2==2
5 Bitwise Operators True if left operand is equal to right
True

6 Identity Operators
!= True if left operand is not equal to >>x!=2
7 Membership Operators the right True
Comparison operators
#Comparison/Relational Operators
1 Arithmetic Operators
Arithmetic Operators n1=10
2 Assignment Operators n2=20
n3=30
3 Comparison Operators Print(n3>n2)
Print(n2 == n3)
4 Logical Operators
Print( n!= n2)
5 Bitwise Operators
Output :
6 Identity Operators True
>>x!=2
7 Membership Operators
False True
True
Logical operators

1 Arithmetic Operators
Arithmetic Operators

2 Assignment Operators and >>x < 5


Returns True if both statements are true
and x < 10
3 Comparison Operators

4 Logical Operators or >> x < 5 or


Returns True if one of the statements is true
x<4
5 Bitwise Operators

6 Identity Operators not Reverse the result, returns False if the result >>not (x<5
is true and x<10)
7 Membership Operators
Logical operators

1 Arithmetic Operators
Arithmetic Operators
#Logical Operator
2 Assignment Operators x=3
y=4
3 Comparison Operators
print(x>5 and y<6)
4 Logical Operators print(x>5 or y<6)
print(not x!=5)
5 Bitwise Operators

6 Identity Operators Output :


False
7 Membership Operators True
False
Bitwise Operators

Bitwise operators are used to perform bitwise


calculations on integers
Bitwise operators

1 Arithmetic Operators
Arithmetic Operators

2 Assignment Operators a|b 111 7


Perform OR operation on each bit of 101 5
the no. 111 7
3 Comparison Operators

4 Logical Operators a&b 111 7


Perform AND operation on each bit 101 5
of the number. 101 5
5 Bitwise Operators

6 Identity Operators a^b


Perform XOR operation on each bit 111 7
101 5
7 Membership Operators of the number. 010 2
Bitwise operators

1 Arithmetic Operators
Arithmetic Operators

2 Assignment Operators a>>b 3 >>2 = 0


Shift a right by b bits
0011 0000
3 Comparison Operators

4 Logical Operators a<<b 3 <<2 = 12


Shift a left by b bits
0011 1100
5 Bitwise Operators

6 Identity Operators

7 Membership Operators
a=6 #110
Output :
b=2 #010
Bitwise and = 2
print('Bitwise and =', a&b) Bitwise or = 6
Bitwise xor = 4
print('Bitwise or =', a| b) right shift = 1
print('Bitwise xor =', a^b) left shift = 8

print('right shift = ', a >>2)


print('left shift = ', b <<2)
Identity Operators

The identity operators in Python are used to determine


whether a value is of a certain class or type.
Identity operators

1 Arithmetic Operators
Arithmetic Operators

2 Assignment Operators is True if the operands are identical


>>x=y
>>x is y
(refer to the same object) True
3 Comparison Operators

4 Logical Operators
Is not True if the operands are not identical (do >>x=y
>>x is not y
5 Bitwise Operators not refer to the same object)
False

6 Identity Operators

7 Membership Operators
Membership Operators

Used to check whether a value/variable exists


in the sequence like
string, list, tuples, sets, dictionary or not
Membership operators

X=[1,2,3,4,5]
1 Arithmetic Operators
Arithmetic Operators

2 Assignment Operators in True if it finds elements in the >>3 in x


specified sequence True
3 Comparison Operators

4 Logical Operators Not in


True if it does not find elements in >>3 not in x
the specified sequence False
5 Bitwise Operators

6 Identify Operators

7 Membership Operators
#Identity operators #Membership operators
a=10 L1=[1,2,3,4]
b=10 print(3 in L1)
print(a is b)
Output : True
Output : True

L1=[1,2,3,4]
a=10
print(5 not in L1)
b=20
print(a is not b)
Output : True
Output : True
Operator Precedence
Precedence of Operators:
• This is is used in an expression with more than one operator with
different precedence to determine which operation to perform first.
Example 1:
>>> 3+4*2
11

Multiplication gets evaluated before the addition operation

>>> (10+10)*2
40

Parentheses () overriding the precedence of the arithmetic operators


a = 20
b = 10
c = 15 OUTPUT :
d=5 90.0
e = (a + b) * c / d 90.0
print(e) 90.0
50.0
e = ((a + b) * c) / d
print(e)
e = (a + b) * (c / d);
print(e)
e = a + (b * c) / d;
print(e)
Expressions:
• An expression is a combination of values, variables, and operators. An
expression is evaluated using assignment operator.

Examples: Y=x + 17 >>> x=10


>>> x=10 >>> y=20
>>> z=x+20 >>> c=x+y
>>> print(z) >>> print(c)
30 30

A value all by itself is a simple expression, and so is a variable.


>>> y=20
>>> print(y)
20
• Python also defines expressions only contain identifiers, literals, and
operators. So,

• Identifiers: Any name that is used to define a class, function, variable


module, or object is an identifier.
• Literals: These are language-independent terms in Python and should
exist independently in any programming language. In Python, there are
the string literals, byte literals, integer literals, floating point literals, and
imaginary literals.

• Operators: In Python you can implement the above mentioned


operators using their corresponding token.
Some of the python expressions are:

Conditional expression:
• Syntax:
true_value if Condition else false_value

x = "greater" if 3>4 else "smaller"


print(x)

Output : smaller
CONDITIONAL STATEMENTS (Decision Making)

• Conditional statement in python perform different computations or actions


depending on whether a specific Boolean constraint evaluates to True or False.

• Conditional statements are handled by if statement in python.

• Python language provide the following conditional(Decision making) statements.

 if statement
 (if-else)statement
 Nested if statement
 if...elif..else ladder
33
The if statement
• The if statement is a decision making statement. It is used to control the flow of
execution of the statements and also used to test logically whether the condition is
true or false.

Syntax

if Test expression:
statement(s)

34
Example program Example program

a=10 a=10
if (a<=10): if (a<=10):
print("condition is true") print("condition is true")

Output :
Output :
condition is true
File "<string>", line 3
print("condition is true")
^
IndentationError: expected an indented block

35
n=4
if n%2==0:
print(n,"is even")

Output : 4 is even

n=int(input("Enter any positive integer :"))


if n%2==0:
print(n,"is even")

Output :
Enter any positive integer : 2
2 is even
If … else Statement
 The if…else statement is called alternative execution, in which there are two
possibilities and the condition determines wich one gets executed.

Syntax

if Test_expression:
Body of if
else:
Body of else

37
Write a program to check if a number is Odd or Even

n=int(input("Enter any positive integer :"))


if n%2==0:
print(n,"is Even")
else:
print(n,"is Odd")

OUTPUT
Enter any positive integer : 7
7 is Odd
38
Note : If u have only one statement to execute you can put it on the same line

Example:

a=int(input("Enter a value:"))
b=int(input("Enter b value:"))

print("a is greater") if a>b else print("b is greater")

Output :
Enter a value:8
Enter b value:42
b is greater
Nested if - else :We can write an entire if… else statement in another if… else
statement called nesting, and the statement is called nested if.

Syntax:
if condition 1 :
if condition 2 :
statement 1
else :
statement 2
else:
statement 3
Nested if-else statement-Example

a=int(input("Enter any integer number : "))


b=int(input("Enter any integer number : "))
c=int(input("Enter any integer number : "))
if a>b:
if a>c:
print(a,"is greater")
else:
OUTPUT
print(c,"is greater") Enter any integer number : 20
else: Enter any integer number : 40
if b>c: Enter any integer number : 30
print(b,"is greater") 40 is greater
else:
print(c,"is greater")
• Example program2

n = int(input("Enter number:"))
if (n<=15):
OUTPUT
if (n == 10): Enter number : 10
print("play cricket")
Play cricket
else:
print("play kabaddi")
else:
print("Don't play game")

42
if-elif - else ladder statement
• elif – is a keyword used in Python in replacement of else if to place another condition
in the program. This is called chained conditional.

Syntax:
if Condition 1 :
statement block1
elif Condition 2 :
statement block2
elif Condition 3 :
statement block3

….
else :
default statement
Example1: largest among three numbers

a = int(input(“Enter 1st number:”))


b= int(input(“Enter 2nd number:”))
c= int(input(“Enter 3rd number:”))
OUTPUT
if (a > b) and (a > c):
Enter 1st number:10
print("a is greater")
Enter 2nd number:25
elif (b >a) and (b > c): Enter 3rd number:15
print(“b is greater") b is greater
else:
print(“c is greater")

44
Example2:
avg=int(input("Enter average of a student : "))
if avg>=70:
print("Distinction")
elif avg>=60:
print("First Class")
Output :
elif avg>=50:
Enter average of a student : 65
print("Second Class") First Class
elif avg>=40:
print("Third Class")
else:
print("failed")
LOOPS/REPETITIVE STATEMENTS

• A loop statement allows us to execute a statement or group of statements multiple


times as long as the condition is true.
• Repeated execution of a set of statements with the help of loops is called iteration.
• Loops statements are used when we need to run same code again and again, each time
with a different value.

• In Python Iteration (Loops) statements are of three types:

1. While Loop
2. For Loop
3. Nested For Loops
s 46
While loop
• Loops are either infinite or conditional. Python while loop keeps reiterating a block
of code defined inside it until the desired condition is met.
• The statements that are executed inside while can be a single line of code or a block
of multiple statements.

Syntax:

while(expression):
Statement(s)
#Example Program to demonstrate while loop
OUTPUT :
i=1
WELCOME TO MRCET
while i<=5: WELCOME TO MRCET
WELCOME TO MRCET
print("WELCOME TO MRCET") WELCOME TO MRCET
WELCOME TO MRCET
i=i+1

#Display n natural numbers from 1 to n


OUTPUT :
n=int(input("Enter n value: "))
Enter n value: 6
i=1 1
2
while i<=n: 3
4
print(i) 5
6
i=i+1
#W.A.P to find factorial of a given number

n=int(input("Enter any positive integer: "))


fact=1;
while n>=1:
fact=fact*n
n=n-1
print("Factoril of a given number is = ",fact)

OUTPUT :
Enter any positive integer: 5
Factoril of a given number is = 120
Write a program to find sum of n natural numbers

num = int(input("Enter a number: "))


sum = 0
while(num > 0):
sum = sum+num
num = num-1
OUTPUT
print("The sum is",sum)
Enter a number: 10
The sum is 55

50
Using else statement with while loops
 Python supports t have an else statement associated with a loop
statement.
 If the else statement is used with a while loop, the else statement
is executed when the condition false.
Program to illustrate the else in while loop
counter=0
while counter < 3: OUTPUT
Inside loop
print("Inside loop")
Inside loop
counter = counter + 1 Inside loop
else: Outside loop
print("Outside loop")
51
For loop statement
• The for loop is another repetitive control structure, and is used to execute a set of
instructions repeatedly, until the condition becomes false.

• The for loop in Python is used to iterate over a sequence (list, tuple, string) or
other iterable objects. Iterating over a sequence is called traversal

Syntax
Syntax: for var in sequence: A sequence of values assigned to
Statement(s) var in each iteration

Holds the value of item


in sequence in each iteration
52
For loop flow chart # Sample program
numbers = [1, 2, 4, 6, 11, 20]
for val in numbers:
seq=val*val
print(seq)

OUTPUT :
1
4
16
36
121
400
Iterating over a list: Iterating over a Tuple:
list = [6, 5, 3, 8, 4, 2, 5, 4]
sum = 0 tuple = (2,3,5,7)
for val in list: for a in tuple:
print (a)
sum = sum+val
print("The sum is", sum)

OUTPUT :
2
3
5
OUTPUT : 7
The sumis 37

54
Iterating over a String: OUTPUT :
M
R
College=“MRCET”
C
for name in College: E
print(name) T

Iterate over a string of a word Datacamp


and print the letter a
OUTPUT :
a
for i in “Datacamp” : a
if i==‘a’: a
print(i)
The range() Function
• The range() function returns a sequence of numbers, starting from 0 (by
default),and incremented by 1 (by default),and ends at a specified number.

Example1:
OUTPUT :
for x in range(6):
0 1 2 3 4 5
print(x,end=' ')

Example2:
for x in range(2,6): OUTPUT :
2 3 4 5
print(x, end=' ')
Note : The range() function defaults to increment the sequence by 1,however it is
possible to specify the increment value by adding third parameter.

Example:
for x in range(2,20,2): OUTPUT :
print(x, end=' ') 2 4 6 8 10 12 14 16 18

for Loop with else


Example:
genre = ['pop', 'rock', 'jazz'] OUTPUT
for i in range(len(genre)): I like pop
print("I like", genre[i]) I like rock
I like jazz
else: No items left
print("No items left.")
Nested For loop
When one Loop defined within another Loop is called Nested Loops.

Syntax:

for val in sequence:


for val in sequence:
statements
statements
Example1: OUTPUT :
1
12
for i in range(1,6):
123
for j in range(1,i+1): 1234
print(j , end=" ") 12345
print(" ")

Example2:
OUTPUT :
1
for i in range(1,5):
22
for j in range(i):
print(i , end=" ")
333
print( )
4444
Break and continue
 You might face a situation in which you need to exit a loop completely when an
external condition is triggered or there may also be a situation when you want to
skip a part of the loop and start next execution.

 Python provides break and continue statements to handle such situations and to
have good control on your loop.

Break:
• The break statement is used to terminate the loop or statement in which it is
present.

• If the break statement is present in the nested loop, then it terminates only those
loops which contains break statement.
FLOW CHART
while test expression:
if condition:
break

# code outside while loop

for var in sequence:


# code inside for loop
if condition:
break
# code inside for loop
# code outside for loop
# Program to display all the elements before number 88

for num in [11, 9, 88, 10, 90, 3, 19]:


if(num==88):
print("The number 88 is found")
print("Terminating the loop")
break
print(num)

Output:
11
9
The number 88 is found
Terminating the loop
#Example:
for letter in "Python": # First Example
if letter == "h":
break
print("Current Letter :", letter )

Output:
Current Letter : P
Current Letter : y
Current Letter : t
CONTINUE:
• The continue statement is used to skip the rest of the code inside a loop for the
current iteration only. Loop does not terminate but continues on with the next
iteration.

for var in sequence:


# code inside for loop
If condition:
continue
# code inside for loop
# code outside for loop

while test expression


If condition:
continue
# code inside while loop
# code outside while loop
# Example
for letter in "Python":
if letter == "h":
continue
print("Current Letter :", letter)

Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
# Program to show the use of # program to display only odd numbers
continue inside loops

for val in "string": for num in [20, 11, 9, 66, 4, 89, 44]:
if val == "i": if num%2 == 0:
continue continue
print(val) print(num)

Output: Output:
s
t 11
r 9
n 89
g
Pass statement

• As the name suggests pass statement simply does nothing. The pass statement in Python is
used when a statement is required syntactically but you do not want any command or code
to execute.

• It is like null operation, as nothing will happen is it is executed. Pass statement can also be
used for writing empty loops.

• Pass is also used for empty control statement, function and classes.

Syntax:
pass
# Python program to demonstrate pass statement

s='MRCET' Output:
for i in s: M
if i == 'C': R
pass # No error will be raised C
print(i) E
T
List Comprehension:
• List Comprehension provide a concise way to create lists.
• List comprehension offers a shorter syntax when you want to create a new list based
on the values of an existing list.
• For example, assume we want to create a list of squares like,

Which is more concise and readable.


list=[]
for x in range(10):
[Link](x**2) List1=[x**2 for x in range(10)]
print(list) print(List1)

Output:
Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Example: Based on a list of fruits, you want a new list, containing only the fruits
with the letter "a" in the name. Without list comprehension you will have to write
a for statement with a conditional test inside:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


newlist = []
for x in fruits:
if "a" in x:
[Link](x)
print(newlist)

Output :

['apple', 'banana', 'mango']


With list comprehension you can do all that with only one line of code:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)

Output :
['apple', 'banana', 'mango']
x=[m for m in range(8)]
List1=[x**2 for x in range(10) if x>4]
print(x) print(List1)

Output : Output:
[0, 1, 2, 3, 4, 5, 6, 7] [25, 36, 49, 64, 81]

list=[x**2 for x in range(1,11) if x%2==1]


print(list)

Output :
[1, 9, 25, 49, 81]
Tuple Comprehension:
Tuple Comprehensions are special: The result of a tuple comprehension is special. You might expect
it to produce a tuple, but what it does is produce a special "generator" object that we can iterate
over.

For example:
x = (i for i in 'abc’) #tuple comprehension
print(x)

Output:
<generator object <genexpr> at 0x033EEC30>

we might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr> at
0x02AAD710>
• The result of a tuple comprehension is not a tuple: it is actually a generator. The only
thing that you need to know now about a generator now is that you can iterate over it,
but ONLY ONCE.

Output:
x = (i for i in 'abc')
a
for i in x:
b
print(i) c

#Create a list of 2-tuples like (number, square):


z=[(x, x**2) for x in range(6)]
print(z)
Output:
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
Set Comprehension:
Similarly to list comprehensions, set comprehensions are also supported:
Example: 1
Output:
a = {x for x in 'abracadabra' if x not in 'abc'}
{'r', 'd’}
print(a)

Example:2
Output:
x={3*x for x in range(10) if x>5}
{18, 21, 24, 27}
print(x)
Dictionary Comprehension:

• Dictionary comprehensions can be used to create dictionaries from arbitrary key


and value expressions:

>>> z={x: x**2 for x in (2,4,6)}


>>> z
{2: 4, 4: 16, 6: 36}

>>> dict1 = {x: x*x for x in range(6)}


>>> dict1
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Exercises:
• 1: Print First 10 natural numbers using while loop
• 2: Print the following pattern
• 1
• 12
• 123
• 1234
• 12345
• 3: Accept number from user and calculate the sum of all number between 1 and given
number
• 4: Print multiplication table of given number
• 5: Given a list iterate it and display numbers which are divisible by 5 and if you find
number greater than 150 stop the loop iteration
• list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
# Program to check if a number is prime or not

num = int(input("Enter a number: "))


if num > 1 :
Output:
for i in range(2, num): Enter a number: 5
5 is a prime number
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
# Program to print prime numbers between given interval

lower=int(input("Enter Lower Range :"))


upper=int(input("Enter upper Range :"))
for num in range(lower,upper+1): Output:
Enter Lower Range :1
if num > 1 : Enter upper Range :10
for i in range(2, num): 2
3
if (num % i) == 0: 5
break 7
else:
print(num)
# Program to calculate sum of individual digits of a given number

num=input("Enter a number :") num=int(input("Enter a number :"))


sum=0 sum=0
for digit in num: for digit in str(num):
sum=sum+int(digit) sum=sum+int(digit)
print("sum=",sum) print("sum =",sum)

Output: Output:
Enter a number :567 Enter a number :978
sum= 18 sum = 24
# Program to check the given no is Armstrong or not

num = int(input("Enter a number: "))


sum = 0 ; count=0 Output1:
temp = num Enter a number: 153
while temp!=0: 153 is an Armstrong number
temp=temp//10
count=count+1 Output2:
temp=num Enter a number: 1634
1634 is an Armstrong number
while temp > 0:
digit = temp % 10
Output3
sum=sum+(digit**count) Enter a number: 123
temp //= 10 123 is not an Armstrong number
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

You might also like