0% found this document useful (0 votes)
7 views36 pages

BCA Python Unit-1

The document outlines the syllabus and introduction to Python programming, detailing its history, features, and various data types. It covers Python's syntax, keywords, identifiers, variables, and basic operations, along with input and output functions. Additionally, it discusses Python's data types, including numeric, string, list, tuple, set, and dictionary, as well as operators and comments.

Uploaded by

Suresh Meesala
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)
7 views36 pages

BCA Python Unit-1

The document outlines the syllabus and introduction to Python programming, detailing its history, features, and various data types. It covers Python's syntax, keywords, identifiers, variables, and basic operations, along with input and output functions. Additionally, it discusses Python's data types, including numeric, string, list, tuple, set, and dictionary, as well as operators and comments.

Uploaded by

Suresh Meesala
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/ 36

BCA Semester – lV

( PYTHON PROGRAMMING )
UNIT-I
Syllabus:
Getting Started with Python: Introduction to Python , Python Keywords ,
Identifiers , Variables , Comments, Data Types , Operators, Input and Output , Type
Conversion , Debugging . Flow of Control, Selection , Indentation , Repetition , Break
and Continue Statement , Nested Loops .
Strings- String Operations , Traversing a String , String handling Functions.

Introduction
Python is a very powerful high-level, general-purpose, object-oriented
programming language created by Guido van Rossum in 1989. Python is very
popular for developers and professionals because, it has a rich set of supporting
libraries, and add-on modules. It is a cross-platform(platform-independent) language
and runs on all major operating systems including Windows, Linux, and Macintosh.
Python comes with a powerful and easy to-use graphical user interface (GUI) toolkit
that makes the task of developing GUI applications.

The Python programming language was conceived in the late 1980s, and its
implementation was started in December 1989 by Guido van
Rossum at CWI(Centrum Wiskunde & Informatica) in the Netherlands as a
successor of ABC programming language. Python was published in 1991.

Python Versions and Release Dates


Release dates for the major versions
Python 1.0 - January 1994
Python 2.0 - October 16, 2000
Python 3.0 - December 3, 2008
Python 3.4 - March 16, 2014
Python 3.5 - September 13, 2015
- December 23, 2016

Python 3.8 Oct 14, 2019


Python 3.9 Oct 5, 2020
Python 3.10 Oct. 04, 2021
Python 3.11.0, Oct 24, 2022

. Python 3.13.0, Oct 7, 2024

Latest version of Python “Python 3.13.1, Dec 3, 2024”


Features of Python
1) Easy to Learn and Use
Python is easy to learn as compared to other programming languages. Its
syntax is straightforward. There is no use of the semicolon or curly-bracket,
the indentation defines the code block.

2) Expressive Language
Python can perform complex tasks using a few lines of code.

3) Interpreted Language
Python is an interpreted language, it means the Python program is executed
one line at a time. The interpreted language makes debugging easy and
portable.

4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux,
UNIX, and Macintosh, etc. So, we can say that Python is a portable language.

5) Free and Open Source


Python is freely available for everyone. It is freely available on its official
website www.python.org

6) Object-Oriented Language
Python supports object-oriented language.It supports object-oriented
concepts inheritance, polymorphism, encapsulation, etc.

7) Large Standard Library


It provides a vast range of libraries for the various fields such as machine
learning, web developing, and also for the scripting.

8) GUI Programming Support


Graphical User Interface is used for the developing Desktop applications and
the web applications.

9) Integrated
Python can be integrated with other languages,
like C, C++, and Java.

10) Dynamic Memory Allocation


In Python, we don't need to specify the data-type of the variable. When we
assign some value to the variable, it automatically allocates the memory to
the variable at run time.
Python Language Basics
Interacting with Python
In python standard distribution There are two ways to
work with Python :
1. Command Line Mode (Interactive Mode)
2. IDLE mode(Script Mode)

Command Line Mode


On selecting the Python Command Line, you see the Python Command Line
window displaying the Python prompt (>>>), as shown in Figure

Python Command Line window.

In command line mode, you type Python instructions one line at a time.

IDLE (Integrated DeveLopment Environment)


Python IDLE comes with the standard Python distribution. IDLE combines
an interactive interpreter with code editing and debugging tools. The Python
IDLE Shell window as shown in Figure.

Python Shell window.


