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

Python Control Structures

The document provides an overview of Python programming concepts, focusing on data types, variable assignment, control structures, and operators. It explains mutable and immutable data types, variable naming conventions, input/output functions, and error types. Additionally, it covers operator precedence, bitwise operations, and control flow using if statements.

Uploaded by

dextrojha
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 views82 pages

Python Control Structures

The document provides an overview of Python programming concepts, focusing on data types, variable assignment, control structures, and operators. It explains mutable and immutable data types, variable naming conventions, input/output functions, and error types. Additionally, it covers operator precedence, bitwise operations, and control flow using if statements.

Uploaded by

dextrojha
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

Python

Control
Structures
Mutable & Immutable Data types
❑ A first fundamental distinction that Python makes on data is
about whether or not the value of an object changes.

❑ If the value can change, the object is called mutable, while if


the value cannot change, the object is called immutable.

❑ Python’s mutable data types are: lists, sets and dictionaries.

❑ Immutable data types include numeric data types, strings,


and tuples.
Every object in Python has an ID (or identity), a type,
and a value, as shown in the following snippet:

age = 42
print(id(age)) # id
print(type(age)) # type
print(age) # value

[Output]
10966208
<class ‘int’>
42
❑ Once created, the ID of an object never changes. It is
a unique identifier for it, and it is used behind the
scenes by Python to retrieve the object when we
want to use it.

❑ The type also never changes. The type tells what


operations are supported by the object and the
possible values that can be assigned to it.
Variable assignment in Python and
Automatic Garbage collection
When you do an assignment in Python, it tags the value with
the variable name.
a=1

and if you change the value of the variable, it just changes the
tag to the new value in memory. You don’t need to do the
housekeeping job of freeing the memory here. Python's
Automatic Garbage Collection does it for you. When a value is
without names/tags it is automatically removed from
memory.
a=2
Assigning one variable to another makes a new tag bound to
the same value as shown below.
b=a
Variables
❑ Variables are containers for storing data values
❑ Python has no command for declaring a variable
❑ A variable is created at the moment you first
assign a value to it
Example
x = 5
y = "John"
print(x)
print(y)
Output
5
John
Variables do not need to be declared
with any particular type, and can
even change type after they have
been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Output
Sally
Type Casting

If you want to specify the data type of


a variable, this can be done with
casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Single or Double Quotes?

String variables can be declared either by


using single or double quotes:

Example
x = "John"
# is the same as
x = ’John’
Output
John
John
case-sensitive
variable names are case-sensitive.
This will create two variables:
a = 4
A = "sally"
print(a)
print(A)
#A will not overwrite a
output
4
sally
Variable Names

• A variable can have a short name (like x and


y) or a more descriptive name (age, carname,
total_volume).
• 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)
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Many Values to Multiple Variables
Python allows you to assign values to
multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Output
Orange
Banana
Cherry
One Value to Multiple Variables
And you can assign the same value to
multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Output
Orange
Orange
Orange
Input / Output Functions
print() - used to display the msg on the screen
print("msg"[optional],variable[optional],end
parameter[optional])
The end key of print function will set the string that needs to be
appended when printing is done.
By default the end key is set by newline character.
print("hello all", end=" ")
print("welcome to CME") #prints space between first and second
statement.
Output
hello all welcome to CME
The end key value can be any symbol, letter or number.
input()- to take input from user.
The value should be assigned to a variable
input("msg"[optional])
A=input("enter a number")
By default the input value is string.
If you need numeric you need to specify
explicitly.
B=int(input("enter a number"))
Program for addition of two
numbers
x=10
y=20
z= x + y
print (z)

Output
30
Program for addition of two numbers
using input function
x=int(input(“enter first number”))
y=int(input(“enter second number”))
z= x + y
print (“the result is”,z)

output
enter first number 10
enter second number 20
the result is 30
Operator Precedence in Python
Operator Description
() Parentheses
** Exponentiation (raise to the power)
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^ | Bitwise exclusive `OR' and `OR'
<= < > >= Comparison operators
== != Equality operators
= %= /= //= -= += Assignment operators
*= **=
in not in Membership operators
not or and Logical operators
Program to demonstrate operator precedence
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print("Value of (a + b) * c / d is ", e)
e = ((a + b) * c)) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d) # (30) * (15/5)
print ("Value of (a + b) * (c / d) is ",e)
e = a + (b * c) / d # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e )
Output

Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
num1 = 4
num2 = 5
res = num1 + num2
res += num1 #compound assignment
#res=res+num1
print(" Result of is ", res)

Output
13
Bitwise Operators
Bit 1 Bit 2 Result (&) Bit 1 Bit 2 Result (^)

0 0 0 0 0 0
0 1 0 0 1 1
1 0 0 1 0 1
1 1 1 1 1 0
Variable-1 Variable-2 Output 0 0 0 0 1 1 1 0 1 1 1 1

