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

Python Programming Guide and Basics

This document provides comprehensive notes on Python programming, covering its introduction, key features, installation, basic syntax, data types, control flow, functions, OOP, exception handling, file handling, and common programming problems. It includes practical examples and explanations for various concepts such as operators, loops, lists, dictionaries, and modules. The notes serve as a guide for beginners to learn and understand Python programming effectively.

Uploaded by

naikatharva111
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)
16 views19 pages

Python Programming Guide and Basics

This document provides comprehensive notes on Python programming, covering its introduction, key features, installation, basic syntax, data types, control flow, functions, OOP, exception handling, file handling, and common programming problems. It includes practical examples and explanations for various concepts such as operators, loops, lists, dictionaries, and modules. The notes serve as a guide for beginners to learn and understand Python programming effectively.

Uploaded by

naikatharva111
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 Programming Notes

1. Introduction to Python
What is Python?
Python is a high-level, interpreted, general-purpose programming language created by
Guido van Rossum in 1991. It emphasizes code readability with the use of significant
indentation. Python is widely used in web development, data science, machine learning,
automation, and scientific computing.

Key Features of Python


Easy to Learn - Simple syntax similar to English language
Interpreted Language - Code executed line by line by interpreter
Dynamically Typed - No need to declare data types explicitly
Object-Oriented - Supports classes and objects
Rich Standard Library - Extensive built-in modules and functions
Platform-Independent - Runs on Windows, Mac, Linux
Extensive Frameworks - Django, Flask, NumPy, Pandas, TensorFlow
Community Support - Large, active community with resources

Why Learn Python?


Most popular language for machine learning and AI
Data science and analytics
Web development with Django and Flask
Automation and scripting
Scientific computing
Game development
Cybersecurity and ethical hacking

2. Setting Up Python Environment


Installation
1. Download Python from: [Link]
2. Run installer and check "Add Python to PATH"
3. Verify installation: python --version

IDEs and Editors


PyCharm - Full-featured IDE
VS Code - Lightweight with extensions
Jupyter Notebook - Interactive coding
Thonny - Beginner-friendly
IDLE - Built-in Python IDE
Your First Python Program
print("Hello, Python!")
Run the program:
python [Link]

3. Basic Syntax and Data Types


Variables and Assignment

Variables (no type declaration needed)


name = "Alice"
age = 25
height = 5.6
is_student = True

Multiple assignment
x, y, z = 1, 2, 3

Dynamic typing
var = 10 # Integer
var = "hello" # String (type changed)

Data Types

Integer
age = 25
count = -10

Float
price = 99.99
pi = 3.14159

String
name = "John"
message = 'Hello, World!'
multi_line = """This is a
multi-line string"""
Boolean
is_valid = True
is_empty = False

None
result = None

Type Conversion

Convert to different types


x = "10"
y = int(x) # Convert to integer
z = float(x) # Convert to float
s = str(25) # Convert to string
b = bool(1) # Convert to boolean

print(type(y)) # <class 'int'>


print(type(s)) # <class 'str'>

