0% found this document useful (0 votes)
16 views21 pages

Python Programming Fundamentals Guide

This document provides an overview of Python programming, covering its introduction, input-processing-output (IPO) model, comments, variables, operators, type conversion, conditional statements, looping statements, lists, tuples, and string operations. It emphasizes Python's simplicity and versatility across various applications, along with examples for each concept. The document serves as a comprehensive guide for beginners to understand fundamental Python programming concepts.
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)
16 views21 pages

Python Programming Fundamentals Guide

This document provides an overview of Python programming, covering its introduction, input-processing-output (IPO) model, comments, variables, operators, type conversion, conditional statements, looping statements, lists, tuples, and string operations. It emphasizes Python's simplicity and versatility across various applications, along with examples for each concept. The document serves as a comprehensive guide for beginners to understand fundamental Python programming concepts.
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

B.

Sc (Physical Science & Life Science)


Sec-III (Fundamentals of Python)
1. Introduction about Python Programming:
Python is a high-level, interpreted, and general-purpose programming language that is widely used for
developing a variety of applications. It was created by Guido van Rossum and first released in 1991. Python
is known for its simple syntax, readability, and ease of learning, which makes it an ideal choice for
beginners as well as experienced programmers.
Python is widely used in various fields including web development, data science, artificial
intelligence, machine learning, automation, scientific computing, and cyber security. Popular
frameworks and libraries such as Django, Flask, NumPy, Pandas, and TensorFlow enhance its functionality.
Example:
print("Hello, World!")
output: Hello, World!
2. Input, Processing, and Output (IPO) in Python
The IPO cycle is the basic structure of any program. It describes how a program works by taking Input,
performing Processing, and producing Output.
Input in Python
Input is the data entered into the program by the user.
Python uses the input() function to accept input.
Example:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
 input() reads data as a string
 int() converts input into integer
2. Processing in Python
Processing is the step where calculations, decisions, or logical operations are performed on the input data.
Example:
sum = a + b
average = sum / 2
 Arithmetic operations
 Logical and conditional operations
 Data manipulation
[Link] in Python

 Output is the result produced by the program after processing.


Python uses the print() function to display output.
 Example:
 print("Sum =", sum)
 print("Average =", average)

Example for Input, Processing and Output:


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

# Processing
sum = a + b
average = sum / 2

# Output
print("Sum =", sum)
print("Average =", average)
3. Explain Comments in Python?
Comments: Comments in Python are statements that are not executed by the interpreter. They are used
to explain the code, make programs easy to understand, and improve readability.
Purpose of Comments
 Explain the logic of the program
 Make code readable and maintainable
 Help others understand the program
 Useful for debugging and documentation
ii. Single-Line Comments

 Single-line comments begin with the # symbol.


 Example:
 # This program adds two numbers
 a = 10
 b = 20
 print(a + b) # Display the sum
iii. Multi-Line Comments
 Python does not have a separate syntax for multi-line comments, but triple quotes are commonly
used.
 Example:
 """
 This program demonstrates
 multi-line comments in Python
 """
 print("Hello, Python")

Comments in Python help explain program logic, improve clarity, and make code easy to maintain. They
are essential for writing good and understandable programs.

4. Explain Variables in Python?


Variables : A variable in Python is a name used to store data in a program. The value of a variable can
change during program execution. Python variables make programs flexible and easy to read.
Creating Variables
In Python, variables are created automatically when a value is assigned.
No need to declare the data type.
Example:
x = 10
name = "Python"
price = 99.5
Rules for Naming Variables
 Must start with a letter (a–z / A–Z) or underscore (_)
 Cannot start with a number
 Can contain letters, numbers, and underscores
 No spaces allowed
 Cannot use Python keywords

Valid:
total
student_ name
_marks
Invalid:
1total
student-name
class
Types of Variables :
a) Local Variables
Declared inside a function and used only within it.
def show():
x = 10 # local variable
print(x)

b) Global Variables
Declared outside a function and accessible throughout the program.
x = 20 # global variable

def show():
print(x)

5. Explain Operators in Python?


Operators: Operators are symbols used to perform operations on variables and values. Python supports
different types of operators to carry out calculations, comparisons, and logical operations.
 Operators: Special symbols like -, + , * , /, etc.
 Operands: Value on which the operator is applied.
Types of Operators in Python

Arithmetic Operators
Python Arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication and division.
Python Code:

# Variables
a = 15
b=4
# Addition
print("Addition:", a + b)

# Subtraction
print("Subtraction:", a - b)

# Multiplication
print("Multiplication:", a * b)

# Division
print("Division:", a / b)

