O GoConqr está de visual novo! Conte para nós o que você achou.

Notas

Python

nik john Engineering Inglês 2 páginas

Conteúdo das notas (2)

Página 1

Página 2

PYTHON

OUTPUT – print()

print() is used to display output on the screen.

Syntax:

print(value)

Examples:

print("Hello World")

print(3.14)

print(2 + 3)

print("Hello", "World")

Anything inside single (' ') or double (" ") quotes is called a string and prints as it is.

PYTHON CHARACTER SET

Python supports:

• Letters: a-z, A-Z

• Digits: 0-9

• Special symbols: + - * / % @ _ etc.

• Whitespaces: space, \t (tab), \n (newline)

• ASCII and Unicode characters

VARIABLES

A variable stores data (value).

Examples:

name = "Shradha"

age = 30

PI = 3.14

VARIABLE NAMING RULES (Identifiers)

Must start with a letter or underscore (_)

Can contain letters, digits, underscores

Cannot use Python keywords (if, for, class, while, def, etc.)

Invalid examples:

2name = "Bob"

class = 10

IMPORTANT NOTES

• Python is dynamically typed (no need to declare type).

• Python is case-sensitive (age and Age are different).

• Indentation is important (standard: 4 spaces).

• Keywords are reserved words (if, for, while, def, class, else, in, etc.)

DATA TYPES

A data type defines the type of value stored.

Basic Data Types:

int → Whole numbers (10, 25)

float → Decimal numbers (3.14, 2.5)

str → Text ("hello")

bool → True or False

None → No value

Other data types:

list, tuple, set, complex

Checking type:

x = 10

print(type(x))

TYPE CONVERSION & TYPE CASTING

Type Conversion is converting one data type to another.

Implicit Conversion (Automatic)

a = 5

b = 3.0

print(a + b) → Result becomes float automatically

Explicit Type Casting (Manual)

Common functions:

int(), float(), str(), bool(), list(), tuple()

Example:

x = 10

y = float(x)

z = str(x)

OPERATORS

Operators perform operations on values (operands).

Example:

print(1 + 3)

A) ARITHMETIC OPERATORS

Addition

Subtraction

Multiplication

/ Division

% Modulus (remainder)

** Power

// Floor division

Example:

a = 5

b = 2

print(a + b)

print(a - b)

print(a * b)

print(a / b)

print(a % b)

print(a ** b)

print(a // b)

B) RELATIONAL (COMPARISON) OPERATORS

== Equal

!= Not equal

Greater than

< Less than

= Greater than or equal

<= Less than or equal

Example:

a = 10

b = 20

print(a == b)

print(a != b)

print(a > b)

print(a < b)

C) ASSIGNMENT OPERATORS

= Assign

+= Add and assign

-= Subtract and assign

*= Multiply and assign

/= Divide and assign

%= Modulus and assign

**= Power and assign

Example:

x = 10

x += 5

x -= 3

x *= 2

x /= 4

x %= 4

x **= 3

D) LOGICAL OPERATORS

and → True if both conditions are true

or → True if at least one condition is true

not → Reverses the result

Example:

x = 10

y = 20

z = 5

print(x > z and y > x)

print(x > y or y > z)

print(not (x > y))

E) UNARY OPERATORS

Operate on single operand.

+x → Unary plus

-x → Unary minus

not → Logical NOT

~x → Bitwise NOT

Example:

x = 5

print(-x)

print(+x)

OPERATOR PRECEDENCE (Order of Execution)

Highest to Lowest:

() Parentheses

** Exponent

+x, -x, ~x (Unary)

*, /, //, %

+, -

<<, >>

&

^

|

Comparison (==, !=, >, <, >=, <=)

not

and

or

Assignment (=, +=, -=, etc.)

INPUT – input()

Used to take user input during program execution.

Syntax:

variable = input("message")

Important: input() always returns a string.

Example:

name = input("Enter name: ")

print(name)

print(type(name))

Converting input type:

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

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

print(a + b)

CONDITIONAL STATEMENTS

Conditional statements allow decision-making based on True/False conditions.

Main types:

if → Executes block if condition is True

elif → Checks another condition

else → Executes if all above conditions are False

Basic Syntax:

if condition:

code

elif condition:

code

else:

code

Example 1 – Age Check:

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

if age >= 18:

print("You can vote")

else:

print("You cannot vote")

Example 2 – Traffic Light:

color = input("Enter color: ")

if color == "red":

print("Stop")

elif color == "yellow":

print("Look")

elif color == "green":

print("Go")

else:

