0% found this document useful (0 votes)
11 views10 pages

Python Theory

Uploaded by

arjun
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
11 views10 pages

Python Theory

Uploaded by

arjun
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 10

Unit I: Python Fundamentals

1. Introduction to Python Programming Language


 What is Python?
o Python is a high-level, general-purpose programming language
known for its simplicity and readability. It supports multiple
programming paradigms including procedural, object-oriented, and
functional programming.
 Introduction to Program and Debugging
o Programs are sequences of instructions that a computer follows to
perform a task.
o Debugging is the process of finding and fixing errors or bugs in a
program.
 Formal and Natural Languages
o Formal languages (like Python) have strict syntax and semantics
used for programming.
o Natural languages (like English) are more flexible but less precise.

2. Variables, Expressions, and Statements


 Values and Types
o Python supports different data types like integers, floats, strings,
and booleans.
 Variables
o A variable is a named reference to a value stored in memory.

 Variable Names and Keywords


o Variable names follow certain rules (e.g., they can’t start with a
number) and some names are reserved as keywords (like for, while,
if).
 Statements
o A statement performs an action (e.g., assignment statements like x
= 5).
 Operators and Operands
o Python provides operators like +, -, *, / for arithmetic and and, or for
logical operations.
 Order of Operations
o Python follows PEMDAS (Parentheses, Exponents,
Multiplication/Division, Addition/Subtraction) for evaluating
expressions.
 Operations on Strings
o Python allows concatenation (+) and repetition (*) of strings.

 Composition and Comments


o You can compose multiple statements into a more complex
operation, and add comments for documentation using #.

3. Conditionals and Iteration


 Modulus Operator
o The modulus operator (%) returns the remainder of a division.

 Boolean Expressions
o Boolean expressions return True or False.

 Logical Operators
o Logical operators include and, or, and not.

 Conditional Operators
o Conditional operators like ==, !=, >, <, are used for comparison.

 Alternative Execution and Nested Conditionals


o if-else and elif statements allow for multiple branches of execution.

 Return Statements
o return is used in functions to return a value.

 Loops
o While Loops: Repeat as long as a condition is true.

o For Loops: Iterate over a sequence (like a list or string).

4. Functions and Recursion


 Function Calls
o Functions allow code reuse by encapsulating logic that can be called
multiple times.
 Type Conversion and Coercion
o Functions like int(), float(), and str() convert data types.

 Math Functions
o Python provides built-in math functions like abs(), pow(), and the
math module for more complex operations.
 Adding New Functions
o Define a function using def with a name, parameters, and a body.

 Parameters and Arguments


o Parameters are the inputs defined by a function, and arguments are
the values passed during a function call.
 Recursion
o A function that calls itself is recursive. Recursion is useful for
problems like calculating the factorial of a number or traversing
trees.

Unit II: Advanced Data Types


1. Strings
 String: A Compound Data Type
o A string is a sequence of characters.

 String Length
o The len() function returns the number of characters in a string.

 String Traversal
o You can loop through the characters of a string using a for loop.

 String Slices
o Slicing allows access to a substring using s[start:end].

 Comparison
o Strings can be compared using relational operators.

 Find Function
o The find() method searches for a substring and returns the index of
its first occurrence.
 Looping and Counting
o You can loop through a string and count occurrences of a character
using a loop.

2. Lists
 List Values
o Lists are ordered collections of values (like [1, 2, 3]).
 Length
o The len() function returns the number of elements in a list.

 Membership
o You can check if an item is in a list using in.

 Operations
o Lists support concatenation (+) and repetition (*).

 Slices
o You can access parts of a list using slicing (e.g., list[start:end]).

 Deletion
o Elements can be deleted using del or remove().

 Accessing Elements
o Elements are accessed by their index (e.g., list[0]).

 List and For Loops


o You can iterate through a list with a for loop.

 List Parameters and Nested Lists


o Lists can be passed as parameters to functions and can contain
other lists (nested lists).

3. Tuples and Dictionaries


 Mutability and Tuples
o Tuples are immutable, meaning their values cannot be changed
after creation.
 Tuple Assignment
