0% found this document useful (0 votes)
25 views26 pages

Bca Python 4th Sem

This document provides an introduction to Python, covering its popularity, key features, and various applications. It explains fundamental concepts such as variables, data types, operators, input/output functions, type conversion, debugging, and conditional statements. The content is structured into sections, making it a comprehensive guide for beginners learning Python programming.

Uploaded by

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

Bca Python 4th Sem

This document provides an introduction to Python, covering its popularity, key features, and various applications. It explains fundamental concepts such as variables, data types, operators, input/output functions, type conversion, debugging, and conditional statements. The content is structured into sections, making it a comprehensive guide for beginners learning Python programming.

Uploaded by

VCR JC
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT -1

Getting Started with Python

1. What is Python?

Python is a high-level, interpreted, and general-purpose programming language that is


easy to learn and powerful to use.
It was created to make programming simple, readable, and efficient, especially for
beginners.

Why Python is So Popular

Python is widely used by students, teachers, and professionals because:

 ✅ Easy to learn – English-like syntax


 ✅ Less code – Do more work with fewer lines
 ✅ Free & Open Source
 ✅ Huge library support
 ✅ Used everywhere – from school projects to AI research

Key Features of Python

 🧠 Simple & Readable Syntax


 ⚡ Interpreted Language (no need to compile)
 🔁 Dynamically Typed
 🧩 Object-Oriented
 🌍 Cross-platform (Windows, macOS, Linux)

Where is Python Used?

Python is used in many real-world fields:

 📊 Data Science & Data Analysis


 🤖 Artificial Intelligence & Machine Learning
 🌐 Web Development (Django, Flask)
 🧪 Scientific & Research Computing
 🎮 Game Development
 📱 Automation & Scripting

First Python Program


print("Hello, World!")

📌 Output:
Hello, World!

1|Page
2. Python keywords:
Python keywords are reserved words with special meanings that cannot be used
as variable names, function names, or identifiers. They form the core syntax for
control flow, data types, and program structure in Python 3.

Complete List

Use import keyword; print([Link]) to view them dynamically. The 35


standard keywords (Python 3.12+) are:

Category Keywords

Booleans False, None, True

Logical and, not, or

Control Flow if, elif, else, for, while, break, continue, pass

Functions def, return, lambda, yield

Classes/OOP class, global, nonlocal, del

Exceptions try, except, finally, raise, assert

Modules import, from, as

Async async, await

Misc in, is, with

Rules for Naming Identifiers in Python

Python follows strict rules for identifiers:

✅ Can contain letters (a–z, A–Z), digits (0–9), and underscore (_)

❌ Must NOT start with a digit


1value ❌
value1 ✅

2|Page
❌ No special characters like @, $, #, %
total$ ❌
total_ ✅

❌ Keywords cannot be used as identifiers


class ❌
for ❌

✅ Python identifiers are case-sensitive


marks ≠ Marks

Valid vs Invalid Identifiers


Valid Identifiers Invalid Identifiers
age 2age ❌
_count total-marks ❌
student_name class ❌
Score1 @value ❌

3. What is a Variable?

A variable is a name that stores data (value) in a program.


In Python, variables are used to store information that can be used and changed later.

📌 Simple definition:

Variable = name given to a memory location that holds a value

Creating Variables in Python

👉 Python does not require any declaration.


x = 10
name = "Ravi"
marks = 95.5

Here:

 x, name, marks → variables


 10, "Ravi", 95.5 → values

Dynamic Typing

Python automatically decides the type of variable based on the value.


x = 10 # integer
x = "Hello" # now string

3|Page
✔ Same variable
✔ Different data types
➡️This is called dynamic typing

Types of Variables (Based on Data)

Examples:
age = 18 # int
percentage = 92.5 # float
student = "Anu" # string
passed = True # boolean

Assigning Multiple Variables

Python allows multiple assignment in one line.


a, b, c = 10, 20, 30

Or same value to multiple variables:


x = y = z = 5

Rules for Variable Names

Variables must follow identifier rules:

 Must start with a letter or _


 Cannot start with a number
 No special symbols
 Cannot use keywords
 Case-sensitive