print("Invalid color")

Important:

• elif and else cannot exist without if.

• Multiple if statements are allowed.

LOGICAL OPERATORS IN CONDITIONS

and → Both conditions True

or → At least one True

not → Reverses result

Example:

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

if age < 13:

print("Child")

elif age >= 13 and age < 18:

print("Teenager")

else:

print("Adult")

NESTED CONDITIONALS

Placing one if inside another.

Example – Login System:

username = input("Enter username: ")

password = input("Enter password: ")

if username == "admin" and password == "pass":

print("Login successful")

else:

if username != "admin":

print("Wrong username")

else:

print("Wrong password")

TERNARY STATEMENT (One-line if-else)

Syntax:

value_if_true if condition else value_if_false

Example:

age = 18

status = "Adult" if age >= 18 else "Not Adult"

print(status)

Note:

• Used only for simple conditions.

• Can always be replaced with normal if-else.

MATCH-CASE (Python 3.10+)

Alternative to long if-elif chains.

Syntax:

match variable:

case value1:

code

case value2:

code

case _:

default code

Example:

color = input("Enter color: ")

match color:

case "red":

print("Stop")

case "yellow":

print("Look")

case "green":

print("Go")

case _:

print("Invalid color")

_ acts like default case.

LOOPS

Loops repeat a block of code.

Types:

while loop

for loop

WHILE LOOP

Repeats while condition is True.

Syntax:

while condition:

code

Example 1 – Print 1 to 5:

i = 1

while i <= 5:

print(i)

i += 1

Example 2 – Reverse 5 to 1:

i = 5

while i > 0:

print(i)

i -= 1

Infinite Loop:

If condition always True, loop never stops.

Example (Do NOT run):

while True:

print("Hello")

LOOP CONTROL STATEMENTS

break → Stops loop immediately

continue → Skips current iteration

Example – break:

i = 1

while i <= 10:

if i % 6 == 0:

break

print(i)

i += 1

Example – continue:

i = 0

while i < 10:

i += 1

if i % 3 == 0:

continue

print(i)

FOR LOOP

Used to iterate over a sequence (string, list, range, etc.)

Syntax:

for variable in sequence:

code

Example – range:

for i in range(5):

print(i)

Output: 0 1 2 3 4

MEMBERSHIP OPERATOR – in

Used to check existence in sequence.

Example:

word = "Prime"

for ch in word:

print(ch)

if 'i' in word:

print("Letter exists")

COUNTING USING LOOP

word = "artificial intelligence"

count = 0

for ch in word:

if ch == 'i':

count += 1

print("i occurs", count, "times")

NESTED LOOPS

Loop inside another loop.

for i in range(1, 3):

for j in range(1, 3):

print(i, j)

RANGE() FUNCTION

Generates number sequence.

Parameters:

range(start, stop, step)

• start default = 0

• stop = excluded

• step default = 1

Examples:

range(5) → 0 to 4

range(1, 6) → 1 to 5

range(1, 10, 2) → 1 3 5 7 9

FUNCTIONS

Functions are reusable blocks of code.

Definition:

def function_name():

code

Calling:

function_name()

Example:

def hello():

print("Hello")

hello()

FUNCTION WITH PARAMETERS

Parameters → Variables in function definition

Arguments → Values passed during call

Example:

def sum(a, b):

print(a + b)

sum(5, 10)

RETURN STATEMENT

Returns value from function.

def avg(a, b, c):

return (a + b + c) / 3

print(avg(1, 2, 3))

DEFAULT PARAMETERS

Provide default value.

Rules:

• Default parameters must come last.

• Cannot place non-default after default.

Example:

def sum(a, b=1):

return a + b

print(sum(5)) # 6

BUILT-IN FUNCTIONS

Predefined functions in Python.

Examples:

print()

input()

type()

range()

LAMBDA FUNCTIONS

Short anonymous one-line functions.

Syntax:

lambda arguments: expression

Example:

square = lambda x: x * x

print(square(5))

PRACTICE PROGRAMS (IMPORTANT)

Multiple of 5

num = int(input("Enter number: "))

if num % 5 == 0:

print("Multiple of 5")

else:

print("Not multiple of 5")

Odd or Even

num = int(input("Enter number: "))

if num % 2 == 0:

print("Even")

else:

print("Odd")

Multiplication Table

n = int(input("Enter number: "))

i = 1

while i <= 10:

print(n * i)

i += 1

Sum of First N Natural Numbers

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

total = 0

for i in range(1, n+1):

total += i

print("Sum =", total)