Character set:
Any Programming language is required to represent its characters with the help
of character set. An ASCII character set is used to represent characters up to 3rd
generation languages(c/c++). An ASCII character set supports 8 bit characters. The
number of characters that can be represented by this coding system is limited to 256
only. In order to extend ASCII coding system, an universal coding system
(UNICODE) is introduced. Python adapted this coding system for representing its
characters.
Note: There are 65536(0 to 65535) characters are available in UNICODE
character set.

Keywords
Keywords are the reserved words in Python. There are 35 keywords in Python
3.10 This number can vary in different versions of Python. All the keywords except
True, False and None are in lower case. List of Keywords in Python 3.10 given below.

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield

Note: you can always get the list of keywords in your current version by typing the
following in the prompt.
>>> import keyword
>>>keyword.kwlist
>>>len(keyword.kwlist)
Identifiers
Identifier is a user-defined name given to a variable, function, class, module,
etc. using the combination of following characters.
1. Alphabets : A to Z and a to z
2. Digits : 0 to 9
3. Underscore : _

Rules for Naming Python Identifiers


 A keyword cannot be used as identifier.
 It should not contain white space.
 It can be a combination of A-Z, a-z, 0-9, or underscore.
 It should start with an alphabet character or an underscore ( _ ).
 It should not contain any special character other than an underscore ( _ ).
 It cannot start with a digit.

Examples of valid identifiers


Var
Var1
Var_1
_1_var

Examples of Invalid identifiers


1Var
1_Var
Var_$1
Var 1

Variables
Variables are used for storing data in a program. Therefore, by assigning different
data types to variables(you can store numbers, strings, etc.). In Python, we don't
need to specify the data-type of the variable. When we assign some value to the
variable, it automatically allocates the memory to the variable at run time.

For example
A = 10
value = 10.0
st_value="Hello World!"

You can see in the preceding examples the variable can be a single character or a
word or words connected with underscores.
Multiple Assignment
1) Python allows you to assign a single value to several variables.
For example
a=b=c=1
Here, an integer value 1 is assigned all the three variables.
2) Python allows you to assign multiple values to several variables.
For example
a,b,c=1,2,'Hello'
Here, two integer values 1 and 2 are assigned to variables a and b respectively, and
a string "Hello" is assigned to the variable c.

Data Types in Python


Python has several data types that are built into the language. With
these types, you can represent numeric values, text and binary data,
and Boolean values in your code. So, these data types are the basic
building blocks of most Python programs and projects. Python has a rich
set of fundamental data types. The operations on an object depends on
its data type.

Numeric
Integers
This value is represented by int class. It contains positive or negative
whole numbers (without fractions or decimals). Integer datatype has
no limit In Python.
Eg:
n=10
a=b=c=1
x,y=100,200
Float
This value is represented by the float class. It is a real number with a
floating-point representation. It is specified by a decimal point.
Eg:
n=10.25
Complex Number:
A complex number is represented by a complex class. It is specified
as (real part) + (imaginary part)j . For example – 2+3j, where 3j is the
imaginary component and is equal to √-9 (√9 × √−1 = 3i or 3j).
Eg1:
>>> complex(2,3)
(2+3j)

Sequence Type
Strings:
Sequences of Unicode characters. A string can be defined either Single
quotes (or) double quotesor (or) triple quotes. By using triple quotes we can
write multi-line strings.
S1=’abcd’
S2=”welcome”
S3=’’’ Welcome to Python
Programming ’’’

List
List is are just like array that is mutable (changeable) sequence of elements. Each
element or value that is inside a list is called an item. A list is created by placing all
the items (elements) inside a square brackets, separated by comma. It can have any
number of items and they may be of different types (integer, float, string etc.).

Syntax:
List_Name = [item-1,item-2,………,item-n]

# empty list
a=[]

# list of integers
a = [1, 2, 3]

# list with mixed data types


a = [1, "Hello", 3.4]

Tuples
A tuple is a sequence of immutable(Unchanged) elements. Tuples are just like
lists. The differences between tuples and lists are, the tuples cannot be changed
unlike lists and tuples use parentheses, whereas lists use square brackets.
Note: parentheses brackets are optional for Tuples
Syntax:
Tuple_name=(item-1,item-2,…,ietm-n)
Eg:
>>> tup1=('hari','ravi',100,200)
>>> tup1
('hari', 'ravi', 100, 200)