Bit 1 Bit 2 Result (|)

0 0 0
0 1 1
1 0 1
1 1 1
Converting Decimal to
Binary
Calculating Decimal
Equivalent
Binary Number : 101012

Step Binary Number Decimal Number

1 101012 (1 x 24) + (0 x 23) + (1x 22) + (0 x 21) + (1 x 20)

2 101012 (16 + 0 + 4 + 0 + 1)10

3 101012 2110

101012 is normally written as 10101.


Shift Operators (<< >>):
These operators are used to shift the bits of a
number left or right thereby multiplying or dividing
the number by 2 respectively. They can be used
when we have to multiply or divide a number by 2.
Bitwise right shift: Shifts the bits of the number to
the right and fills 0 on voids left as a result. Similar
effect as of dividing the number with some power
of 2.

Example:
a = 10 0000 1010
a = a >> 1 (= 5) 0000 0101
a = 10
a = a >> 1
0000 1010 #shift to right by 1 bit

__000 0101 #place zero for the vacant


space

0000 0101 #find the decimal equivalent


=5
Bitwise left shift: Shifts the bits of the number to
the left and fills 0 on voids left as a result. Similar
effect as of multiplying the number with some
power of 2.

Example:
a = 5 = 0000 0101
b = a << 1 (= 0000 1010 = 10 )
c = a << 2 (= 0001 0100 = 20 )
a = 5
a=a<<1
0000 0101 #shift to left by 1 bit

0000 101__ #place zero for the vacant


space

0000 1010 #find the decimal equivalent

=10
Program for bitwise operators
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c=a&b # 12 = 0000 1100
print ("Value of c is ",c)
c=a|b # 61 = 0011 1101
print ("Value of c is ",c)
c=a^b # 49 = 0011 0001
print ("Value of c is ",c)
c = a << 2 # 240 = 1111 0000
print ("Value of c is ",c)
c = a >> 2 # 15 = 0000 1111
print("Value of c is ",c)
Output
Value of c is 12
Value of c is 61
Value of c is 49
Value of c is 240
Value of c is 15
Uses of bitwise operators
❑ Bit fields (flags)

❑ Communication over ports/sockets

❑ Compression, Encryption

❑ Graphics
Assignment
❖ WAP to Calculate simple interest
SI=P*R*T/100
❖ WAP to Calculate area of a rectangle
Area=Length*Breadth
❖ WAP to evaluate an expression
x = m + 5mn – 7m2n + nm2 + 9
❖ WAP to swap two numbers.
Input x=10 y=20
Output x=20 y=10
❖ WAP to Convert Celsius To Fahrenheit
F=(9/5*C)+32
Types of Errors
❑ Error:- Abnormal behavior of a program is
called error.

❑ Interpreting Errors

❑ Runtime Errors
Interpreting errors – errors that occur when you ask
Python to run the application. The most common
errors of this type are syntax errors

For example:

x = int(input('Enter a number: ‘)

SyntaxError: EOL while scanning string literal

Y= "hello

SyntaxError: invalid character in identifier


Runtime errors – errors that occur after the code has been
compiled and the program is running. The error of this type will
cause your program to behave unexpectedly or even crash.
An example of a runtime error is the division by zero.

x = float(input('Enter a number: ‘))


y = float(input('Enter a number: ‘))
z = x/y
print (z)
The program above runs fine until the user enters 0 as the
second number

Output

Enter a number: 5
Enter a number: 0
Traceback (most recent call last): File "C:/Python34/Scripts/[Link]",
line 3, in <module> z = x/y ZeroDivisionError: float division by zero
Addition of two complex numbers
print("Format for writing complex number: a+bj")
c1 = complex(input("Enter First Complex Number: "))
c2 = complex(input("Enter second Complex Number: "))
print("Sum of both the Complex number is", c1 + c2)

Output
Format for writing complex number: a+bj
Enter First Complex Number: 7+3j
Enter second Complex Number: 8+6j
Sum of both the Complex number is (15+9j)
Data Type Conversions
1) Explicit
2) Implicit
1. Type Conversion is the conversion of object from one data type to
another data type.
2. Implicit Type Conversion is automatically performed by the Python
interpreter.
3. Python avoids the loss of data in Implicit Type Conversion.
4. Explicit Type Conversion is also called Type Casting, the data types of
objects are converted using predefined functions by the user.
5. In Type Casting, loss of data may occur as we enforce the object to a
specific data type.
Program for Explicit type conversion
s="25"
t="30"
print(s+t)
c=int(s)
d=int(t)
print(c+d)
e=float(s)
print(e)

Output
2530
55
25.0
Program for Implicit type conversion
num1 = 321
num2 = 1.84
print("datatype of num1:",type(num1))
print("datatype of num2:",type(num2))
num3 = num1+ num2
print("Value of num3:“,num3)
print("datatype of num3:",type(num3))

OutPut
datatype of num1: <class 'int'>
datatype of num2: <class 'float'>
Value of num3: 322.84
datatype of num3: <class 'float'>
Control Structures
Python Conditions and If statements
Python supports the usual logical conditions from
mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways,
most commonly in "if statements" and loops.
Syntax of IF
1) if test expression:
statement(s)

2) if test expression:
Body of if
else:
Body of else
3) if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Code 1
a = int(input("enter first number"))
b = int(input("enter second number"))
if b > a:
print("b is greater than a")
Code 2
a = int(input("enter first number"))
b = int(input("enter second number"))
if b > a:
print("b is greater than a")
# you will get an error for indentation
Code 3
a = int(input("enter first number"))
b = int(input("enter second number"))
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Code 4
a = int(input("enter first number"))
b = int(input("enter second number"))
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("b is less than a")
Short Hand If ... Else
If you have only one statement to execute,
one for if, and one for else, you can put it
all on the same line:
Example
Code 5
One line if else statement:
a = int(input("enter first number"))
b = int(input("enter second number"))
print("A") if a > b else print("B") If a>b:
print("A")
else:
print("B")
The "AND" keyword is a logical operator, and is
used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater
than a:
Code 6
a = int(input("enter first number"))
b = int(input("enter second number"))
c = int(input("enter second number"))
if a > b and c > a:
print("Both conditions are True")
The "OR" keyword is a logical operator,
and is used to combine conditional
statements:
Example
Test if a is greater than b, OR if c is
greater than a:
Code 7
a = int(input("enter first number"))
b = int(input("enter second number"))
c = int(input("enter second number"))
if a > b or c > a:
print("OR operator is evaluated")
Nested If example

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


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
The pass Statement
if statements cannot be empty, but if you for
some reason have an if statement with no
content, put in the pass statement to avoid
getting an error.
Example
a = int(input("enter first number"))
b = int(input("enter second number"))
if b > a:
pass
c=a+b
print(c)
Assignment
1) Write a program to check whether the entered by
the user is even or odd.
2) Write a program to find out the greatest among
three numbers.
3) Write an algorithm to arrange the numbers a,b,c in
ascending order.
4) Write a program to check whether the username
and password entered by the user is right or
wrong by matching it with existing values and
accordingly display a message.
5) Write a program to implement simple calculator
for +,-,/ and * using if---elif.
Looping Structures
Python provides following types of loops to handle looping
requirements.
while loop Repeats a statement or group of
statements while a given condition is
TRUE.

for loop Executes a sequence of statements


multiple times. Initialization, condition
checking and increment/decrement is done
inside loop.

nested loops You can use one or more loop inside any
another while, for etc.
Loop Control Statements
Loop control statements change execution from its normal
sequence.

break Terminates the loop statement and transfers


statement execution to the statement immediately following
the loop.

continue Causes the loop to skip the remainder of its body


statement and immediately retest its condition prior to
reiterating.

pass The pass statement in Python is used when a


statement statement is required syntactically but you do not
want any command or code to execute.
While Loop
Syntax : while expression:
statement(s)

In Python, all the statements indented by the same number of


character spaces after a programming construct are considered
to be part of a single block of code.
# prints Hello All 3 Times
c=0
while (c < 3):
print("Hello All")
c=c+1

Output:
Hello All
Hello All
Hello All
For in Loop
In Python, There is "for in" loop which is similar to for each loop
in other languages.

Syntax:
for iterator_var in sequence:
statements(s)

# printing elements of a list


print("List Iteration")
list1 = ["abc", "xyz", "lmn"]
for i in list1:
print(i)

Output:
List Iteration
abc
xyz
lmn
Range() function in For loop
The range() is a built-in function of Python which returns a
sequence of integers. It generates the integer numbers between
the given start to stop integer.
Syntax:
range (start, stop , step)
range() takes three arguments.
Out of the three 2 arguments are optional. I.e., Start and Step are
the optional arguments.
A start argument is a starting number of the sequence. i.e., lower
limit. By default, it starts with 0 if not specified.
A stop argument is an upper limit. i.e. generate numbers up to 1
number les than the upper limit.
The step is a difference between each number in the result. The
default value of the step is 1 if not specified. The step can be
positive or negative.
Example – Using only one argument in range()

print("Print first 5 numbers using range function")


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

Output:
Print first 5 numbers using range function
0
1
2
3
4
Example – using two arguments (start and stop) in range()
function

