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

Python Functions

Uploaded by

n65622544
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)
6 views10 pages

Python Functions

Uploaded by

n65622544
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
You are on page 1/ 10

1.

Basic Built-in Functions

Type Conversion & Checking

Function Example Description

int() int("10") → 10 Converts to integer

float() float("3.14") → 3.14 Converts to float

str() str(100) → "100" Converts to string

bool() bool(0) → False Converts to boolean

chr() chr(65) → 'A' ASCII to character

ord() ord('A') → 65 Character to ASCII

bin() bin(10) → '0b1010' Integer to binary

hex() hex(255) → '0xff' Integer to hexadecimal

oct() oct(8) → '0o10' Integer to octal


complex() complex(2, 3) → 2+3j Creates complex number

type() type([]) → <class Returns object type


'list'>

isinstance() isinstance(5, Checks type


int) → True

Mathematical Functions

Function Example Description

abs() abs(-5) → 5 Absolute value

round() round(3.14159, 2) → 3.14 Rounds a number

pow() pow(2, 3) → 8 Exponentiation

divmod() divmod(10, 3) → (3, 1) Quotient & remainder

max() max([1, 2, 3]) → 3 Maximum value

min() min([1, 2, 3]) → 1 Minimum value

sum() sum([1, 2, 3]) → 6 Sum of iterable

Iterables & Sequences

Function Example Description

Length of
len() len("Python") → 6
object

range() list(range(1, 5)) → [1, 2, 3, 4] Generates


Function Example Description

sequence

Sorts
sorted() sorted([3, 1, 2]) → [1, 2, 3]
iterable

Reverses
reversed() list(reversed([1, 2, 3])) → [3, 2, 1]
sequence

enumerate( list(enumerate(['a', 'b'])) → [(0, 'a'),


Adds index
) (1, 'b')]

list(zip([1, 2], ['a', 'b'])) → [(1, 'a'), Pairs


zip()
(2, 'b')] iterables

Input/Output

Function Example Description

print() print("Hello", end=" ") → Hello Prints output

input() name = input("Enter name: ") Takes user input

open() with open("file.txt", "r") as f: File handling

2. String Methods

Method Example Description

str.upper() "hello".upper() → "HELLO" Uppercase

str.lower() "HELLO".lower() → "hello" Lowercase

str.strip() " hello ".strip() → "hello" Removes


Method Example Description

whitespace

str.split() "a,b,c".split(",") → ['a', 'b', 'c'] Splits string

str.join() "-".join(["a", "b"]) → "a-b" Joins list

Replaces
str.replace() "hello".replace("l", "x") → "hexxo"
substring

Finds
str.find() "hello".find("e") → 1
substring

str.startswith
"hello".startswith("he") → True Checks prefix
()

str.endswith() "hello".endswith("lo") → True Checks suffix

Checks if
str.isdigit() "123".isdigit() → True
numeric

"{} world".format("Hello") → "Hello String


str.format()
world" formatting

Modern
f-strings f"Value: {x}"
formatting

3. List Methods

Method Example Description

list.append() [1, 2].append(3) → [1, 2, 3] Adds element

[1, 2].extend([3, 4]) → [1, 2, 3,


list.extend() Extends list
4]
Method Example Description

list.insert() [1, 3].insert(1, 2) → [1, 2, 3] Inserts at index

Removes first
list.remove() [1, 2, 2].remove(2) → [1, 2]
match

[1, 2, 3].pop(1) → 2 (list Removes &


list.pop()
becomes [1, 3]) returns

list.index() [1, 2, 3].index(2) → 1 Finds index

Counts
list.count() [1, 2, 2].count(2) → 2
occurrences

list.sort() [3, 1, 2].sort() → [1, 2, 3] Sorts in-place

Reverses in-
list.reverse() [1, 2, 3].reverse() → [3, 2, 1]
place

list.copy() [1, 2].copy() → [1, 2] Shallow copy

list.clear() [1, 2].clear() → [] Empties list

4. Dictionary Methods

Method Example Description

dict.get() d.get("key", "default") Safe key access

dict.update() d.update({"new": "value"}) Merges


dictionaries

dict.keys() d.keys() → dict_keys(['a', 'b']) Returns keys

dict.values() d.values() → dict_values([1, 2]) Returns values


dict.items() d.items() → dict_items([('a', 1), Returns (key,
('b', 2)]) value) pairs

dict.pop() d.pop("key") Removes key &


returns value

dict.popitem() d.popitem() Removes last


item

dict.setdefault() d.setdefault("key", "default") Sets default if


missing

dict.clear() d.clear() → {} Empties


dictionary

5. Set Methods

Method Example Description

set.add() s.add(4) Adds element

Removes element
set.remove() s.remove(3) (error if
missing)

Removes element
set.discard() s.discard(3)
(no error)

Removes random
set.pop() s.pop()
element

set.union() s1.union(s2) → {1, 2, 3, 4} Combines sets

set.intersection() s1.intersection(s2) → {2} Common elements

Elements in s1
set.difference() s1.difference(s2) → {1}
not in s2
Method Example Description

set.symmetric_diffe s1.symmetric_difference(s2)
Unique elements
rence() → {1, 3, 4}

Adds all elements


set.update() s1.update(s2)
from s2

6. File Handling

Function/Method Example Description

open() with open("file.txt", "r") as f: Opens file

Reads entire
file.read() f.read()
file

file.readline() f.readline() Reads one line

Returns list
file.readlines() f.readlines()
of lines

file.write() f.write("text") Writes to file

Writes
file.writelines() f.writelines(["line1", "line2"])
multiple lines

file.seek() f.seek(0) Moves cursor

Returns cursor
file.tell() f.tell()
position

file.close() f.close() Closes file

7. Functional Programming
Function Example Description

list(map(lambda x: x*2, [1, 2, 3])) → [2, 4, Applies


map()
6] function

list(filter(lambda x: x > 2, [1, 2, Filters


filter()
3])) → [3] elements

Reduces
reduce() reduce(lambda x, y: x + y, [1, 2, 3]) → 6
iterable

Anonymous
lambda (lambda x: x + 1)(5) → 6
function

Checks if
any() any([False, True, False]) → True
any is True

Checks if
all() all([True, True, False]) → False
all are True

8. Object-Oriented Programming (OOP)

Function/Method Example Description

Defines a
class class MyClass:
class

__init__() def __init__(self, x): Constructor

Calls
super() super().__init__() parent
class

Class
@classmethod @classmethod def from_string(cls, s):
method
Function/Method Example Description

Static
@staticmethod @staticmethod def utility():
method

Getter
@property @property def name(self):
method

Setter
@name.setter @name.setter def name(self, value):
method

Checks
hasattr() hasattr(obj, 'x') → True
attribute

Gets
getattr() getattr(obj, 'x', 'default')
attribute

Sets
setattr() setattr(obj, 'x', 10)
attribute

9. Exception Handling

Function/Statement Example Description

try: x = 1/0 except


try-except Catches errors
ZeroDivisionError:

Raises
raise raise ValueError("Invalid")
exception

assert x > 0, "x must be Debug


assert
positive" assertion

Always
finally finally: f.close()
executes
10. Modules & Imports

Function/Statement Example Description

import import math Imports module

Imports specific
from-import from math import sqrt
function

as import numpy as np Alias

__import__() os = __import__('os') Dynamic import

You might also like