Factorial

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

fact = 1

for i in range(1, n+1):

fact *= i

print("Factorial =", fact)

Largest of 3 Numbers

def get_largest(a, b, c):

if a > b and a > c:

return a

elif b > c:

return b

else:

return c

print(get_largest(3, 10, 5))

1️⃣ STRINGS

What is a String?

A string is a sequence of characters enclosed in quotes ("" or '').

Strings are immutable (cannot be changed after creation).

s = "Hello" print(type(s)) #

len() – Length of String

word = "Prime" print(len(word)) # 5

Concatenation (+)

str1 = "Apna" str2 = "College" word = str1 + " " + str2 print(word) # Apna College

Loop on String

s = "Python" for ch in s: print(ch)

Indexing (Zero-Based)

First index = 0

Negative indexing allowed

s = "Python" print(s[0]) # P print(s[3]) # h print(s[-1]) # n

Slicing

Syntax:

string[start:stop:step]

start → inclusive (default 0)

stop → exclusive

step → default 1

s = "Python" print(s[0:2]) # Py print(s[2:]) # thon print(s[:3]) # Pyt print(s[::2]) # Pto print(s[::-1]) # nohtyP

String Formatting

1. Using .format()

name = "Rahul" age = 25 text = "My name is {} and I am {} years old".format(name, age) print(text) print("Coordinates: {1}, {0}".format("x", "y")) print("Name: {n}, Age: {a}".format(n="Bob", a=30))

2. Using f-strings (Preferred)

name = "Rahul" age = 25 print(f"My name is {name} and I am {age} years old") a = 5 b = 10 print(f"sum = {a + b}") print(f"avg = {(a + b)/2}")

2️⃣ LISTS

What is a List?

Ordered

Mutable

Allows duplicates

Heterogeneous (different data types)

Written using []

my_list = [1, 2, 3] my_list2 = [10, "Hello", 3.14, True]

Indexing

fruits = ["apple", "banana", "cherry"] print(fruits[0]) # apple print(fruits[-1]) # cherry

Modify Elements (Mutable)

nums = [1, 2, 3, 4] nums[0] = 10 print(nums) # [10, 2, 3, 4]

Slicing

Syntax:

list[start:stop:step]

numbers = [0,1,2,3,4,5,6,7,8,9] print(numbers[2:5]) # [2,3,4] print(numbers[:4]) # [0,1,2,3] print(numbers[5:]) # [5,6,7,8,9] print(numbers[::2]) # [0,2,4,6,8] print(numbers[-5:-2]) # [5,6,7]

List Methods

len()

nums = [5,2,9] print(len(nums)) # 3

append()

nums.append(7)

insert(index, element)

nums.insert(1,4)

sort()

nums.sort()

reverse()

nums.reverse()

Loop on List

numbers = [10,20,30] for num in numbers: print(num)

Linear Search

numbers = [5,12,7,3,18,9] target = 18 for idx in range(len(numbers)): if numbers[idx] == target: print(f"{target} found at index {idx}") break

3️⃣ TUPLES

What is a Tuple?

Ordered

Immutable

Allows duplicates

Heterogeneous

Written using ()

t = (10, 20, 30) print(type(t))

Special cases:

empty_tuple = () single = (42,)

Indexing & Slicing (Same as List)

t = (10,20,30,40) print(t[0]) # 10 print(t[-1]) # 40 print(t[1:3]) # (20,30)

Loop on Tuple

for val in t: print(val)

Sum of Tuple Elements

t = (5,15,25) total = 0 for val in t: total += val print(total)

Tuple Methods

index()

t = (1,2,2,3) print(t.index(2)) # 1

count()

print(t.count(2)) # 2

4️⃣ DICTIONARIES

What is a Dictionary?

Unordered (insertion order preserved in modern Python)

Mutable

Key–Value pairs

Keys must be unique & immutable

Written using {}

student = { "name": "Bob", "age": 20 }

Access Values

print(student["name"])

Dictionary Methods

keys()

print(student.keys())

values()

print(student.values())

items()

print(student.items())

get() (Safe access)

print(student.get("age")) print(student.get("city")) # None

update()

student.update({"city": "Delhi"})

Loop on Dictionary

d = { "name": "Shradha", "cgpa": 9.5 } for key, value in d.items(): print(key, value)

5️⃣ SETS

What is a Set?

Unordered

Unique elements only

Mutable

No indexing/slicing

Written using {}

my_set = {1,2,2,3} print(my_set) # {1,2,3}

Empty set:

empty_set = set()

Set Methods