total_marks = 450 # valid
2marks = 50 # invalid ❌

Updating Variable Values

Variables can be changed anytime.


score = 50
score = 75

➡️Old value is replaced by new value.

Simple Real-Life Example


price = 100
price = price + 20
print(price)

📌 Output:
120

4|Page
4. What are Comments?

Comments are non-executable lines in a Python program.


They are written to explain code and make it easy to understand for humans.

📌 Definition:

Comments are statements ignored by the Python interpreter.

Why Do We Use Comments?

 🧠 To explain logic
 📖 To make code readable
 For debugging
 👥 For team collaboration

Types of Comments in Python

1 Single-Line Comments

Use # symbol.
# This is a single-line comment
x = 10 # assigning value to x

👉 Everything after # is ignored by Python.

2 Multi-Line Comments

Python has no special multi-line comment symbol.


But we use triple quotes (''' or """) as a workaround.
"""
This is a multi-line comment
Used to explain multiple lines
"""
x = 20

or
'''
This is also a multi-line comment
'''

Mostly used for documentation, not for execution.

3 Docstrings (Special Comment)

Used to describe functions, classes, or modules.


def add(a, b):
"""This function adds two numbers"""
return a + b

5|Page
5. What is data types in python ?

A data type specifies the kind of data a variable can store.


In Python, data types help the interpreter understand how much memory to allocate and
what operations are allowed.

📌 Definition:

Data type defines the type of value stored in a variable.

Built-in Data Types in Python

1 Numeric Data Types

Used to store numbers.


Type Example
int 10, -5, 100
float 3.14, 92.5
complex 2+3j
a = 10
b = 2.5
c = 3+4j

2 String Data Type (str)

Used to store text.


name = "Ravi"
subject = 'Python'

✔ Strings can be written using single or double quotes

3 Boolean Data Type (bool)

6|Page
Stores True or False values.
passed = True
failed = False

👉 Mostly used in conditions

4 List Data Type (list)

 Stores multiple values

 Ordered

 Mutable (can be changed)


marks = [85, 90, 78]

5 Tuple Data Type (tuple)

 Stores multiple values

 Ordered

 Immutable (cannot be changed)


coordinates = (10, 20)

6 Set Data Type (set)

 Stores unique values

 Unordered
subjects = {"Maths", "Physics", "Chemistry"}

7 Dictionary Data Type (dict)

 Stores data as key–value pairs

 Very powerful data type


student = {
"name": "Anu",
"age": 17,
"marks": 92
}

Mutable vs Immutable Data Types


Mutable Immutable
list int
dict float
set string
tuple

7|Page
Checking Data Type

Use type() function.


x = 10
print(type(x))

Output:
<class 'int'>

Type Conversion (Type Casting)


a = int("10")
b = float(5)
c = str(25)

6. What is a Operator Types ?

Type Examples Purpose

Math operations like addition (5+3=8), floor division (9//2=4), exponent


Arithmetic +, -, *, /, //, %, ** (2**3=8)

Comparison ==, !=, >, <, >=, <= Boolean checks, e.g., 5 > 3 returns True

Assignment =, +=, -=, *=, /= Assign or update values, e.g., x += 5 (same as x = x + 5)

Logical and, or, not Combine conditions, e.g., True and False is False

Membership in, not in Check presence, e.g., 'a' in 'apple' is True

Identity is, is not Object identity, e.g., x is None

Bitwise &, ` , ^ , ~ , <<, >>`

Arithmetic Operators

Operator Example Code Output

+ print(10 + 5) 15

- print(10 - 5) 5

8|Page
Operator Example Code Output

* print(10 * 5) 50

/ print(10 / 5) 2.0

// print(10 // 3) 3

% print(10 % 3) 1

** print(2 ** 3) 8

Comparison Operators

Operator Example Code Output

== print(5 == 5) True

!= print(5 != 3) True

> print(5 > 3) True

< print(5 < 3) False

>= print(5 >= 5) True

<= print(5 <= 3) False

Assignment Operators

Operator Example Code Output (x final)

= x = 10 10

+= x = 5; x += 3 8

9|Page
Operator Example Code Output (x final)

-= x = 5; x -= 3 2

*= x = 5; x *= 3 15

/= x = 10; x /= 2 5.0

//= x = 10; x //= 3 3

%= x = 10; x %= 3 1

**= x = 2; x **= 3 8

Logical Operators

Operator Example Code Output

and print(True and False) False

or print(True or False) True

not print(not True) False

Membership & Identity

Operator Example Code Output

in print('a' in 'apple') True

not in print('z' not in 'apple') True

is x = [1]; y = x; print(x is y) True

is not print(x is not None) True

10 | P a g e
Bitwise Operators

Operator Example Code Output

& print(5 & 3) 1

` ` `print(5

^ print(5 ^ 3) 6

~ print(~5) -6

<< print(5 << 1) 10

>> print(5 >> 1) 2

7. What is Input and Output?

 Input → Taking data from the user

 Output → Displaying result to the user

📌 Definition:

Input and Output allow interaction between the user and the program.

🔹 Input in Python

input() Function

Used to take input from the user.


name = input("Enter your name: ")

 Whatever the user enters is taken as string by default.

Example
age = input("Enter your age: ")
print(age)

11 | P a g e
If user enters 18,
age stores "18" (string).

Taking Integer Input (Type Casting)

To use numbers, convert input:


age = int(input("Enter your age: "))

Other conversions:
price = float(input("Enter price: "))

Output in Python

print() Function

Used to display output.


print("Hello World")

Printing Variables
marks = 95
print(marks)

Printing Multiple Values


name = "Anu"
age = 17
print(name, age)

Output:
Anu 17

Using Separator (sep)


print("A", "B", "C", sep="-")

Output:
A-B-C

Using End (end)


print("Hello", end=" ")
print("World")

Output:
Hello World

🔹 Formatted Output

Using f-string (Best & Easy)


name = "Ravi"
marks = 92
print(f"{name} scored {marks} marks")

12 | P a g e
Output:
Ravi scored 92 marks

Using format()
print("Marks = {}".format(95))

Complete Input–Output Program


name = input("Enter name: ")
marks = int(input("Enter marks: "))

print(f"Student Name: {name}")


print(f"Marks: {marks}")

8. What is Type Conversion?

Type conversion means changing one data type into another.

📌 Definition:

Type conversion is the process of converting a value from one data type to another.

Types of Type Conversion in Python


1 Implicit Type Conversion (Automatic)

Python automatically converts one data type into another without programmer
intervention.

Example
a = 10 # int
b = 2.5 # float
c = a + b
print(c)
print(type(c))

Output:
12.5
<class 'float'>

👉 int is converted to float automatically.

2 Explicit Type Conversion (Type Casting)

Programmer manually converts data type using functions.

Common Type Casting Functions


Function Converts To
int() Integer
float() Float

13 | P a g e
Function Converts To
str() String
bool() Boolean
list() List
tuple() Tuple
set() Set

Examples
String → Integer
x = int("10")

Integer → Float
y = float(5)

Integer → String
z = str(25)

Input with Type Conversion (Very Important)


age = int(input("Enter age: "))

✔ Input taken as string


✔ Converted to integer for calculation

Boolean Type Conversion Rules


bool(0) # False
bool(1) # True
bool("") # False
bool("Hi") # True

Converting Collections
list((1,2,3))
tuple([4,5,6])
set([1,1,2,3])

Invalid Type Conversion


int("abc") # Error

9. What is Debugging?

Debugging is the process of finding and fixing errors (bugs) in a program.

📌 Definition:

Debugging means identifying, analyzing, and correcting errors in a program.

Types of Errors in Python

1 Syntax Errors

14 | P a g e
Errors due to wrong syntax.
if x > 5
print(x)

❌ Missing :
👉 Program will not run.

✔ Correct:
if x > 5:
print(x)

2 Runtime Errors

Errors that occur while program is running.


a = 10
b = 0
print(a / b)

❌ ZeroDivisionError

3 Logical Errors

Program runs without error, but gives wrong output.


length = 10
breadth = 5
area = length + breadth # ❌

✔ Correct:
area = length * breadth

Common Debugging Techniques

1 Reading Error Messages

Python gives clear error messages.

Example:
NameError: name 'x' is not defined

👉 Means variable x is not declared.

2 Using print() Statements

Most common beginner method.


print("Value of x:", x)

Helps track program flow.

3 Step-by-Step Checking

 Check input

15 | P a g e
 Check calculations

 Check output

4 Using try–except

Used to handle runtime errors safely.


try:
a = int(input("Enter number: "))
b = int(input("Enter number: "))
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero")

5 Debugging Using IDE Tools

Some editors provide built-in debugger:

 VS Code

 PyCharm

 Jupyter Notebook
10. What is a Conditional Statement?

Definition

A conditional statement is used to make decisions in a program.


It allows the program to execute different blocks of code based on whether a condition is
True or False.

📌 In simple words:

Conditional statements help a program choose what to do next based on a condition.

How a Conditional Statement Works

1. A condition is checked

2. If the condition is True, one block runs

3. If the condition is False, another block runs

Diagram idea:
Start → Condition? → True → Block 1
→ False → Block 2

Types of Conditional Statements in Python

16 | P a g e
1 if Statement

Executes a block only if the condition is True.

Example:

if x > 0:
print("Positive number")

2 if–else Statement

Chooses one of two blocks.

Example:

17 | P a g e
if x % 2 == 0:
print("Even")
else:
print("Odd")

3 if–elif–else Statement

Used when there are multiple conditions.

Example :
if marks >= 90:
print("A grade")
elif marks >= 60:
print("B grade")
else:
print("C grade")

4 Nested if

if inside another if.

Example:
if x > 0:
if x % 2 == 0:
print("Positive Even")

[Link] is a Loop?

A loop is used to repeat a block of code multiple times until a condition is satisfied.

📌 Simple definition:

Loops allow repeated execution of statements.

18 | P a g e
Types of Loops in Python

1 for Loop

Used when the number of repetitions is known.

Diagram idea

Start → Initialize → Condition?


→ Yes → Loop Body → Next value → Condition
→ No → End

Example
for i in range(1, 6):
print(i)

➡️Prints numbers from 1 to 5.

2 while Loop

Used when repetition depends on a condition.

Diagram idea

Start → Condition?
→ True → Loop Body → Update → Condition
→ False → End

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

Loop Control Statements

🔸 break

➡️Stops the loop immediately.


for i in range(5):
if i == 3:
break

🔸 continue

➡️Skips current iteration.


for i in range(5):
if i == 2:
continue
print(i)

19 | P a g e
🔸 pass

➡️Does nothing (placeholder).


for i in range(3):
pass

12. What is Indentation?

Indentation means giving space (usually 4 spaces) at the beginning of a line.


In Python, indentation is used to define blocks of code.

📌 Definition:

Indentation tells Python which statements belong to the same block.

Why Indentation is Important in Python

 Python does not use { } brackets

 It uses indentation to show structure

 Wrong indentation → Error

Indentation in Conditional Statements

Correct Indentation ✅
if x > 0:
print("Positive")
print("Number")

Diagram idea:

↳ indented statements (block)


if condition

Wrong Indentation ❌
if x > 0:
print("Positive")

❌ Causes:
IndentationError

Indentation in Loops
for i in range(3):
print(i)

Diagram idea:

↳ repeated indented block


Loop

20 | P a g e
Indentation Levels

Each new block needs one extra indentation level.


if x > 0:
if x % 2 == 0:
print("Positive Even")

What are Nested Loops?

A nested loop means one loop inside another loop.

📌 Simple definition:

A loop inside another loop is called a nested loop.

How Nested Loops Work

 Outer loop runs first

 For each iteration of the outer loop, the inner loop runs completely

Flow (in words):


Outer loop → Inner loop → Inner finishes → Outer continues

Example: Nested for Loop


for i in range(1, 4):
for j in range(1, 3):
print(i, j)

Execution idea:

 i = 1 → j = 1, 2

 i = 2 → j = 1, 2

 i = 3 → j = 1, 2

Nested while Loop Example


i = 1
while i <= 2:
j = 1
while j <= 3:
print(i, j)
j += 1
i += 1

Where Nested Loops Are Used

 ⭐ Pattern printing

21 | P a g e
 ⭐ Tables

 ⭐ Matrix operations

 ⭐ Comparing elements

13. What is a String?

A string is a sequence of characters enclosed in single quotes (' ') or double quotes
(\" \").
Strings are used to store textual data such as names, messages, and sentences.

📌 Important point:

Strings in Python are immutable, i.e., once created, they cannot be changed.

1 STRING OPERATIONS — Theory

➤ Concatenation (+)

Concatenation means joining two or more strings to form a single string.

Theory:
When + is used between strings, Python joins them in the same order.
"Bio" + "logy" → "Biology"

➤ Repetition (*)

Repetition means repeating a string multiple times.


The * operator repeats the given string specified number of times.
"Hi" * 3 → "HiHiHi"

➤ Membership (in, not in)

Membership operators check whether a character or substring exists in a string.

Theory:

 in → returns True if present

 not in → returns True if absent

➤ Length (len())

Theory:
len() returns the total number of characters in a string (including spaces).

22 | P a g e
2 TRAVERSING A STRING — Theory

What is Traversing?

Traversing a string means accessing each character of the string one by one.

📌 This is useful for:

 Counting characters

 Searching characters

 Processing text

➤ Indexing

Each character in a string has a position number (index).

Theory:

 Indexing starts from 0 (left to right)

 Negative indexing starts from -1 (right to left)

Index Diagram:
P y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1

➤ Traversing Using Loop

Theory:
Using a loop, Python accesses each character sequentially from the string.

This method is commonly used in string processing programs.

3 STRING SLICING — Theory

What is Slicing?

Slicing means extracting a part of a string.

Syntax:
string[start : end]

Theory:

 start → included

23 | P a g e
 end → excluded

Diagram:
Python
↑----↑
1 4
Result → yth

4 STRING HANDLING FUNCTIONS — Theory

Python provides built-in functions to manipulate strings easily.


Function Theory
upper() Converts string to uppercase
lower() Converts string to lowercase
capitalize() Capitalizes first character
title() Capitalizes first letter of each word
strip() Removes leading & trailing spaces
replace() Replaces part of string
find() Finds position of substring
count() Counts occurrences
split() Breaks string into list
join() Joins list into string

📌 Important:

These functions do not modify the original string — they return a new string.

String Operations

➕ Concatenation

Joining strings using +


a = "Py"
b = "thon"
print(a + b)

Diagram idea:
"Py" + "thon" → "Python"

✖️Repetition

Repeating a string using *


print("Hi " * 3)

Diagram idea:
"Hi" → Hi Hi Hi

🔍 Membership

24 | P a g e
Check presence using in / not in
print("y" in "Python") # True

📏 Length
len("Python") # 6

2 Traversing a String

Traversing means accessing characters one by one.

➤ Using Indexing
word = "Python"
print(word[0]) # P
print(word[-1]) # n

Diagram (index positions):


P y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1

➤ Using Loop
for ch in "Python":
print(ch)

Diagram idea:
P→y→t→h→o→n

3 String Slicing

Extract part of a string.


word = "Python"
print(word[1:4])

Output: yth

Diagram idea:
Python
↑---↑
1 4

4 String Handling Functions (Very Important)


Function Use Example
upper() Convert to uppercase "py".upper()
lower() Convert to lowercase "PY".lower()
capitalize() First letter capital "python".capitalize()
title() First letter of each word "hello world".title()
strip() Remove spaces " hi ".strip()
replace() Replace text "hi".replace("i","ello")
find() Find position "Python".find("t")
count() Count occurrence "banana".count("a")

25 | P a g e
Function Use Example
split() Split string "a,b".split(",")
join() Join strings " ".join(["Hi","All"])

Example
text = " python "
print([Link]().upper())

Output: PYTHON

26 | P a g e

You might also like