Python Basic
Python Basic
source code/program------>bytecode------>binary/machine
code---->computer
([Link]) ([Link])
(output)
Identifier:
Constant:
A constant is an identifier whose values cannot be changed
throughout the execution of the program whereas variable values
keep on changing.
Variable:
In python variables are considered as a tag and values are considered
as objects. In python, memory is allocated to the values instead of
variables. While in C and Java memory is allocated to the variable not
to the values.
Every variable name should start with alphabet or underscore(_)
No space are allowed in variable declaration
Except underscore(_) no other special symbol are allowed in the
middle of variable declaration
No reserved keyword can be use a variable name
Note:- In python memory allocated to the values, while in C and Java
memory is allocated to the variable.
>>>a=100
>>> id(a)
8791191328816
>>> b=100
>>> id(b)
8791191328816
In the above example both a and b have the same memory address
because in python memory is allocated to the values instead of
variables. Due to which less memory is utilized. While in C and Java
each variable is allocated a different memory address.
>>> a= 100
>>> a=200
>>> print(a)
>>>200
In this example first we assign value 10 to the variable a after that we
assign 20 to the variable b. As we discuss, python allocates memory
to the address not to the variable. As value 10 has no tag variable as
variable a given the value 20, so value 10 will become useless and it
will be deleted by the garbage collector in python.
print() function:
file: This is an optional parameter that specifies the file where you
want to print the output. By default, it's set to `[Link]`, which
means it prints to the standard output (usually the console).
flush: This is an optional parameter that, when set to `True`, forces the
output to be flushed immediately. By default, it's set to `False`.
Type Conversion:
input() function:
In Python, you can get input from the user using the `input()` function.
In the floor division // rounds the result down to the nearest whole
number
[Link] Comparison Operator
—-----------AND Operator—----------
True and Expression=Expression
False and Expression= False
True and Expression1 and Expression2 = Expression2
False and Expression1 and Expression2 = False
—-----------OR Operator—----------
True or Expression = True
False or Expression = Expression
True or Expression1 or Expression2 = True
False or Expression1 or Expression2 = Expression1
>>> a = 10
>>> b = 20
>>> c = 30
>>> print(a<b and c)
o/p- 30
>>> a = 10
>>> b = 20
>>> c = 30
>>> d = 40
>>> print(a<b and c and d)
o/p- 40
>>> a = 10
>>> b = 20
>>> c = 30
>>> d = 40
>>> print(a<b and a<d and c)
o/p- 30
[Link] Operators:
[Link] Operators:
[Link] Membership Operators:
Syntax
if condition:
# Code to be executed if the condition is True
If the condition is true then only the block of statements inside the if
statement will be executed.
If else statement:
Syntax
if condition:
# Code to be executed if the condition is True
else:
# Code to be executed if the condition is False
If the condition is true then only the block of statements inside the if
statement will be executed otherwise the else part will be executed.
If-elif statement:
Syntax
if condition1:
# Code to be executed if condition1 is True
elif condition2:
# Code to be executed if condition2 is True
elif condition3:
# Code to be executed if condition3 is True
# ...
else:
# Code to be executed if none of the conditions are True
The if-elif (short for "else if") statement in Python allows you to
evaluate multiple conditions and execute different blocks of code
based on the first condition that is True.
If the condition is true then only the block of statements inside the if
statement will be executed otherwise the elif part will be executed
If all conditions are false then lastly the else part will be executed.
While loop:
Syntax
while condition:
# Code to be executed as long as the condition is True
range() function:
For loop:
A `for` loop in Python is used to iterate over a sequence (such as a
list, tuple, string, or range) or any other iterable object.
Syntax
for variable in iterable:
# Code to be executed in each iteration
for: It is the keyword that starts the loop.
variable: This is a variable that takes the value of each item in the
iterable during each iteration.
iterable: This is the collection or sequence of items that the loop will
iterate over.
Code block: The indented block of code following the `for` statement is
executed in each iteration, with the `variable` taking on the value of
the current item from the iterable.
Break statement:
The `break` statement in Python is used to exit or terminate a loop
prematurely. It is commonly used within loops, such as `for` or `while`
loops, to immediately stop the loop's execution and exit it, even if the
loop's termination condition has not been met.
Syntax:
for variable in iterable:
if condition:
break
Syntax:
while condition:
if condition:
break
Continue Statement:
In Python, the `continue` statement is used inside loops (like `for` and
`while` loops) to skip the current iteration and proceed to the next
iteration of the loop.
Syntax:
Datatype:
Datatype represents the type of data stored into a variable or memory.
Built-in Datatype:
1.None type
2.Numeric type
3.Sequences
4.Sets
5.Mapping
User-defined datatype:
1.Array
2.Class
3.Module
1. None Type:
Mutable:
In Python, the term "mutable" refers to objects that can be modified
or changed after they are created.
● List
● Sets
● Dictionaries
● User defined Classes
Immutable:
In Python, "immutable" refers to objects that cannot be modified or
changed after they are created.
● Strings
● Tuples
● Integers, floats, booleans
● Immutable sets (frozensets):
1. Creating Strings:
You can create strings using single or double quotes. For example:
2. String Concatenation:
You can concatenate (combine) strings using the `+` operator:
3. String Length:
You can find the length of a string using the `len()` function:
length = len(my_string)
4. String Slicing:
str[start:end:step]: Slices the string from the 'start' index to 'end'
index.
str[:end]: Slices from the beginning to the 'end' index.
str[start:]: Slices from the 'start' index to the end.
step: An optional parameter indicating the step size, i.e., how many
characters to skip. If omitted, it defaults to 1.
String Method:
Python provides a wide range of string functions and methods that you
can use to manipulate strings.
Commonly used string functions and methods:
● [Link](delimiter, maxsplit):
Splits the string into a list of substrings using the delimiter.
delimiter is the character or substring at which the string
should be split. It is an optional parameter, and if not provided,
it defaults to splitting at whitespace (spaces, tabs, and
newline characters).
maxsplit is also an optional parameter that determines the
maximum number of splits to make. If not provided, or set to
-1, it will split the string as many times as possible.
● separator_string.join(iterable):
The join method in Python is used to concatenate elements of
an iterable (e.g., a list, tuple, or string) into a single string,
using a specified separator. It is the inverse operation of the
split method.
separator_string is the string that you want to use as a
separator between the elements of the iterable.
iterable is the collection of elements you want to join together.
● [Link](): Checks if the string consists of only digits.
Types of functions:
Built-in Functions:
Python provides a set of built-in functions that are always available
for you to use. Examples include `print()`, `len()`, `input()`, and
`type()`. These functions serve general purposes and are part of the
Python standard library.
User-Defined Functions:
You can create your own functions using the `def` keyword. These
functions are defined by you to perform specific tasks as needed in
your program. User-defined functions allow you to encapsulate logic
and promote code reusability.
1. Function Definition:
def function_name(parameters):
"""Optional docstring"""
# Function code
# ...
2. Function Call:
To use the function, you call it by its name, passing any required
arguments:
print( function_name(arguments))
Argument:
Nested Function:
Nested functions in Python refer to defining one function within
another function. The inner function has access to the variables and
scope of the outer function. This concept is often used to encapsulate
functionality or create helper functions within a larger function.
For example, in the function call `add(3, 5)`, the values `3` and `5` are
the actual arguments.
Example:
def add(a, b): # In the add function, a and b are formal arguments.
return a + b
Type of Arguments:
2. Keyword Arguments:
- Keyword arguments are actual arguments specified using the
parameter names in the function or method call.
- They allow you to pass arguments in any order as long as you
associate them with the correct formal parameters using their names.
3. Default Arguments:
- Default arguments are values assigned to formal parameters in the
function or method definition.
- If you don't provide a corresponding actual argument for a default
parameter, the default value is used.
Lambda Function:
Syntax:
Syntax :
Local variable:
In Python, a local variable is a variable that is defined within a
specific scope, such as within a function or a block of code. Local
variables have limited visibility, and they are only accessible
within the scope in which they are defined.
Global Variable:
Variables defined in the global scope are accessible from
anywhere within the script or module. They are not confined to
any specific function or code block and can be used globally
throughout the program.
Global keyword:
In Python, the global keyword is used to indicate that a variable
declared within a function should be treated as a global variable
rather than a local variable. When you create a variable inside a
function without using the
global keyword, it is considered a local variable, which
means it is only accessible within that function's scope.
Globals Function:
In Python, the globals() function is a built-in function that
returns a dictionary representing the current global
symbol table. This dictionary contains all global variables
and their values in the current module, including both
variables and functions.
Recursive function:
A recursive function in programming is a function that calls itself
to solve a problem. A recursive function is like a task that breaks
itself into smaller, similar tasks until it's easy enough to solve.
List:
List Method:
3. insert(i, x): Inserts element `x` at index `i`,and moves the current
element forward but does not replace the elements.
4. remove(x): Removes the first occurrence of element `x` from the list.
5. pop([i]): Removes and returns the element at index `i`. If `i` is not
specified, it removes and returns the last element.
8. count(x): Returns the number of times element `x` appears in the list.
Slicing of List:
In Python, slicing is a way to extract a portion of a list, string, or other
sequence types.
Syntax:
my_list[start:stop:step]
Concatenation of list:
In Python, you can concatenate lists using the + operator or by using
the extend() method.
Repetition of list:
If we want to create a list by repeating its elements, we can use the *
operator in Python. This operator allows you to repeat the elements
of a list a certain number of times.
Aliasing of list:
Aliasing in the context of lists refers to creating multiple references
(aliases) to the same list object. When you create an alias for a list
and modify the content of the list through one reference, the
changes will be reflected in all other references to the same list.
Coping of list:
In Python, when we need to create a copy or clone of a list, there are
two types of copy:
1. Shallow Copy:
A shallow copy creates a new object but does not create copies of
nested objects. Instead, it copies references to the nested
objects. We can use the `copy()` method or the `[:]` slice notation to
create a shallow copy.
2. Deep Copy:
List Function:
There is also a built-in list() function in Python. This function can be
used to convert other iterable objects (like strings, tuples, or
sets) into a list.
Tuple:
2. Immutable Nature:
- Tuples are immutable, meaning their elements cannot be changed
or modified after creation.
- Once a tuple is defined, you cannot add, remove, or modify
elements.
4. Accessing Elements:
- Elements in a tuple are accessed using indexing (starting from 0).
5. Length:
- The `len()` function returns the number of elements in a tuple.
Use Cases:
1. Coordinates:
2. RGB Color Values:
3. Employee Information:
4. Geographical Data:
5. Stock Data:
Tuple method:
Tuples in Python have two built-in methods: count() and index().
1. count() method:
Syntax:
[Link](element)
2. index() method:
Syntax:
[Link](element[, start[, end]])
Note: If the specified element is not found in the tuple, both `count()`
and `index()` methods will raise a `ValueError`. To avoid this, you can
check the presence of an element using the `in` operator before using
these methods.
Set:
2. Mutable: You can add and remove elements from a set. This allows
you to modify the content of a set after its creation.
3. Unique Elements: A set does not allow duplicate elements. If you
try to add an element that already exists in the set, it won't be added
again.
4. Syntax: Sets are defined using curly braces `{}` or the `set()`
constructor. For example:
my_set = {1, 2, 3, 4, 5}
empty_set = set()
7. Use Cases: Sets are useful when dealing with collections of unique
elements, such as removing duplicates from a list, checking for
membership, or performing set operations.
Sets are particularly useful in scenarios where you need to work with
unique elements and perform set operations efficiently.
Set operations:
1. Union (| or `union()`):
The union of two sets includes all unique elements from both sets.
2.1 intersection_update():
intersection_update() method is different from the intersection()
method, because the intersection() method returns a new set,
without the unwanted items, and the intersection_update()
method removes the unwanted items from the original set.
3. Difference (- or `difference()`):
The difference of two sets includes elements that are in the first set
but not in the second.
3.1 difference_update():
difference_update() method is different from the difference() method,
because the difference() method returns a new set, without the
unwanted items, and the difference_update() method removes
the unwanted items from the original set.
subset:-
For two sets A and B, if every element in set A is present in set B,
then set A is a subset of set B(A ⊆ B) and B is the superset of
set A(B ⊇ A).
Superset:-
In set theory, a superset is the opposite concept of a subset. If set (A)
contains every element of set (B), and possibly more elements,
then (A) is considered a superset of (B).
[ A = {1, 2, 3, 4, 5} ]
[ B = {1, 2, 3} ]
6. Superset (`issuperset()`):
Check if one set is a superset of another.
7. Disjoint Sets:
Two sets are disjoint sets if there are no common elements in both
sets.
Example: A = {1,2,3,4} B = {7,8,9,10}. Here, set A and set B are
disjoint sets.
1. add(element):
The add() method adds a single element to the set.
If the element already exists, the add() method does not add the
element.
2. update(iterable):
Adds multiple elements from an iterable (list, tuple, set, etc.) to the
set.
3. remove(element):
Removes the specified element from the set. Raises an error if the
element is not present.
4. discard(element):
Removes the specified element from the set if it is present. Does
not raise an error if the element is not found.
5. pop():
The pop() method removes and returns a random item from the
set. Raises an error if the set is empty.
Copy():
The copy() method copies the set.
clear():
The clear() method removes all elements in a set.
Dictionary:
4. Key-Value Pairs:
Dictionaries consist of key-value pairs separated by a colon (`:`). Each
key is followed by its corresponding value.
6. Accessing Values:
Values in a dictionary are accessed using their corresponding keys.
print(my_dict['name'])
7. Mutable:
Dictionaries are mutable, meaning you can modify, add, or remove
key-value pairs after the dictionary is created.
Dictionaries Method:
[Link]():
The clear() method removes all items from a dictionary. After using
clear(), the dictionary becomes empty.
Syntax:
my_dict.clear()
[Link]():
The copy() method in Python is used to create a shallow copy of a
dictionary. A shallow copy means that a new dictionary is created, but
the keys and values inside the new dictionary are references to the
same objects as the keys and values in the original dictionary.
Syntax:
copied_dict = original_dict.copy()
[Link]():
The fromkeys() method creates a new dictionary with keys from a
given iterable and values set to a default value.
Here, iterable is the iterable (list, tuple, etc.) from which keys will be
taken, and value is the default value to be set for all keys. If value
is not provided, it defaults to None.
Syntax:
[Link](iterable, value)
[Link]():
The get() method retrieves the value associated with a specified
key. It provides a way to safely access dictionary elements without
raising a KeyError if the key is not present.
Syntax:
[Link](key, default)
[Link]():
The items() method returns a view of the dictionary's key-value pairs
as tuples. Each tuple contains a pair of the key and its
corresponding value.
This view object can be converted to a list or used in various
iterations.
[Link]():
The keys() method displays a list of all the keys in a dictionary.
Syntax:
keys_view = my_dict.keys()
[Link]():
The values() method displays a list of all the values in a dictionary.
Syntax:
keys_view = my_dict.values()
[Link]():
The pop() method removes and returns the value associated with a
specified key from a dictionary. If the key is not found, it raises a
KeyError or returns a specified default value if provided.
syntax:
pop(key, default=None):
● key: The key whose associated value is to be removed and
returned.
● default (optional): If the key is not found, the method returns this
value. If not provided and the key is not found, a KeyError is
raised
[Link]():
The popitem() method removes and returns the last key-value pair
from the dictionary as a tuple.
Syntax:
removed_item = my_dict.popitem()
[Link]():
setdefault() method gets the value of a key from a dictionary. If the
key is present in the dictionary, it returns the corresponding value. If
the key is not present, it inserts the key with a specified default
value and returns that value.
syntax:
[Link](key, default_value)
List Comprehension:
List comprehension is a concise way to create lists in Python. It
allows you to create a new list by specifying the elements you
want to include, often in a single line of code. List comprehensions
are both expressive and efficient, making your code more readable
and concise.
Syntax:
new_list = [expression for item in iterable if condition]
Nested If statement:
Syntax:
new_list = [expression for item in iterable if condition1 if condition2 ...]
If else statement:
Syntax:
new_list = [result_if_true if condition else result_if_false for item in
iterable]
[Link]():
The map() function in Python is a built-in function that applies a
specified function to all items in an iterable (such as a list, tuple,
or string) and returns an iterator that produces the results. It
provides a concise way to perform operations on each element of
a collection without the need for explicit loops.
Syntax:
map(function, tierable, ...)
[Link]():
The `filter()` function in Python is a built-in function used for filtering
elements of an iterable (e.g., a list) based on a specified function
called a "predicate." The `filter()` function returns an iterator
containing the elements from the iterable for which the predicate
returns `True`.
Syntax:
filter(function, iterable)
[Link]():
The `reduce()` function in Python is part of the `functools` module
and is used to successively apply a function (a function taking two
arguments) to the items of an iterable, reducing it to a single
cumulative result. It's particularly useful for operations like computing
the sum of elements, finding the maximum value, or any other
cumulative operation like sum()`, `max()`, or `min()`
Syntax:
[Link](function, iterable)
Concept Meaning
Call by A copy of the variable is passed to the function. The
Value original is unchanged.
Call by The actual variable's reference is passed, so
Reference changes inside the function affect the original.
num = 10
modify(num)
print("Outside function:", num)
Output:
Inside function: 15
Outside function: 10
nums = [1, 2, 3]
modify_list(nums)
print("Outside function:", nums)
Output:
Inside function: [1, 2, 3, 100]
Outside function: [1, 2, 3, 100]
➡️ The list was modified both inside and outside the function.
🧠 Summary
Data Type Behavior in Function
int, float, str, Call by value-like
tuple (immutable)
list, dict, set Call by reference-like
(mutable)