add()

s = {10,20,30} s.add(40)

remove()

s.remove(10)

pop()

(Removes random element)

s.pop()

clear()

s.clear()

Union & Intersection

A = {1,2,3} B = {3,4,5} print(A.union(B)) # {1,2,3,4,5} print(A.intersection(B)) # {3}

Type | Ordered | Mutable | Duplicates | Indexing

--------------------------------------------------------

String | Yes | No | Yes | Yes

List | Yes | Yes | Yes | Yes

Tuple | Yes | No | Yes | Yes

Dictionary | No* | Yes | Keys: No| By Key

Set | No | Yes | No | No

Object Oriented Programming (OOP)

1️⃣ Object Oriented Programming (OOP)

OOP is a programming paradigm that organizes code into objects (data + behavior).

Data → Attributes (variables)

Behavior → Methods (functions)

It helps in:

Modularity

Reusability

Maintainability

Real-world modeling

2️⃣ Class & Object

Class

Blueprint/template for creating objects.

Defines attributes and methods.

Object

Instance of a class.

Contains real data.

Created from class.

Example:

class Car: brand = "Toyota" car1 = Car() car2 = Car() print(car1.brand) print(car2.brand)

Class vs Object

Class:

Blueprint

Does not hold actual data

Can create multiple objects

Object:

Real instance

Holds actual data

Occupies memory

3️⃣ Constructor

Special method to initialize objects.

Called automatically when object is created.

Defined using __init__().

class Student: def __init__(self): print("Constructor called") stu1 = Student()

self Keyword

Refers to current object.

Used to access instance variables.

Passed automatically.

Parameterized Constructor

class Student: def __init__(self, name): self.name = name stu1 = Student("Rahul") stu2 = Student("Harshita") print(stu1.name, stu2.name)

Types of Constructors

Default → only self

Parameterized → takes arguments

Note: Python does NOT support constructor overloading like Java/C++.

4️⃣ Attributes in OOP

Attributes store data of object.

1. Class Attributes

Shared by all objects

Defined outside methods

class Student: college = "ABC College" stu1 = Student() print(stu1.college) print(Student.college)

2. Instance Attributes

Unique to each object

Defined inside __init__()

class Student: def __init__(self, name, gpa): self.name = name self.gpa = gpa stu1 = Student("Rahul", 8.7) print(stu1.name, stu1.gpa)

5️⃣ Methods in OOP

Methods = Functions inside class.

1. Instance Methods

Take self as first parameter

Can access instance & class attributes

class Student: def __init__(self, name, marks): self.name = name self.marks = marks def display(self): print(f"Name: {self.name}, Marks: {self.marks}")

2. Class Methods

Use @classmethod

Take cls as first parameter

Used for class-level data

class Student: school_name = "ABC School" @classmethod def change_school(cls, new_name): cls.school_name = new_name

3. Static Methods

Use @staticmethod

Do NOT take self or cls

Logical grouping only

class Math: @staticmethod def add(a, b): return a + b

6️⃣ 4 Pillars of OOP

Encapsulation

Abstraction

Inheritance

Polymorphism

7️⃣ Encapsulation

Bundling data + methods together and controlling access.

Access Modifiers in Python

1. Public

Accessible everywhere

class Student: def __init__(self, name): self.name = name

2. Protected (_variable)

Single underscore

Meant for internal use

class Person: def __init__(self): self._age = 20

3. Private (__variable)

Double underscore

Name mangling happens

Cannot access directly

class Bank: def __init__(self, balance): self.__balance = balance b = Bank(5000) print(b._Bank__balance) # name mangled access

Getters & Setters

Used to access private variables.

class Employee: def __init__(self, salary): self.__salary = salary def get_salary(self): return self.__salary def set_salary(self, new_salary): self.__salary = new_salary

8️⃣ Inheritance

Child class inherits properties & methods from parent.

Parent → Base / Superclass

Child → Derived / Subclass

Benefits:

Code reuse

Cleaner design

Extensibility

1. Single Inheritance

class Parent: def display(self): print("Parent class") class Child(Parent): pass c = Child() c.display()

2. Multi-Level Inheritance

class Employee: start_time = "9AM" class AdminStaff(Employee): pass class Accountant(AdminStaff): pass

3. Multiple Inheritance

class Teacher: def __init__(self, salary): self.salary = salary class Student: def __init__(self, gpa): self.gpa = gpa class TA(Teacher, Student): def __init__(self, salary, gpa): Teacher.__init__(self, salary) Student.__init__(self, gpa)

