Wednesday, March 13, 2024

Python: Functions Cheatsheet Part-1

 



Functions

A function is like a   mini ­program within a program that performs a specific task.


Why functions?

  1. Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read, understand, and debug.
  2. A major purpose of functions is to group code that gets executed multiple times. Without a function defined, you would have to copy and paste this code each time.

Common Built­in Functions:

abs()
help()
min()
max()
hex() ­ hexadecimal representation of an integer
bin() ­ binary
oct() ­ octal
id()
input()
int()
float()
str()
print()
bool()
range()
round()
pow()
sum()
ord()
len()
type()

Common str methods:

capitalize()
count()
encode()
endswith()
expandtabs()
find()
format()
isalpha()
isdigit()
isdecimal()
islower()
isupper()
join()
startswith()
swapcase()
title()

User ­defined functions 

Definition of a function 

Syntax

def functionName(parameters) : statement(s)


The keyword def introduces a function definition.
It must be followed by the function name and the parenthesized list of formal parameters.
There can be number of arguments in a function.
The statements that form the body of the function start at the next line, and must be indented.