4. Operators
Arithmetic Operators
a = 10
b=3
print(a + b) # 13 (Addition)
print(a - b) # 7 (Subtraction)
print(a * b) # 30 (Multiplication)
print(a / b) # 3.333... (Division)
print(a // b) # 3 (Floor Division)
print(a % b) # 1 (Modulus)
print(a ** b) # 1000 (Exponentiation)

Comparison Operators
x = 10
y =5
print(x == y) # False (Equal)
print(x != y) # True (Not equal)
print(x > y) # True (Greater than)
print(x < y) # False (Less than)
print(x >= y) # True (Greater or equal)
print(x <= y) # False (Less or equal)
Logical Operators
a = True
b = False
print(a and b) # False (AND)
print(a or b) # True (OR)
print(not a) # False (NOT)

Assignment Operators
x = 10
x += 5 # x = 15 (Addition assignment)
x -= 3 # x = 12
x *= 2 # x = 24
x /= 4 # x = 6.0
x //= 2 # x = 3.0
x %= 3 # x = 0.0

5. Control Flow Statements


If-Else Statement
age = 18
if age >= 18:
print("You are an adult")
else:
print("You are a minor")

If-Elif-Else
marks = 75

if marks >= 90:


print("Grade: A")
elif marks >= 80:
print("Grade: B")
elif marks >= 70:
print("Grade: C")
else:
print("Grade: F")

Ternary Operator
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
6. Loops
For Loop

Print numbers 1 to 5
for i in range(1, 6):
print(i)

Loop through list


fruits = ["Apple", "Banana", "Orange"]
for fruit in fruits:
print(fruit)

Loop with index


for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")

While Loop
count = 1
while count <= 5:
print(count)
count += 1

Break and Continue

Break - exit loop


for i in range(1, 11):
if i == 5:
break
print(i) # 1 2 3 4

Continue - skip iteration


for i in range(1, 6):
if i == 3:
continue
print(i) # 1 2 4 5
7. Functions
Function Definition

Simple function
def greet():
print("Hello!")
greet() # Call function

Function with parameters


def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8

Function with default parameters


def introduce(name, age=18):
print(f"{name} is {age} years old")
introduce("Alice")
introduce("Bob", 25)

Function with Multiple Return Values


def get_name_and_age():
return "Alice", 25
name, age = get_name_and_age()
print(name, age) # Alice 25

Variable-length Arguments
def sum_numbers(*numbers):
total = 0
for num in numbers:
total += num
return total
print(sum_numbers(1, 2, 3)) # 6
print(sum_numbers(1, 2, 3, 4, 5)) # 15
Keyword arguments
def print_info(**info):
for key, value in [Link]():
print(f"{key}: {value}")

print_info(name="Alice", age=25, city="Mumbai")

Lambda Functions

Anonymous function
square = lambda x: x ** 2
print(square(5)) # 25

Use in map
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]

Use in filter
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even) # [2, 4]

8. Strings
String Creation and Access
text = "Hello, Python!"

Access character
print(text[0]) # H
print(text[-1]) # !

String slicing
print(text[0:5]) # Hello
print(text[7:]) # Python!
print(text[:5]) # Hello
String Methods
text = "hello world"
print([Link]()) # HELLO WORLD
print([Link]()) # Hello world
print([Link]("world")) # 6
print([Link]("world", "python")) # hello python
print([Link]()) # ['hello', 'world']
print([Link]("hello")) # True
print([Link]("world")) # True

String Formatting
name = "Alice"
age = 25

Old style
print("Name: %s, Age: %d" % (name, age))

Format method
print("Name: {}, Age: {}".format(name, age))

f-string (Python 3.6+)


print(f"Name: {name}, Age: {age}")
print(f"Age after 5 years: {age + 5}")

9. Lists
List Creation and Access

Create list
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

Access elements
print(numbers[0]) # 1
print(numbers[-1]) # 5
List slicing
print(numbers[1:4]) # [2, 3, 4]
print(numbers[:3]) # [1, 2, 3]
print(numbers[::2]) # [1, 3, 5] (every 2nd element)

List Methods
numbers = [1, 2, 3]

Add elements
[Link](4) # [1, 2, 3, 4]
[Link]([5, 6]) # [1, 2, 3, 4, 5, 6]
[Link](0, 0) # [0, 1, 2, 3, 4, 5, 6]

Remove elements
[Link](3) # Remove value 3
popped = [Link]() # Remove and return last element
[Link](0) # Remove element at index 0

Other operations
print(len(numbers)) # Length
print(3 in numbers) # Check if element exists
[Link]() # Sort in place
[Link]() # Reverse in place
[Link](2) # Count occurrences
[Link](5) # Find index of element
[Link]() # Remove all elements

List Comprehension

Create lists using comprehension


squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]

With condition
even = [x for x in range(10) if x % 2 == 0]
print(even) # [0, 2, 4, 6, 8]
10. Tuples
Tuple Creation

Immutable sequence
point = (3, 4)
person = ("Alice", 25, "Engineer")

Access elements
print(point[0]) # 3
print(person[1]) # 25

Tuple unpacking
x, y = point
print(x, y) # 3 4

Tuple operations
print(len(point)) # 2
print(5 in point) # False

Tuple vs List

Tuples are immutable


my_tuple = (1, 2, 3)

my_tuple[0] = 10 # Error!
Lists are mutable
my_list = [1, 2, 3]
my_list[0] = 10 # OK