>>> tup2=(1,2,3,4,5)
>>> tup2
(1, 2, 3, 4, 5)

>>> tup3 = "a", "b", "c", "d"


>>> tup3
('a', 'b', 'c', 'd')

>>> t=tuple('PYTHON')
>>> t
('P', 'Y', 'T', 'H', 'O', 'N')

Boolean:
The boolean data type is either True or False. In Python, boolean variables are
defined by the True and False keywords. Note the keywords True and False must
have an Upper Case first letter.
Eg:
a=True
b=False

Sets
A set is a collection of values(elements)with no duplicate elements.This is based
on a data structure known as a hash table. Sets support mathematical operations
like union, intersection, difference, and symmetric difference. Curly braces ( {} )or
the set() function can be used to create sets.

Syntax :
1)Set_name={item-1,item-2,..,item-n}
2)set_name = set([Sequence])

Eg:
>>> a={1,2,3,4,5}
>>> a
{1, 2, 3, 4, 5}

>>> b={1,2,3,1}
>>> b
{1, 2, 3}
>>> s1=set([3,2,5,1,4])
>>> s1
{1, 2, 3, 4, 5}
>>> s2=set((4,2,1,6,3))
>>> s2
{1, 2, 3, 4, 6}
>>> s3=set("WELCOME")
>>> s3
{'E', 'C', 'O', 'L', 'M', 'W'}

Dictionaries
Python dictionary is an unordered collection of items. Creating a dictionary is
placing items inside curly braces {} separated by comma. An item has a key and the
corresponding value expressed as a pair. Each key is separated from its value by a
colon ( key : value ).
Note: Dictionary is based on a data structure known as a hash table.

Syntax:
Dictionary_name = { key-1 : value-1, key-2 : value-2,….., key-n: value-n}

Eg1:
>>> d = {'a':10, 'b':1, 'c':22}
>>> d
{'a': 10, 'b': 1, 'c': 22}

Eg2:
>>> d = {'Name': 'Harsha', 'Age': 6, 'Class': 'First'}
>>> print (d['Name'])
Harsha
>>> print (d['Age'])
6
>>> print (d['Class'])
First

Finding Data Types


To find the data type of the specified object, we use the type() function, which
returns the data type of the object passed to it.
Syntax:
type(value/object)
eg:
>>> type(10)
<class 'int'>

>>> type(10.0)
<class 'float'>

>>> type(‘abc’)
<class 'str'>
>>> type(True)
<class 'bool'>
>>> type(2+3j)
<class 'complex'>

Comments
Comments are text notes added to the program to provide explanatory
information about the source code. Un executable lines in a program are called as
comment lines. Comments lines are for documentation purposes and these lines
are ignored by the interpreter.
Python supports the following types of comments.
 Single line comments
 Multiline (Block)comments
 Inline style comments
 Docstring comments

Single line comments


Begin with a hash symbol (#) at the beginning of the line
Example:
# This is a single line comment

Multi-Line Comments
Python does not provide the option for multiline comments. However, there are
different ways through which we can write multiline comments. We can multiple
hash(#) symbols to write multiline comments in Python.
Example
# Python program to demonstrate
# multiline comments
print("Multiline comments")

Inline style comments


Inline style comments occur on the same line of a statement. Inline style
comments looks like this:
Example:
x=3 # value 3 store in x
y=5 # value 5 store in y

Python Docstrings
Python provides an in-built feature called docstrings for commenting on modules,
methods, functions, objects, and classes. Triple quotes (’’’) can be used to generate
multi-line comments,
Example:
’’’
This is a
Doc string comment
’’’
Python Input and Output
Python provides no. of built-in functions for I/O operations. Some of the
functions like input() and print() are widely used for standard input and output
operations . Let us see the output section first.
Python Output Using print() function
The 'print' function is used to print data to the standard output device(monitor) .

Syntax:
print(objects, sep=' ', end='\n')

 Here, objects are the value(s) to be printed. Objects are separated by


comma.
 The ‘sep’ is used to display separator between the values. Default is a
space character.
 After all values are printed, ‘end’ is printed. Default is a new line.
eg:
print('Welcome')
Output: Welcome

a=5
print('The value of a is', a)
Output: The value of a is 5

print(1,2,3,4,5)
Output: 1 2 3 4 5

print(1,2,3,4,5,sep='*')
Output: 1*2*3*4*5

print(1,2,3,4,5,sep='#',end='$')
Output: 1#2#3#4#5$
python Input
We want to take the input from the user, We use input() function.
Syntax :
input([prompt])

where prompt is the string we wish to display on the screen. It is


an optional.

Note: input function return only string value.


>>> num = input('Enter any number: ')
Enter any number: 10
>>> num
'10'
Here, we can see that the entered value 10 is a string, not a number.

Python Operators
Operator :
Operator is special symbol in Python and it performs a particular
operation.
Operand :
The value on which the operator acts is called as operand.

Python has a number of operators which are classified below.


1)Arithmetic operators
2)Relational operators
3)Logical operators
4)Bitwise operators
5)Assignment operators
6)Special operators
a. Identity operator b. Membership operator

Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
** Exponent
// Floor Division