# Floor Division
print("Floor Division:", a // b)

# Modulus
print("Modulus:", a % b)

# Exponentiation
print("Exponentiation:", a ** b)

Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625
Comparison Operators:
In Python, Comparison (or Relational) operators compares values. It either returns True
or False according to the condition.
Example:
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Output
False
True
False
True
False
True
Logical Operators
Python Logical operators perform Logical AND, Logical OR and Logical
NOT operations. It is used to combine conditional statements.
Example:
a = True
b = False
print(a and b)
print(a or b)
print(not a)
Output
False
True
False

Bitwise Operators
Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to
operate on binary numbers.
Bitwise Operators in Python are as follows:
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
Example:
a = 10
b=4

print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)
Output
0
14
-11
14
2
40
Assignment Operators
Python Assignment operators are used to assign values to the variables. This operator is
used to assign the value of the right side of the expression to the left side operand.
Example
a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
Output
10
20
10
100
102400

Explain Type Conversion in Python?


Type conversion in Python refers to changing one data type into another. It is useful
when we want to perform operations on different types of data.
There are two types of type conversion in Python:
1. Implicit Type Conversion
2. Explicit Type Conversion

Implicit Type Conversion


In implicit type conversion, Python automatically converts one data type into another without user
intervention.
Example:
a = 10 # int
b = 2.5 # float
c=a+b # int converted to float
print(c)
print(type(c))
Output:
12.5
<class 'float'>
Python converts int to float to avoid data loss.
2. Explicit Type Conversion (Type Casting)
In explicit type conversion, the programmer manually converts a data type using built-in functions.
Common Type Casting Functions:
Function Description Example
int() Converts to integer int("10")
float() Converts to float float(5)
str() Converts to string str(100)
Function Description Example
bool() Converts to boolean bool(1)
Examples:
a) String to Integer
x = "10"
y = int(x)
print(y)
b) Integer to Float
a=5
b = float(a)
print(b)
c) Number to String
num = 25
text = str(num)
print(text)

Explain Conditional Statements in Python?


Conditional statements in Python are used to make decisions based on conditions. They allow a program to
execute different blocks of code depending on whether a condition is True or False.
1. if Statement
The if statement executes a block of code when the condition is true.
Syntax:
if condition:
statement(s)
Example:
age = 18
if age >= 18:
print("Eligible to vote")

2. if–else Statement
Executes one block if the condition is true and another block if it is false.
Syntax:
if condition:
statement(s)
else:
statement(s)
Example:
marks = 30
if marks >= 35:
print("Pass")
else:
print("Fail")

3. if–elif–else Statement
Used to check multiple conditions.
Syntax:
if condition1:
statement(s)
elif condition2:
statement(s)
else:
statement(s)
Example:
marks = 85
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")