11. Dictionaries
Dictionary Creation and Access

Create dictionary
student = {
"name": "Alice",
"age": 25,
"cgpa": 8.5,
"branch": "CSE"
}

Access values
print(student["name"]) # Alice
print([Link]("age")) # 25
print([Link]("city", "Mumbai")) # Mumbai (default if not found)

Dictionary Methods
student = {"name": "Alice", "age": 25}

Add/modify
student["city"] = "Mumbai" # Add new key
student["age"] = 26 # Modify existing value

Remove
del student["city"] # Delete key
[Link]("age") # Remove and return value

Iterate
for key in student:
print(f"{key}: {student[key]}")
for key, value in [Link]():
print(f"{key}: {value}")

Get keys and values


print([Link]()) # dict_keys(['name', 'age'])
print([Link]()) # dict_values(['Alice', 26])
Other operations
print(len(student)) # 2
print("name" in student) # True
[Link]() # Remove all items

12. Sets
Set Creation and Operations

Create set (unordered, unique elements)


numbers = {1, 2, 3, 3, 4}
print(numbers) # {1, 2, 3, 4}

Add and remove


[Link](5) # {1, 2, 3, 4, 5}
[Link](3) # {1, 2, 4, 5}
[Link](10) # No error if element doesn't exist

Set operations
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1 & set2) # Intersection: {2, 3}
print(set1 | set2) # Union: {1, 2, 3, 4}
print(set1 - set2) # Difference: {1}

13. Object-Oriented Programming (OOP)


Classes and Objects
class Student:
# Class variable
school = "ABC School"

# Constructor
def __init__(self, name, roll_no, cgpa):
# Instance variables
[Link] = name
self.roll_no = roll_no
[Link] = cgpa
# Instance method
def display_info(self):
print(f"Name: {[Link]}")
print(f"Roll No: {self.roll_no}")
print(f"CGPA: {[Link]}")

def get_grade(self):
if [Link] >= 8.0:
return "A"
elif [Link] >= 7.0:
return "B"
else:
return "C"

Create objects
student1 = Student("Alice", 101, 8.5)
student2 = Student("Bob", 102, 7.2)
student1.display_info()
print(f"Grade: {student1.get_grade()}") # Grade: A

Inheritance

Parent class
class Vehicle:
def init(self, brand, year):
[Link] = brand
[Link] = year

def display_info(self):
print(f"Brand: {[Link]}, Year: {[Link]}")

Child class
class Car(Vehicle):
def init(self, brand, year, doors):
super().init(brand, year)
[Link] = doors
def display_info(self):
super().display_info()
print(f"Doors: {[Link]}")

Usage
car = Car("Honda", 2020, 4)
car.display_info()

Polymorphism
class Animal:
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Woof! Woof!"
class Cat(Animal):
def sound(self):
return "Meow! Meow!"

Usage
animals = [Dog(), Cat(), Dog()]
for animal in animals:
print([Link]())

14. Exception Handling


Try-Except
try:
num1 = 10
num2 = 0
result = num1 / num2
print(result)
except ZeroDivisionError:
print("Cannot divide by zero!")
except TypeError:
print("Invalid data type!")
except Exception as e:
print(f"Error: {e}")
finally:
print("Program completed")
Custom Exceptions
class CustomError(Exception):
def init(self, message):
[Link] = message
try:
age = 10
if age < 18:
raise CustomError("Age must be 18 or above")
except CustomError as e:
print(f"Error: {[Link]}")

15. File Handling


Reading from File

Read entire file


with open("[Link]", "r") as file:
content = [Link]()
print(content)

Read line by line


with open("[Link]", "r") as file:
for line in file:
print([Link]())

Read all lines


with open("[Link]", "r") as file:
lines = [Link]()

Writing to File

Write to file
with open("[Link]", "w") as file:
[Link]("Hello, File!\n")
[Link]("Line 2\n")
Append to file
with open("[Link]", "a") as file:
[Link]("Line 3\n")

16. Modules and Packages


Import Modules

Import entire module


import math
print([Link])
print([Link](16))

Import specific function


from math import sqrt, pi
print(sqrt(25)) # 5

Import with alias


import numpy as np
arr = [Link]([1, 2, 3])

Import all
from math import *
print(ceil(3.4))