Ari.py
print('Enter any two Numbers ')
a=int(input())
b=int(input())
print('Addition :',a+b)
print('Subtraction :',a-b)
print('Multiplication :',a*b)
print('Division :',a/b)
print('Modulus :',a%b)
print('Floor Division :',a//b)
print('Exponent :',a**b)

round()
Python provides an inbuilt function round() ,which rounds precision digits of
floating point number.
Syntax:
round(floating number, no of precision digits)
>>>round(10.639 , 2)
10.64
>>> round(10/3,2)
3.33
>>> n=10.3159
>>> n
10.3159
>>> round(n,2)
10.32

2)Relational operators
These are used to test the relation between 2 values or 2 expressions.
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

Logical operators :
These are used to combine the result of 2 or more expressions.
and Logical AND
or Logical OR
not Logical NOT

Exp1 Exp2 Exp1 and Exp2 Exp1 or Exp2


-----------------------------------------------------------------------
True True True True
True False False True
False True False True
False False False False

If Exp=True -> not Exp=False


If Exp=False -> not Exp=True

Bit-wise Operators :
These operators are used for manipulation of data at bit level.
Bit-wise logical operators :
These are used for bit-wise logical decision making.
& Bit-wise logical AND

| Bit-wise logical OR

^ Bit-wise logical XOR


B1 B2 B1 & B2 B1 | B2 B1 ^ B2
---------------------------------------------------------------------
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0

Eg : a=5
b=6
a=5 - 1 0 1
b=6 - 1 1 0

1 0 1
1 1 0
----------------------
a&b : 1 0 0 =4
----------------------

1 0 1
1 1 0
----------------------
a|b : 1 1 1 =7
----------------------

1 0 1
1 1 0
----------------------
a^b : 0 1 1 =3
----------------------

Bit1.py
print('Enter any two Numbers ')
a=int(input())
b=int(input())
print('a & b :',a&b)
print('a | b :',a|b)
print('a ^ b :',a^b)

Bit-wise shift operartor :


The shift operations take binary patterns and shift the bits to the left or right.
<< left shift
>> right shift
Eg :
a=4
a=4 - 1 0 0 (binary form)
b=a<<2 means value of 'a' is to be left shifted by 2 bits and store it in b.
1 0 0

Hence it became,

1 0 0 0 0

then the value of b :-

1 0 0 0 0 = 2 power 4 = 16

a=4 - 1 0 0 (binary form)


c=a>>1 means value of 'a' is to be right shifted by 1 bit and store it in c.

1 0 0

Hence it became,

1 0

then the value of c :-


1 0 = 2 power 1 = 2

Bit-wise shift operartor :


The shift operations take binary patterns and shift the bits to the left or right.

<< - left Shift


>> - Right Shift
Eg :
a=4
a=4 -> 1 0 0 (binary form)
b=a<<2; means value of a is to be left shifted by 2 bits and store it in b.

then the value of b :-


1 0 0 0 0 = 2 power 4 = 16

a=4 -> 1 0 0 (binary form)


c=a>>1; means a is to be right shifted by 1 bit and store it in c.

then the value of c :-


1 0 = 2 power 1 = 2

Bit2.py
a=4
b=a<<2
c=a>>1
print('a :',a)
print('b :',b)
print('c :',c)