super() Keyword

Used to call parent class method.

super().__init__(role)

9️⃣ Abstraction

Hiding implementation details and showing only essential features.

Implemented using:

Abstract Classes

Abstract Methods

Abstract Class Example

from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def make_sound(self): pass class Lion(Animal): def make_sound(self): print("Roar") class Cow(Animal): def make_sound(self): print("Moo")

Abstract class:

Cannot be instantiated

Must override abstract methods

🔟 Polymorphism

Same function/operator behaves differently.

1. Operator Overloading

print(1 + 2) # Addition print("1" + "2") # Concatenation

2. Method Overriding (Runtime Polymorphism)

class Animal: def sound(self): print("Generic sound") class Dog(Animal): def sound(self): print("Bark") a = Animal() d = Dog() a.sound() d.sound()

Child method overrides parent method.

3. Duck Typing

"If it looks like a duck and behaves like a duck, it’s a duck."

class Dog: def speak(self): print("Bark") class Cat: def speak(self): print("Meow") def make_it_speak(entity): entity.speak() d = Dog() c = Cat() make_it_speak(d) make_it_speak(c)

No type checking required — behavior matters.

1️⃣ FILE I/O (Input / Output)

File I/O means reading from and writing to files using Python.

Opening a File

Syntax:

file = open("filename", "mode")

Example:

f = open("data.txt", "r")

File Modes

r → Read (default, error if file doesn't exist)

w → Write (creates/overwrites file)

a → Append (adds at end)

r+ → Read + Write

w+ → Write + Read (overwrites)

a+ → Append + Read

b → Binary mode (rb, wb)

Reading from a File

1. read() → Reads entire file

f = open("data.txt", "r") content = f.read() print(content) f.close()

2. readline() → Reads one line

f = open("data.txt", "r") line1 = f.readline() line2 = f.readline() f.close()

3. readlines() → Returns list of lines

f = open("data.txt", "r") lines = f.readlines() f.close()

Writing to a File

1. write() → Write string

f = open("data.txt", "w") f.write("Hello students!") f.close()

2. writelines() → Write multiple lines

f = open("data.txt", "a") f.writelines(["Line 1\n", "Line 2\n"]) f.close()

Recommended Way (Context Manager)

Automatically closes file.

with open("data.txt", "r") as f: content = f.read() print(content)

Deleting a File

import os os.remove("data.txt")

2️⃣ EXCEPTION HANDLING

An exception is an error during program execution.

Exception handling prevents program crash.

Common Exceptions

ZeroDivisionError

NameError

FileNotFoundError

TypeError

ValueError

Basic Syntax

try: # risky code except: # handle error

Handling Specific Exception

try: print(10 / 0) except ZeroDivisionError: print("Cannot divide by zero")

Multiple Blocks

else → Runs if NO exception

try: x = int(input("Enter number: ")) except ValueError: print("Invalid input") else: print("You entered:", x)

finally → Always runs

try: f = open("data.txt") except FileNotFoundError: print("File not found") finally: print("Execution completed")

Used for cleanup tasks.

3️⃣ LIST COMPREHENSION

Short, elegant way to create lists.

Basic Syntax

[expression for item in iterable]

Example:

nums = [x for x in range(1, 6)] print(nums) # [1,2,3,4,5]

With Condition

[expression for item in iterable if condition]

Example:

evens = [x for x in range(1, 11) if x % 2 == 0] print(evens)

With if-else

[true_value if condition else false_value for item in iterable]

Example:

labels = ["Even" if x % 2 == 0 else "Odd" for x in range(1, 6)] print(labels)

4️⃣ JSON MODULE

JSON (JavaScript Object Notation) is a lightweight data format.

Similar to Python dictionary.

Import:

import json

Convert Python → JSON String

dumps()

import json data = { "name": "John", "age": 25, "marks": [85, 90, 92] } json_string = json.dumps(data) print(json_string)

Convert JSON String → Python

loads()

json_data = '{"name": "John", "age": 25}' python_obj = json.loads(json_data) print(python_obj["name"])

Write JSON to File

json.dump()

import json data = {"name": "Aisha", "city": "Delhi"} with open("data.json", "w") as f: json.dump(data, f, indent=4)

indent=4 → Makes JSON readable.

Read JSON from File

json.load()

import json with open("data.json", "r") as f: data = json.load(f) print(data)

Informações

Descrição
Notes
Criado por
nik john
Visualizações
2
Avaliação

Fale Conosco

Sobre o que é sua mensagem?

O que você acha do novo visual?

Você gostou?