o You can assign multiple values to variables using tuples (e.g., x, y =
1, 2).
 Tuple as Return Values
o Functions can return multiple values using tuples.

 Random Numbers and Lists of Random Numbers


o The random module allows generation of random numbers, which
can be stored in lists.
 Counting and Many Buckets
o You can count occurrences of items in a list or other data structures.

 Dictionaries: Operations and Methods


o Dictionaries store key-value pairs and support operations like
adding, accessing, and deleting key-value pairs.
 Sparse Matrices
o Sparse matrices are represented using dictionaries to store non-zero
elements efficiently.
 Aliasing and Copying
o Copying data types like lists or dictionaries can result in aliasing,
where multiple variables refer to the same object in memory.

If you are working on a specific project or have particular areas where you'd like
more focus, let me know!
4o
You said:
example python code for each
ChatGPT said:
ChatGPT
Here are Python code examples for each of the topics you mentioned:

Unit I: Python Fundamentals


1. Introduction to Program and Debugging
python
Copy code
# Simple program: Add two numbers
a=5
b=3
print(a + b) # Output: 8

# Debugging example: fixing division by zero error


try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
2. Variables, Expressions, and Statements
python
Copy code
# Variables and types
x = 10 # Integer
y = 3.5 # Float
name = "Alice" # String

# Expressions and statements


z=x+y
print("Sum:", z)

# Operations on strings
greeting = "Hello"
name = "World"
print(greeting + " " + name) # Concatenation

# Comments
# This is a comment and it won't be executed by Python
3. Conditionals and Iteration
python
Copy code
# Conditional statements
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")

# While loop
count = 0
while count < 5:
print("Count:", count)
count += 1

# For loop
for i in range(5):
print("For loop iteration:", i)
4. Functions and Recursion
python
Copy code
# Function definition and call
def add_numbers(a, b):
return a + b

result = add_numbers(2, 3)
print("Sum:", result)

# Recursion example: factorial function


def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)

print("Factorial of 5:", factorial(5)) # Output: 120

Unit II: Advanced Data Types


1. Strings
python
Copy code
# String traversal and slicing
word = "Python"
for letter in word:
print(letter)
# String slice
print(word[0:2]) # Output: Py

# String comparison
print("apple" > "banana") # False, because 'a' comes before 'b'

# Find function
sentence = "Hello, welcome to Python!"
index = sentence.find("Python")
print("Index of 'Python':", index) # Output: 18
2. Lists
python
Copy code
# List values and operations
numbers = [1, 2, 3, 4, 5]
print(numbers[0]) # Output: 1

# List membership
print(3 in numbers) # True

# List slicing
print(numbers[1:3]) # Output: [2, 3]

# Deleting element
del numbers[2] # Deletes the element at index 2
print(numbers) # Output: [1, 2, 4, 5]

# List and for loop


for num in numbers:
print(num)
# Nested list
nested_list = [[1, 2], [3, 4]]
print(nested_list[0][1]) # Output: 2
3. Tuples and Dictionaries
python
Copy code
# Tuple example
tuple_example = (10, 20, 30)
print(tuple_example[1]) # Output: 20

# Tuple assignment
x, y = (5, 10)
print(x, y) # Output: 5 10

# Dictionary operations
student_grades = {"Alice": 90, "Bob": 85}
print(student_grades["Alice"]) # Output: 90

# Adding a new key-value pair


student_grades["Charlie"] = 95
print(student_grades)

# Random numbers
import random
random_number = random.randint(1, 100)
print(random_number)

# Counting using dictionary


fruit_counts = {}
fruits = ["apple", "banana", "apple", "orange"]
for fruit in fruits:
if fruit in fruit_counts:
fruit_counts[fruit] += 1
else:
fruit_counts[fruit] = 1
print(fruit_counts) # Output: {'apple': 2, 'banana': 1, 'orange': 1}

# Sparse matrix representation


sparse_matrix = {(0, 1): 5, (2, 3): 10}
print(sparse_matrix.get((0, 1), 0)) # Output: 5
print(sparse_matrix.get((1, 2), 0)) # Output: 0

You might also like