Assignment Operators :
These operators are used to assign values to variables.
Simple assignment :
=
compound assignment
+=
-=
*=
/=
//=
%=
**=

n=10, if we want to add 5 to n then we will give


n=n+5
(or)
n+=5 which is compound assignment.

Eg:
>>> n=10
>>> n
10
>>> n+=5
>>> n
15

Special operators
Python language offers two types of special operators. They are
1.identity operators
2.membership operators

Identity operators
‘is’ and ‘is not’ are the identity operators in Python. They are used to check two
values or variables.

is - True if the operands are identical


is not - True if the operands are not identical

eg:
>>> a=10
>>> b=10
>>> c=20
>>> a is b
True
>>> a is not c
True

Membership operators
‘in’ and ‘not in’ are the membership operators in Python.
They are used to test whether a value or variable is found in a sequence(string, list,
tuple,set,Etc.).

in - True if value/variable is found in the sequence


not in - True if value/variable is not found in the sequence
eg:

>>> st='abcd'
>>> 'a' in st
True
>>> 'k' not in st
True
>>> x='a'
>>> x in st
True
>>> "WEL" in "WELCOME"
True
>>> "WCE" in "WELCOME"
False

Type conversion (or) Type casting in Python


Sometimes it is necessary to convert values from one type to another. The
process of converting from one type to another type is called as type casting or
type conversion. To convert one type to another Python supplies several built-in
functions. these functions are

1)float(x) :
This function converts string type to a floating point number

2) int(x)
This function converts string type to integer.

Program
Conv1.py

s=input("Enter any string :")


f=float(s)
print("After converting to float :",f)
n=int(s)
print("After converting to integer :",n)
3. ord(x) :
converts a character to integer(Unicode value).

4.chr(x) :
Converts an integer(Unicode value) to a character

5. str(x) :
Converts integer (or) float into a string.

6.complex(real,imag) :
Converts real numbers to complex number

Eg(Unicode values):
A to Z 65 to 90
a to z 97 to 122
0 to 9 48 to 57
Esc 27
Backspace 8
Enter 13
SpaceBar 32
Tab 9
etc.

program
Conv2.py
c = ord('A')
print ("After converting character to integer :",c)
c = chr(65)
print ("After converting integer to character :",c)
c = str(123)
print ("After converting integer to string :",c)
c = complex(1,2)
print ("After converting integers to complex number :",c)

Debugging
Debugging is the process of finding and fixing errors(bugs) in your code. Here
are some tools and techniques for debugging Python:
Python Debugger (PDB)
Debugging in Python is facilitated by pdb module (python debugger) which comes
built-in to the Python standard library. The major advantage of pdb is it runs purely
in the command line.
pdb supports:
 Setting breakpoints
 Stepping through code
 Source code listing
 Viewing stack traces
Starting Python Debugger
To start debugging within the program just insert import pdb,
pdb.set_trace() commands. Run your script normally.

Example
Debugging a Simple Python program of addition of numbers using Python pdb
module

import pdb
pdb.set_trace()
x = input("Enter first number : ")
y = input("Enter second number : ")
sum=x+y
print(sum)

The pdb prompt can be use the following commands


 help : To display all commands
 where : Display Line number of the current line
 next : Execute the current line and move to the next line
 step : step into functions called at the current line

Indentation
In Python, indentation is used to define blocks of code. It tells the Python
interpreter that a group of statements belongs to a specific block. All statements
with the same level of indentation are considered part of the same
block. Indentation is achieved using whitespace (spaces or tabs) at the
beginning of each line.

Indentation in Python is used to create a group of statements that are executed


as a block. Many popular languages such as C, and Java uses braces ({ }) to define
a block of code, and python uses indentation.
Control Flow
Control flow in Python is the order in which a program's code executes. It is
regulated by loops and conditional statements, etc. Python has three types of control
structures:
 Sequential: The default mode
 Selection: Used for decisions and branching
 Repetition: Used for looping, or repeating a piece of code multiple times

Selection
Conditional statments
1. simple if statement :
It is a conditional controlled statement and is used to control the flow of
execution.
Syntax :

if condition:
statements;

Here condition is Boolean expression and if it is true then the statement


block will be executed and the control transfer to the next statement. Otherwise
if the condition is false, then the control directly goes to the next statement.

Flow Chart

Program:To find maximum value of given 2 values using simple if


