0% found this document useful (0 votes)
14 views8 pages

Python Programming Basics Guide

python short notes

Uploaded by

saha.arghaq
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)
14 views8 pages

Python Programming Basics Guide

python short notes

Uploaded by

saha.arghaq
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 NOTES

1. Introduction to Python

• Developed by: Guido van Rossum (1991)

• Type: High-level, interpreted, object-oriented language

• File extension: .py

• Execution:

• python [Link]

Features

• Simple & easy to learn

• Open-source & free

• Platform independent

• Object-oriented

• Huge library support

• Dynamic typing (no need to declare variable type)

2. Basic Syntax

print("Hello, World!")

a = 10

b = 20

print(a + b)

• Indentation: Defines code blocks (no braces {})

• Comments:

• # Single line

• '''Multi-line comment'''
3. Data Types

Type Example Description

int a=5 Integer numbers

float b = 3.14 Decimal numbers

str s = "Hello" String

bool flag = True Boolean

list [1,2,3] Ordered, mutable

tuple (1,2,3) Ordered, immutable

set {1,2,3} Unordered, unique

dict {'a':1,'b':2} Key-value pairs

complex 3+4j Complex numbers

Check type:

type(a)

4. Operators

• Arithmetic: + - * / % // **

• Comparison: == != > < >= <=

• Logical: and or not

• Assignment: = += -= *=

• Membership: in, not in

• Identity: is, is not

5. Control Statements

If-Else

x = 10

if x > 0:
print("Positive")

elif x == 0:

print("Zero")

else:

print("Negative")

Loops

for i in range(5):

print(i)

while i < 5:

print(i)

i += 1

Jump Statements

break, continue, pass

6. Functions

def add(a, b):

return a + b

print(add(2, 3))

• Default argument: def greet(name="User"):

• Lambda function:

• f = lambda x: x * x

• print(f(5))

7. Data Structures

List

nums = [1, 2, 3]
[Link](4)

[Link](2)

[Link]()

print(nums[0])

Tuple

t = (1, 2, 3)

print(t[1])

Set

s = {1, 2, 3, 2}

[Link](4)

print(s)

Dictionary

d = {'name': 'Alice', 'age': 25}

print(d['name'])

d['age'] = 30

8. Strings

s = "Python"

print([Link]())

print([Link]())

print(s[0:3])

print(len(s))

print([Link]("P", "J"))

9. File Handling

f = open("[Link]", "w")

[Link]("Hello Python")

[Link]()
f = open("[Link]", "r")

print([Link]())

[Link]()

10. Exception Handling

try:

x=5/0

except ZeroDivisionError:

print("Cannot divide by zero")

finally:

print("Done")

11. Object-Oriented Programming (OOP)

class Student:

def __init__(self, name, age):

[Link] = name

[Link] = age

def display(self):

print([Link], [Link])

s1 = Student("John", 20)

[Link]()

Concepts:

• Inheritance

• class A:

• def show(self): print("A")


• class B(A):

• def show(self): print("B")

• Polymorphism

• Encapsulation

• Abstraction

12. Modules & Packages

import math

print([Link](16))

from math import pi

print(pi)

• Create your own module: Save code as [Link], then import mymodule

13. Iterators & Generators

def gen():

for i in range(3):

yield i

for val in gen():

print(val)

14. Important Built-in Functions

len(), type(), id(), range(), sorted(), max(), min(), sum(), input(), int(), str(), list(), tuple(),
set(), dict()

15. File I/O with with

with open("[Link]", "r") as f:

data = [Link]()
16. Libraries to Know

Category Library

Data Analysis pandas, numpy

Visualization matplotlib, seaborn

Web flask, django

Machine Learning scikit-learn

Automation os, sys, shutil

Networking socket, requests

17. Input/Output Example

name = input("Enter name: ")

print("Hello", name)

18. Miscellaneous

• List Comprehension:

• squares = [x*x for x in range(5)]

• Dictionary Comprehension:

• d = {x: x*x for x in range(5)}

• Enumerate:

• for i, val in enumerate(['a','b','c']):

• print(i, val)