4. Nested if Statement
An if statement inside another if statement.
Example:
num = 10
if num > 0:
if num % 2 == 0:
print("Positive Even Number")
Example:
num = int(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive")
else:
print("Negative")
Explain Looping statements in Python?
Looping statements in Python are used to execute a block of code repeatedly as long as a specified
condition is satisfied. They help reduce code repetition and make programs efficient.
In Python Looping statements are 3types:
1. for Loop
2. While Loop
i. for Loop
The for loop is used to iterate over a sequence such as a list, string, or range.
Syntax:
for variable in sequence:
statement(s)
Example:
for i in range(1, 6):
print(i)
2. while Loop
The while loop executes a block of code as long as the condition is True.
Syntax:
while condition:
statement(s)
Example: Output:
i=1 1
while i <= 5: 2
print(i) 3
i=i+1 4
Loop Control Statements
break
Stops the loop immediately.
for i in range(1, 10):
if i == 5:
break
print(i)
continue
Skips the current iteration.
for i in range(1, 6):
if i == 3:
continue
print(i)
pass
Does nothing; used as a placeholder.
for i in range(5):
pass
Nested Loops
A loop inside another loop.
Example:
for i in range(1, 4):
for j in range(1, 4):
print(i, j)

Explain Lists in Python?


List: A list in Python is a built-in data structure used to store multiple values in a single variable. Lists are
ordered, mutable (changeable), and can store different data types.
Creating a List
Lists are created using square brackets [ ].
numbers = [10, 20, 30, 40]
names = ["Divya", "Ravi", "Anu"]
mixed = [1, "Python", 3.5, True]
Accessing List Elements
List elements are accessed using index values (starting from 0).
numbers = [10, 20, 30]
print(numbers[0]) # 10 Output: 10
print(numbers[2]) # 30 30
Negative indexing:
print(numbers[-1]) # Last element Output: 30
Slicing a List
Slicing extracts a part of the list.
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # [20, 30, 40]
Modifying List Elements
Lists are mutable, so values can be changed.
numbers = [10, 20, 30]
numbers[1] = 25
print(numbers)
List Operations
Adding Elements
[Link](40) # Add at end
[Link](1, 15) # Add at index
[Link]([50, 60]) # Add multiple items
Removing Elements
[Link](20) # Remove specific element
[Link]() # Remove last element
del numbers[1] # Remove by index
List Methods
Method Description
append() Add element
insert() Insert at position
remove() Remove element
pop() Remove last
sort() Sort list
reverse() Reverse list
count() Count occurrence
index() Find index
Looping Through a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
List Length
print(len(fruits))
List Example Program
marks = [85, 90, 78, 88]
total = sum(marks)
print("Total Marks:", total)
print("Average:", total / len(marks))
Advantages of Lists
 Stores multiple values
 Dynamic size
 Easy to modify
 Supports many built-in functions
Explain Tuples in Python?
Tuple: A tuple in Python is a built-in data structure used to store multiple values in a single variable.
Tuples are ordered and immutable (cannot be changed) after creation.
Creating a Tuple
Tuples are created using parentheses ( ).
numbers = (10, 20, 30)
names = ("Divya", "Ravi", "Anu")
mixed = (1, "Python", 3.5, True)
Single-element tuple:
t = (5,) # comma is mandatory
Accessing Tuple Elements
Tuple elements are accessed using index values.
numbers = (10, 20, 30)
print(numbers[0])
print(numbers[-1])
Slicing a Tuple
Slicing works the same as in lists.
numbers = (10, 20, 30, 40, 50)
print(numbers[1:4])
Immutability of Tuples
Tuple values cannot be changed, added, or removed.
❌ Invalid:
numbers[1] = 25 # Error
✔ However, a tuple can contain mutable objects like lists.
Tuple Operations
Concatenation
t1 = (1, 2)
t2 = (3, 4)
t3 = t1 + t2
print(t3)
Repetition
t = (1, 2)
print(t * 3)
Membership
print(10 in numbers)
Tuple Methods
Tuples have limited methods:
Method Description
count() Count occurrences
index() Find index
Looping Through a Tuple
for i in numbers:
print(i)

What is String? Explain String Operations in Python?


A string in Python is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or triple
quotes (''' ''' / """ """).
Strings are used to store and manipulate text data such as names, messages, and sentences.
Examples
name = "Python"
college = 'ABC College'
message = """Welcome to Python Programming"""
Key Features of Strings
 Strings are immutable (cannot be changed after creation).
 Each character in a string has an index (starts from 0).
 Supports slicing, indexing, and many built-in functions.
String Operations in Python
1. String Indexing
Accessing individual characters using index values.
s = "Python"
print(s[0]) # P
print(s[3]) # h
2. String Slicing
Extracting a part of a string.
s = "Python"
print(s[0:4]) # Pyth
print(s[:3]) # Pyt
print(s[2:]) # thon
3. String Concatenation
Joining two or more strings using +.
a = "Hello"
b = "World"
print(a + " " + b) # Hello World
4. String Repetition
Repeating a string using *.
s = "Hi "
print(s * 3) # Hi Hi Hi
5. String Length
Finding the length of a string using len().
s = "Python"
print(len(s)) # 6
6. Membership Operators
Checking whether a character or substring exists.
s = "Python"
print('P' in s) # True
print('Java' in s) # False
7. String Comparison
Comparing strings using relational operators.
a = "Apple"
b = "Banana"
print(a == b) # False
print(a < b) # True
Common String Methods
1. lower() and upper()
s = "Python"
print([Link]()) # python
print([Link]()) # PYTHON
2. strip()
Removes spaces from beginning and end.
s = " Python "
print([Link]()) # Python
3. replace()
Replaces a substring.
s = "I like Java"
print([Link]("Java", "Python"))
4. find()
Finds the position of a substring.
s = "Python"
print([Link]("t")) # 2
split()
Splits a string into a list.
s = "Python is easy"
print([Link]())
join()
Joins elements of a list into a string.
words = ['Python', 'is', 'fun']
print(" ".join(words))
startswith() and endswith()
s = "Python"
print([Link]("Py")) # True
print([Link]("on")) # True
Explain about Dictionaries in Python?
Dictionaries: A dictionary in Python is a collection of key–value pairs, where each key is unique and is used
to access its corresponding value. Dictionaries are unordered, mutable, and indexed by keys instead of
numbers.
Syntax
dictionary_name = {key1: value1, key2: value2, key3: value3}
Example
student = {
"name": "Divya",
"age": 20,
"course": "BCA"
}
Characteristics of Dictionaries
 Keys must be unique and immutable (e.g., string, number, tuple)
 Values can be any data type
 Dictionaries are mutable (can be modified)
 Written using curly braces {}
Accessing Dictionary Elements
print(student["name"]) # Divya
print([Link]("age")) # 20
get() is safer because it does not give an error if the key is missing.
Adding and Updating Elements
student["college"] = "ABC College" # Add
student["age"] = 21 # Update
Removing Elements
[Link]("age") # Remove specific key
del student["course"] # Delete item
[Link]() # Remove all items
Dictionary Operations:
1. Length of Dictionary
print(len(student))
2. Membership Test
print("name" in student) # True
print("marks" in student) # False
3. Looping Through Dictionary
for key in student:
print(key, student[key])
for key, value in [Link]():
print(key, value)
Common Dictionary Methods
Method Description
keys() Returns all keys
values() Returns all values
items() Returns key-value pairs
update() Updates dictionary with another
pop() Removes specified key
clear() Removes all items
Example
student = {"name": "Divya", "age": 20}
print([Link]())
print([Link]())
print([Link]())
Nested Dictionaries
A dictionary inside another dictionary.
students = {
1: {"name": "Divya", "marks": 85},
2: {"name": "Anu", "marks": 90}
}
Difference Between List and Dictionary
List Dictionary
Uses index Uses keys
Ordered Unordered
Stores values only Stores key-value pairs
Example Program
student = {"name": "Divya", "age": 20, "course": "BCA"}
for key, value in [Link]():
print(key, ":", value)
What is Set? Explain Set Operations in Python?
Set: Python set is an unordered collection of multiple items having different datatypes. In Python, sets are
mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can
change.
 Can store None values.
 Implemented using hash tables internally.
 Do not implement interfaces like Serializable or Cloneable.
 Python sets are not inherently thread-safe; synchronization is needed if used across threads.
Creating a Set in Python
In Python, the most basic and efficient method for creating a set is using curly braces.
set1 = {1, 2, 3, 4}
print(set1)
Output:
{1, 2, 3, 4}
Set Operations in Python
1. Add Elements
s = {1, 2, 3}
[Link](4)
print(s)
2. Update Elements
[Link]([5, 6, 7])
print(s)
3. Remove Elements
[Link](3) # Error if element not present
[Link](10) # No error if element not present
[Link]() # Removes a random element
Mathematical Set Operations
1. Union (|)
Returns all unique elements from both sets.
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B)
2. Intersection (&)
Returns common elements.
print(A & B)
3. Difference (-)
Returns elements present in one set but not the other.
print(A - B)
4. Symmetric Difference (^)
Returns elements not common to both sets.
print(A ^ B)
Set Methods
Method Description
union() Returns union of sets
intersection() Returns common elements
difference() Returns difference
symmetric_difference() Returns uncommon elements
clear() Removes all elements
copy() Returns copy of set
Membership Test
s = {1, 2, 3}
print(2 in s) # True
print(5 in s) # False
Subset and Superset
A = {1, 2}
B = {1, 2, 3}
print([Link](B)) # True
print([Link](A)) # True
Explain about Function in detail?
A function in Python is a reusable block of code that performs a specific task. Functions help in breaking a
large program into smaller, manageable parts, making the code easy to understand, reuse, and maintain.
 Reduce code duplication
 Improve program readability
 Make debugging easier
 Promote modular programming.