If.py
print ("Enter any two values")
a=int(input())
b=int(input())
max=a
if max < b :
max=b
print("Maximum value :",max)
Program:To find maximum value of given 3 values using simple if

print("Enter any 3 values")


a=int(input())
b=int(input())
c=int(input())
max=a
if max < b :
max=b
if max < c:
max=c
print("Maximum value :",max)

2. if-else statement
It is an extension of simple if statement.

The general form of an if-else statement is

if condition :
if block
else :
else block

The condition is a Boolean expression, if it is true then if block will be


executed otherwise else block will be executed.

Program: To find maximum value of given two values using if-else


If-else.py
print ("Enter any two values")
a=int(input())
b=int(input())
if a> b :
max=a
else :
max=b
print("Maximum value :",max)

Program: To check whether the given number is even or odd


if-else1.py
n=int(input("Enter any Number :"))
if n%2==0 :
print("Given Number is Even")
else :
print("Given Number is Odd")

3. Nested if statement :
Using a if statement within another if is called as nested if. If a series of
decisions are involved, we use nested if statement.
Syntax:
if condition-1 :
if condition-2 :
Statement-1
else :
Statement-2
else :
if condition-3 :
Statement-3
else :
Statement-4

Flow Chart
Program:To find maximum of three values using nested if
Nest-if.py

print("Enter any 3 values ")


a=int(input())
b=int(input())
c=int(input())
if a>b :
if a>c :
max=a
else :
max=c
else :
if b>c :
max=b
else :
max=c
print("Maximum value :",max)

4. if-elif-else statement
This statement is also used for a series of decisions are involved.

Syntax:
if condition-1 :
statements-1
elif condition-2 :
statements-2
………………….
………………….
elif condition-n:
statements-n
else :
else block - statements

In this statement, the conditions are evaluated from top to bottom, if the
condition is true then the statements associated that block is executed and the
control transfers to the next statement. Otherwise when all conditions are false then
the final else block statements will be executed.
Flow chart

Program:Find maximum of 3 values using if-elif-else


If-elif.py
print("Enter any 3 values ")
a=int(input())
b=int(input())
c=int(input())
if a>b and a>c :
max=a
elif b>c :
max=b
else :
max=c
print("Maximum value :",max)

REPETITION(Loop control statements ):


loop:
The process of repeatedly executing a block of statement up to specified
number of times is called as loop.
Python supports 2 types of looping statements. They are :
1) while loop
2) for loop
While loop
It is a conditional controlled loop statement in python.

Syntax:
while condition :
statements
In this loop first the condition will be evaluated. If it is true, then the
statement block will be executed. After the execution of statements, the
condition will be evaluated once again, if it is true then the statement block will
be executed once again. This process of repeated execution continues until the
condition becomes false.

#Write a program To Display natural numbers from 1 to given number

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


print("Natural number from 1 to",n)
i=1
while i<=n :
print(i,end='\t')
i=i+1

#To Display Even and Odd numbers from 1 to given number


n=int(input("Enter any Number :"))
print("\nEven number from 1 to",n)
i=1
while i<=n :
if i%2==0 :
print(i,end='\t')
i=i+1
print("\n\nOdd number from 1 to",n)
i=1
while i<=n :
if i%2!=0 :
print(i,end='\t')
i=i+1
#To Display factors of given number
n=int(input("Enter any Number :"))
print("Factors of ",n)
i=1
while i<=n :
if n%i==0 :
print(i,end='\t')
i=i+1

#To check whether the given number is prime or not

print("Enter any Number : ",end='')


n=int(input())
count=0
i=1
while i<=n :
if n%i==0 :
count=count+1
i=i+1
if count==2 :
print("Given Number is Prime")
else :
print("Given Number is Not Prime")

#To calculate and display factorial of given number


n=int(input("Enter any Number :"))
fact=1
while n>=1 :
fact=fact*n
n=n-1
print("Factorial of Given Number :",fact)

The range () Function


The range() function generates and returns a sequence of integers and is very
commonly used in for loop . There are 3 variations of the range() function,
depending on the number of parameters passed to it.

range(x):
Returns a list whose items are consecutive integers from 0 to x-1 .
range(x, y):
Returns a list whose items are consecutive integers from x to y-1 .

range(x, y, step):
Returns a list of integers from x to y-1 , and the difference between each
successive value is the value defined by step.