Common Modules

Random numbers
import random
print([Link](1, 10))
print([Link]([1, 2, 3, 4, 5]))

Date and time


import datetime
today = [Link]()
now = [Link]()
Operating system
import os
print([Link]())
print([Link]())

JSON
import json
data = {"name": "Alice", "age": 25}
json_string = [Link](data)
parsed = [Link](json_string)

17. Common Programming Problems and Solutions


Problem 1: Sum of List Elements
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(f"Sum: {total}") # 15

Or using loop
total = 0
for num in numbers:
total += num
print(f"Sum: {total}")

Problem 2: Find Maximum Element


numbers = [3, 7, 2, 9, 1]
maximum = max(numbers)
print(f"Maximum: {maximum}") # 9

Problem 3: Check if Number is Prime


def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False

for i in range(3, int(n**0.5) + 1, 2):


if n % i == 0:
return False
return True

print(is_prime(17)) # True
print(is_prime(20)) # False

Problem 4: Reverse a String


text = "Hello"

Method 1: Slicing
reversed_text = text[::-1]
print(reversed_text) # olleH

Method 2: Loop
reversed_text = ""
for char in text:
reversed_text = char + reversed_text
print(reversed_text) # olleH

Problem 5: Fibonacci Sequence


def fibonacci(n):
a, b = 0, 1
result = []
for _ in range(n):
[Link](a)
a, b = b, a + b
return result
print(fibonacci(10)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

18. Python Best Practices


1. Use Meaningful Names - Variables and functions with clear names
2. Follow PEP 8 - Python Enhancement Proposal 8 style guide
3. Write Docstrings - Document functions and classes
4. Use Type Hints - Specify expected types (Python 3.5+)
5. DRY Principle - Don't Repeat Yourself
6. Error Handling - Always use try-except appropriately
7. Virtual Environments - Use venv to isolate projects
8. List Comprehensions - More Pythonic than loops
9. Context Managers - Use with statement for file handling
10. Testing - Write unit tests using unittest or pytest
19. Quick Reference
String Methods
upper(), lower(), capitalize(), title(), strip()
split(), join(), replace(), find(), startswith()
endswith(), count(), format()

List Methods
append(), extend(), insert(), remove(), pop()
clear(), sort(), reverse(), copy(), index(), count()

Dictionary Methods
keys(), values(), items(), get(), pop(), update()
clear(), copy(), fromkeys()

Set Methods
add(), remove(), discard(), clear(), union()
intersection(), difference(), issubset(), issuperset()

20. Resources for Further Learning


Official Python Documentation: [Link]
Python Tutorial: [Link]
GeeksforGeeks Python: [Link]
Real Python: [Link]
Practice Platforms: LeetCode, HackerRank, CodeChef, Codewars
Books: "Python Crash Course" by Eric Matthes, "Fluent Python" by Luciano Ramalho
YouTube: Search "Python Complete Course for Beginners"

Conclusion
Python is a powerful, versatile language suitable for beginners and experts alike. Its simple
syntax combined with powerful libraries makes it ideal for web development, data science,
and automation. Keep practicing regularly, explore libraries like NumPy and Pandas for
data science, and Django/Flask for web development.
Key Takeaway: Master the fundamentals (data types, loops, functions, OOP), then explore
domain-specific libraries for your area of interest.

Happy Coding! 🐍📚

Common questions

Powered by AI

Python is a high-level, interpreted, general-purpose language that emphasizes code readability with its significant indentation. It is easy to learn due to a simple syntax similar to the English language and does not require explicit data type declarations, thanks to its dynamic typing. As an object-oriented language, it supports classes and objects, enhancing code modularity and reusability. Python comes with a rich standard library, extensive built-in modules, and numerous frameworks such as Django, Flask, NumPy, Pandas, and TensorFlow, making it versatile for applications in web development, data science, machine learning, and more. Its platform independence and strong community support further bolster its appeal to both beginners and experts .

As an interpreted language, Python executes code line by line, making it advantageous for web development and automation because it allows for quick testing and iteration without the need for compilation. This speeds up the development cycle, enabling developers to test scripts rapidly and make incremental adjustments easily. In web development, this flexibility aids in dynamic scripting tasks such as form validation. For automation, it allows scripts to be modified on-the-fly to adapt to changing conditions or requirements. Furthermore, the direct interaction with the Python interpreter facilitates debugging, as errors can be identified and corrected immediately after they occur, enhancing the development process's overall efficiency .

Python's widespread adoption is significantly fueled by its large, active community and extensive library ecosystem. Community support provides continuous development, bug fixes, and accessible learning resources, making the language beginner-friendly and rich in tutorials, forums, and educational content. Libraries such as TensorFlow, Pandas, and Django enable rapid development in AI, data science, and web development, offering pre-built functionality and tools necessary for complex computations, data analysis, and web framework utilization. This ecosystem reduces developmental overhead, allowing professionals and organizations to focus more on application logic rather than foundational code, thereby speeding up innovation and implementation across various sectors .

Python supports Object-Oriented Programming by allowing the creation of classes and objects, encapsulation of data and behavior, inheritance for creating child classes from parent classes, and polymorphism for method overriding. OOP in Python facilitates code reuse, modularity, and easy maintenance by structuring programs around objects rather than actions, thus aligning code more closely with real-world concepts. For example, creating a class Vehicle and using inheritance to define specific types like Car reduces redundancy and improves code clarity. Methods associated with an object encapsulate functionality, significantly reducing namespace conflicts and making large codebases easier to manage and debug .

Python's list comprehensions provide a concise way to create lists by embedding loops and conditionals in a single line. This contrasts with traditional loops that require multiple lines and temporary storage. List comprehensions enhance readability by reducing the boilerplate code needed for loop constructions and make the code more Pythonic. An example is creating a list of squares using a comprehension: [x**2 for x in range(1,6)] instead of using a for loop and append method. Comprehensions are generally more efficient because they are optimized internally, reducing execution time and memory overhead compared to traditional loop implementations .

Control flow statements in Python, such as if-else, if-elif-else, and ternary operators, are used for decision-making processes. The if-else statement dictates the execution of different blocks of code based on conditions, whereas the if-elif-else provides multiple condition evaluation paths. Ternary operators offer a concise syntax for simple conditions. For iteration, Python offers for and while loops. For loops iterate over sequences like lists, executing block code for each element, while while loops run as long as a condition remains true. These statements are crucial for executing code based on various inputs and conditions, enabling dynamic and responsive programming .

Python uses the try-except block for exception handling, promoting robustness and reliability by allowing programs to continue execution or fail gracefully in unexpected situations. By enclosing potentially error-prone code within a try block and defining responses in subsequent except blocks, programmers can control program flow in the event of exceptions like ZeroDivisionError or FileNotFoundError. This prevents runtime errors from causing entire program crashes, thus ensuring uninterrupted service or an informative error message instead. Further handling with finally ensures resource release, and custom exceptions offer tailored responses to application-specific issues, improving overall application stability and robustness .

Python handles type conversion through explicit conversion functions such as int(), float(), str(), and bool(). This dynamic typing system allows variables to change types as needed. Common use cases for type conversion include converting user input strings to the appropriate numerical types for arithmetic operations, toggling between integer and float for precision management, casting numerical values to strings for concatenation, and converting numbers to boolean for conditional checks. For instance, using int() to parse a string input as an integer for arithmetic computations or float() to handle decimal precision in financial calculations .

Python's built-in methods significantly enhance string and list operations, providing robust tools for effective data manipulation. String methods like upper(), lower(), find(), and replace() allow easy transformation and searching of string content, supporting tasks like formatting user inputs and parsing files. List methods like append(), extend(), sort(), and pop() enable efficient manipulation, modification, and sorting of list content, facilitating operations like aggregation and ordering data sets. These built-in methods simplify complex operations into single function calls, reducing development time and enhancing code efficiency and readability by encapsulating common functionalities within intuitive interfaces .

Lambda functions in Python, also known as anonymous functions, are small, single-expression functions defined using the lambda keyword. They are often used for short-lived operations where defining a standard function would be unnecessarily verbose, such as in functional programming paradigms with map(), filter(), and sort() operations. The benefits include reduced code size and increased readability for simple operations, as they keep the focus on functional logic without boilerplate code. However, their limitations include a single expression body, making them less suited for complex functions, and lack of name, which can complicate debugging .

You might also like