Types of Functions in Python
1. Built-in Functions
These are functions already provided by Python.
Examples:
print(), input(), len(), sum(), type()
print("Hello Python")
2. User-defined Functions
Functions created by the programmer.
Syntax:
def function_name(parameters):
statement(s)
return value
Example:
def add(a, b):
return a + b

result = add(10, 20)


print(result)
3. Parts of a Function
 def – keyword to define a function
 function_name – name of the function
 parameters – values passed to the function
 return – sends result back to the caller

Recursion
 A function calling itself is called recursion.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)

print(factorial(5))

Advantages of Functions
 Code reusability
 Easy testing and debugging
 Improves program structure
 Saves development time.

What is File? Explain about File handling in Python?


File : A file in Python is an object used to read data from or write data to a storage device using file-
handling operations.
File Handling : File handling allows a program to store data permanently in files and retrieve it
whenever required.
Types of Files
1. Text files – store data as text
Example: .txt, .csv
2. Binary files – store data in binary format
Example: .jpg, .pdf
File Operations
Python provides the open() function to work with files.
Syntax:
file_object = open("filename", "mode")
File Modes
Mode Description
r Read (default)
w Write (overwrites file)
a Append
r+ Read and write
w+ Write and read
a+ Append and read
b Binary mode
t Text mode
Writing to a File
f = open("[Link]", "w")
[Link]("Welcome to Python")
[Link]()
Reading from a File
f = open("[Link]", "r")
print([Link]())
[Link]()
Other reading methods:
 read() – reads entire file
 readline() – reads one line
 readlines() – reads all lines into a list
File Functions
 close() – closes file
 tell() – returns file pointer position
 seek() – changes file pointer position
 flush() – clears buffer

****The End****

You might also like