Note: When step is not specified, its default value is 1.

• range(10) -> 0,1,2,3,4,5,6,7,8,9


• range(1, 10) -> 1,2,3,4,5,6,7,8,9
• range(1, 10, 2) -> 1,3,5,7,9
• range(10, 0, -1) -> 10,9,8,7,6,5,4,3,2,1
• range(10, 0, -2) -> 10,8,6,4,2
• range(2, 11, 2) -> 2,4,6,8,10
• range(-5, 5) -> −5,−4,−3,−2,−1,0,1,2,3,4

The for Loop


The for loop iterates over a range of values. These values can be a numeric
range, or, elements of a data structure like a
string, list, tuple,etc.
Syntax:
for iterating_var in sequence :
statements

Flow chart

# To displays numbers from 1 to Given Number using for


loop

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


print("Natural Number from 1 to",n)
for i in range(1,n+1):
print (i,end='\t')

#To Display Even and Odd numbers from 1 to given number using for loop
n=int(input("Enter any Number : "))
print("\nEven number from 1 to",n)
for i in range(2,n+1,2):
print(i,end='\t')

print("\n\nOdd number from 1 to",n)


for i in range(1,n+1,2):
print(i,end='\t')

Unconditional control statements


1. The break statement
The break statement terminates and exits from the current loop.It is typically
used in an infinite loop.
Syntax:
break

Infinite Loop
An infinite loop is a loop that executes its block of statements repeatedly until
the user forces the loop to quit.

break.py
To display Numbers from 1 to given number,if the given number is greater
than 20 it displays only 1 to 20 using break.
n=int(input("enter any Number :"))
k=1
while True :
print(k,end='\t')
k=k+1
if(k>20 or k > n ):
break

2. The continue Statement


The continue statement stops execution of the current iteration by skipping the
rest of the loop and continuing to execute the loop with the next iterative value.
Syntax:
continue

write a program to display numbers from 1 to 10 except for the values 4 and 7
using continue.

program
k=1
while k <=10 :
if k==4 or k==7:
k=k+1
continue
print (k,end=’\t’)
k=k+1

Output:
1 2 3 5 6 8 9 10

3. The pass Statement


The pass statement is used in Python to indicate an empty block of statements.
Syntax:
pass

write a program to display numbers from 1 to 10 except for the values 4 and 7
using pass

pass.py
k=1
while k <=10 :
if k==4 or k==7:
pass
else:
print (k,end='\t')
k+=1
Output:
1 2 3 5 6 8 9 10

Nested Loops
A nested loop in python involves the inclusion of one loop with in another loop.
This construction allows for interacting over elements in multiple dimensions , such
as rows and columns of a matrix. By using nested loops, complex data structures
can be traversed efficiently. Nested loops in python can be used to solve problems
such as prime numbers in a given range, pattern printing, etc.
Prg:Write a Program to print prime numbers in a given range

patteren1
n=5
*****
*****
*****
*****
*****
n = int(input("Enter the value of n : "))
for i in range(1,n+1) :
for j in range(1,n+1):
print('*',end=' ')
print()

patteren2
n=5
*
**
***
****
*****

n = int(input("Enter the value of n : "))


for i in range(1,n+1) :
for j in range(1,i+1):
print('*',end=' ')
print()

patteren3
n=5
1
22
333
4444
55555
n = int(input("Enter the value of n : "))
for i in range(1,n+1) :
for j in range(1,i+1):
print(i,end=' ')
print()
patteren4:
n=5
1
12
123
1234
12345

n = int(input("Enter the value of n : "))


for i in range(1,n+1) :
for j in range(1,i+1):
print(j,end=' ')
print()

patteren5
n=5
*
* *
* * *
* * * *
* * * * *

n = int(input("Enter the value of n : "))


s=n*2
for i in range(1,n+1) :
print("%*c"%(s,32),end='')
for j in range(1,i+1):
print('*',end=' ')
print()
s=s-2

Strings
A string is a sequence of characters used to store text information. A string can
be enclosed in single quotes (or) double quotes (or) triple quotes. By using triple
quotes we can write multi-line strings.
Eg:
st=' Hello World! '
st=" Hello World! "
st = '''Hello
Welcome To
Python Programming'''
Traversing a string
Traversing a string means accessing all the elements of the string one after the
other by using the index. A string can be traversed using for loop or while loop.
Example:

EX:

>>> st=”HELLO”
>>> print(st) # prints complete string
>>> print(s*2) #prints string 2 times
>>> print(st+”WORLD”) # prints concatenated string

slicing operator ‘:’ is used to access the individual characters of the string.
EX: st.py

# Given String
st = "ABCDEFGH"
# Start Oth index to end
print(st[0:])
# Starts 1th index to 4th index
print(st[1:5])
# Starts 2nd index to 3rd index
print(st[2:4])
# Starts 0th to 2nd index
print(st[:3])
#Starts 4th to 6th index
print(st[4:7])
o/p:
ABCDEFGH
BCDE
CD
ABC
EFG
String functions
str:
Returns a string representation of the specified object.
Syntax:
str(x)
x –dpyoae d caj ocecejbo
eg:
>>> str(123)
'123'
>>> str(10.345)
'10.345'
>>a=[1,2,3,4,5]
>>> str(a)
'[1, 2, 3, 4, 5]'
>>> k=str(a)
>>> k
'[1, 2, 3, 4, 5]'
>>> type(k)
<class 'str'>

max():
Returns the maximum alphabetical character in the string.
eg:
>>> max("ABCDEFGH")
'H'

min():
Returns the minimum alphabetical character in the string.
eg:
>>> min("ABCDEFGH")
'A'

len():
Counts and returns the number of characters in the string.
eg:
>>> len("ABCD")
4
sorted():
Returns the List representation string’ .s arcscaeoss na sdseoo dsoos
>>> st="CFADEB"
>>> sorted(st)
['A', 'B', 'C', 'D', 'E', 'F']
String Methods
lower():
Returns the string converted to lowercase.
eg:
>>> st="WelCome"
>>> st.lower()
'welcome'

upper():
Returns the string converted to uppercase.
eg:
>>> st="WelCome"
>>> st.upper()
'WELCOME'

capitalize()
Return a capitalized version of String, i.e. make the first character
have upper case and the rest lower case.
eg:
>>> st="welcome"
>>> st.capitalize()
'Welcome'
>>> s="abCDeFgH"
>>> s.capitalize()
'Abcdefgh'

swapcase():
Returns the string with uppercase characters converted to lowercase and
lowercase characters converted to uppercase .

Eg:
>>> st="WELcome"
>>> st
'WELcome'
>>> st.swapcase()
'welCOME'

title():
Returns the string with first character of each word converted to uppercase
characters and the rest all characters in lowercase.

eg:
>>> st="welcome to python programming"
>>> st
'welcome to python programming'
>>> st.title()
'Welcome To Python Programming'
isalpha():
Returns True if all characters in the string are alphabetic, otherwise returns
False.
eg:
>>> st="abcd"
>>> st.isalpha()
True
>>> st="123abcd"
>>> st.isalpha()
False

>>> st="wel Come"


>>> st
'wel Come'
>>> st.isalpha()
False

isdigit():
Returns true if all characters in the string are digits, otherwise returns false.
eg:
>>> st="123"
>>> st.isdigit()
True
>>> st="123abcd"
>>> st.isdigit()
False

islower():
Returns True if all characters(alphabets) in the string are lowercase, otherwise
returns False.
eg:
>>> st="abcd"
>>> st.islower()
True
>>> st="abcd123"
>>> st.islower()
True
>>> st="ABCD"
>>> st.islower()
False
>>> st="1234"
>>> st.islower()
False
>>> st="abcdABCD"
>>> st.islower()
False

isupper():
Returns true if all characters(alphabets) in the string are in uppercase, otherwise
returns false.
eg:
>>> st="ABCD"
>>> st.isupper()
True
>>> st="abcd"
>>> st.isupper()
False
>>> st="ABCD123"
>>> st.isupper()
True
>>> st="abcdABCD"
>>> st.isupper()
False
>>> st="1234"
>>> st.isupper()
False

spilt()
Return a list of the words in given string, using the specified 'sep'

syntax:
split(sep=' ')
eg:
>>> st="This is a Book"
>>> st.split()
['This', 'is', 'a', 'Book']
>>> st="abcd*123*ijkl*456"
>>> st.split(sep='*')
['abcd', '123', 'ijkl', '456']

You might also like