19. File Path & OS

import os

print([Link]())

[Link]("new_folder")
20. Quick Summary

• Everything is an object.

• Indentation = code block.

• No need for type declaration.

• Functions are first-class citizens.

• Powerful standard library.

• Interpreted, cross-platform, and easy to use.

Common questions

Powered by AI

Python's control statements, such as if-else and loops (for and while), enhance programming efficiency by providing straightforward ways to control the flow of execution based on conditions. For example, using a for loop with a range function allows iteration over a sequence of numbers, which can simplify tasks like iterating over elements to sum their values: for i in range(5): sum += i .

File handling in Python is essential for reading from and writing to files, which is critical for data storage and processing. It allows interaction with data persisted on a disk, which is crucial for applications requiring data permanence. For example, to write to a file, you can use: `f = open('file.txt', 'w') f.write('Hello Python') f.close()`. Subsequently, reading the content is accomplished with: `f = open('file.txt', 'r') print(f.read()) f.close()` .

Exception handling in Python enhances program reliability by allowing the program to continue executing or gracefully terminate in the event of unexpected conditions or errors. It uses `try`, `except`, and `finally` blocks to catch errors and manage program flow. For example, a ZeroDivisionError can be handled as follows: `try: x = 5 / 0 except ZeroDivisionError: print('Cannot divide by zero') finally: print('Done')`. This prevents the program from crashing and allows for cleanup actions .

Object-oriented programming in Python involves organizing code into objects that encapsulate data and behavior. It supports code reuse through inheritance, where a new class (derived or child class) inherits attributes and methods from an existing class (base or parent class). This hierarchy allows for extending or modifying existing functionalities without altering the parent class, facilitating code reuse and extension. For instance, class B(A) inherits A's methods, which can be customized in B .

Python's libraries such as pandas and numpy for data analysis, and matplotlib and seaborn for visualization, significantly contribute to its popularity in data science. Pandas support complex data manipulation and analysis through structures like DataFrames, while numpy provides arrays for efficient numerical operations. Visualization libraries like matplotlib and seaborn allow for creating a wide variety of plots and data visualizations, facilitating insight generation. These libraries collectively enable robust data analysis workflows and are integral to Python's appeal in data science .

Python's built-in functions simplify code by providing ready-to-use operations that handle common tasks efficiently, such as determining length with len() or sorting lists with sorted(). For example, the sum() function can be used in data analysis to quickly calculate the total of a list of numbers: sum([1, 2, 3, 4]) returns 10, eliminating the need to manually iterate and accumulate the total .

Python uses dynamic typing, which means variables do not require an explicit declaration of their types. This allows for greater flexibility since the type of a variable can change at runtime, and reduces verbosity by eliminating the need for type specification at variable declaration. Dynamic typing simplifies code maintenance and adaptation while supporting rapid prototyping and development .

List comprehensions in Python improve code conciseness by providing a compact syntax to create lists based on existing iterables, enabling operations and transformations to be performed within a single line instead of using traditional loops. For instance, creating a list of squared numbers can be efficiently done with `[x*x for x in range(5)]`, generating [0, 1, 4, 9, 16] without a multi-line loop .

Python's use of generators for asynchrony provides a lazy and memory-efficient alternative to traditional methods like threading and multiprocessing. Generators yield data only when needed, reducing memory overhead, whereas threading and multiprocessing create parallel execution environments that can be more resource-intensive. This makes generators suitable for I/O-bound tasks, allowing the pausing of function execution while maintaining low resource usage. Unlike the concurrency of threads and multiprocessing, generators provide cooperative multitasking without the complexity of managing asynchronous state across multiple threads or processes .

Iterators in Python allow for traversal of a data sequence without storing the actual data in memory, enhancing memory efficiency. Generators, which are a type of iterator, improve this further by yielding elements one at a time and pausing execution between each yield, thus avoiding memory allocation for the entire dataset at once. This makes them ideal for large datasets or streams of data. Generators are defined using the `yield` keyword inside a function, unlike iterators which require defining an explicit `__iter__` and `__next__` method .

You might also like