print("Print integers within given start and stop number


using range() function")
for i in range(5, 10):
print(i)
Output:
Print integers within given start and stop number using
range() function
5
6
7
8
9
Example – using all three arguments in range()
function

print("Printing All odd numbers between 1 and 10 using


range()")
for i in range(1, 10, 2):
print(i)
Output:
Printing All odd numbers between 1 and 10 using range()
1
3
5
7
Nested Loops
Python allows to use one loop inside another loop.
Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)

The syntax for a nested while loop statement


while expression:
while expression:
statement(s)
statement(s)
for i in range(5):
for j in range(i+1):
print("*",end=' ')
print()
Output
*
**
***
****
*****
i=0
while i < 5:
j=0
while j < i+1:
print('*',end=" ")
j=j+1
print()
i=i+1 Output
*
**
***
****
*****
Loop Control Statements
Continue Statement
It returns the control to the beginning of the loop.

for i in range(5):

if i==3:

(“Loop Continued”)

continue

print(i)

Output:
0
1
Loop Continued
2
4
Break Statement

It brings control out of the loop

e.g.

for i in range(5):

print(“OK”,i)

if i==2:

break

print(“Loop Exited”,i)

Output:

OK 0

OK 1

Loop Exited 2
Pass Statement
We use pass statement to write empty loops.
#An empty loop
A=20
B=30
C=A+B
A='geeksforgeeks'
for letter in A :
pass
print(c)
Program to check whether the number is prime or not
num = int(input("Enter a number: "))
f=0
for i in range(2,num):
if (num % i) == 0:
f=1
break
if f==1
print(num ," is not prime number")
else:
print(num ," is a prime number")
Program to display the Fibonacci sequence up to n-th
term

Output:
How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8
n = int(input("how many terms? "))
n1, n2 = 0, 1
print(n1)
print(n2)
c=0
while c < n-2:
n3 = n1 + n2
print(n3)
n1 = n2
n2 = n3
c=c+1
n = int(input("How many terms? "))
n1, n2 = 0, 1
c=0
while c < n:
print(n1)
n3 = n1 + n2
n1 = n2
n2 = n3
c=c+1
Program to calculate factorial of a number

5!=1*2*3*4*5 or 5*4*3*2*1=120

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


f=1
for i in range(1,num + 1):
f=f*i
print("The factorial of ", num," is" , fact)
Assignment
1) Write a Python program to find those numbers which
are divisible by 7 and multiple of 5, between 1500 and
2700
2) Write a Python program that prints all the numbers
from 0 to 10 except 3 and 6.
3) Write a Python program to check whether an
alphabet is a vowel or consonant.
4) Write a Python program to calculate the sum and
average of values from 1.0 to 10.0.
5) Write a Python program to create the multiplication
table of a number, input by user. If user entered 0 then
give display proper message.
6)Write a Python program to construct the following
pattern
1 1
22 12
333 123
4444 1234
55555 12345

7)Find the sum of series 2+22+222+2222+…..n


Output: Enter no. of terms:-5
The series is 2+22+222+2222+22222
The sum is 24690
8)Write a program to find greatest common divisor
(GCD) of any two numbers.
Program to reverse the digits of a number.
Input:-12345 Output:-54321

Number = int(input("Please Enter any Number: "))

Reverse = 0

while(Number > 0):

Remainder = Number %10

Reverse = (Reverse *10) + Remainder

Number = Number // 10

print(" Reverse of entered number is =" ,Reverse)


Program to check whether the entered number is
palindrome or not.
Input:-12321
Output:- The number is palindrome.

n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
for row in range(1,6):
for i in range(row):
print (row, end=" ")
print()

Output:
1
22
333
4444
55555
for row in range(1, 6):
for column in range(1, row + 1):
print(column, end=' ')
Print()

Output:

1
12
123
1234
12345
Python program to check if the number is an
Armstrong number or not.
abc =a3+b3+c3 (for 3 digit number) 153=13+53+43

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


sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum +=digit**3
temp =temp//10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Output:

Enter a number: 663


663 is not an Armstrong number

Enter a number: 407


407 is an Armstrong number

Enter a number: 153


153 is an Armstrong number
Program to check perfect number
NUM= i +j + k ( i , j, k are factors of NUM)
6=1+2+3

n = int(input("Enter any number: "))


sum = 0
for i in range(1, n):
if n % i == 0:
sum = sum + i
if (sum == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")

Output:
Enter any number: 6
The number is a Perfect number!

Enter any number: 25


The number is not a Perfect number!
Assignment
1) Write a program to check whether the number entered by user
is magic number or not. A magic number is a number which is
equal to the product of sum of all digits of a number and
reverse of this sum.
Input:- 1729 The sum of all digits of the number is 19.
Reverse of this number 91.
Product of these values is 19 * 91 = 1729.
Output: This is a magic number.
2) Write a program to print following combinations from 1,2 and
3. Output:
123
132
213
231
312
321

3) Write a program to count the total number of digits of a


number and calculate the sum of digits.

You might also like