You are on page 1of 29

How operations are performed in Python language?

Different types of Arithmetic operations


What are strings?
How strings are used in Python?
Function in a Python
Concatenation and Repetition of Strings
New line character and Raw string
1 - We will the Python IDLE in this tutorial. - The language that the computer
understands is Binary Code i.e, 0 and 1.
We use a programming language to write code, which is neither a binary
language nor English. - Programming language has its own protocols and
grammar which we use. - We will write code in a programming language say
Python and then it will convert into a binary format that the computer will
understand.
We can perform several operations using Python language.
2 - Starting with operations like Addition, Subtraction, Multiplication, and
Division.
We do addition, subtraction and multiplication with integer values, and then it
gives us answers also in integer data type.
But when performing division with integer values then it gives us an answer in
float data type. - Float stands for Floating Point Representation.
When we divide two integer values then it might be possible that the answer
can in decimal. e.g., 5/2 = 2.5 -As the interpreter wants to give you an exact
answer for the division also, it will return it in float.
If you want to get only the quotient part or the integer part of the answer and
want to neglect the decimal value, it can be done with the help of (//). - //
(double slash) is used for division when you want to return only an integer
value in the answer. - // is also called Integer Division or Floor Division.
We can multiple operations in a single statement as well. - We need to follow
the proper syntax for the programming language. - If we apply an operation
but do not give operands, then it will give an error. 8+9- = Error - We can also
apply BODMASS rules of mathematics to perform operations. - Double
asterisks (**) is used to find the power of a number. number ** power = 2**3
= 2*2*2 - To get the remainder, we use the modulus operator (%).
3 - String is a combination of characters like "Youtube", "Camera", "Telusko",
"Python", etc., all are strings.
Whenever we use strings, we need to use double quotes(" ") or single quotes('
') with it in python.
If you back-slash(\) to tell the python to ignore the special meaning of that
double and single quotes. If you use a back-slash before a single or double
quotes then the quote is also treated as a simple character.
4 - Function is a set of tasks that can be done. We need to call functions. There
are several functions in Python like the print() function.
Round brackets are used with a function to pass a parameter in it.
We can define our own functions as well.
5 - Concatenation is used to combine two things like we can convert two
strings into one using concatenation.
Concatenation is done using the (+) operator. e.g., 'navin' + 'navin'
Repetition is used to print a single value multiple times like we can print a
string like "Navin" multiple times.
Repetition is done using the (*) operator. e.g., 'navin' * 3
6 - (\n) has a special meaning in Python. It is used to enter a new line.
To print the original string or to neglect the meaning of \n, we have to use a
Raw String.
Raw string is a string that returns it as it is without making any changes to it.
We have to specify (r) before the quote to print the same string that is present
inside the quotes.
Variable: It is a container where we can put our value e.g x=2

here x is variable and 2 is value x+3 5 y=3

Note:If I want to use output of previous operation so we use underscore (_) _+y 8

previous output 5 and y is 3 Use String as a variable:


Strings in python are surrounded by either single quotation marks, or double
quotation marks. -- e.g "shiva" ,'shiva' Assign String to a Variable:
Assigning a string to a variable is done with the variable name followed by an
equal sign and the string: name='shiva' name shiva Slicing String:
we can return a range of characters by using the slice syntax. Specify the start
index and the end index, separated by a colon, to return a part of the string.
Get the characters from position 2 to position 5 (not included):
name='youtube' name[2:5] 'utu' Slice From the Start: name[:5]
formstarting to index 5 (exclude) 'youtu' Slice To the End: name[2:]
#from 2nd index to end 'utube'
Negative Indexing: 0 1 2 3 4 5 6
#positive indexing y o u t u b e -7 -6 -5 -4 -3 -2 -1
#Negative indexing
name[-1] 'e' name[:-1] 'youtub'
name[:] 'youtube' name [:0] ''
name[-5:-2] 'utu'
Concatenate String:
name+ ' telusko' 'youtube telus
#1 Lists are used to store multiple items in a single variable.
- We have to use a square bracket [], and in that square bracket, we can store
multiple values. - We can print the list through the variable name.
- Lists are Mutable which means values can be changed in the list. - We can
also get the single value from the list using the index value.
- The index value is 1 less than the size of a list as the index value starts from
0. e.g., If the size of the list is 5, then its index value lies in the range of 0 to 4.
- We can fetch only those values from a list that are in the range of index
values of it.
- We can also get a sub-list of a list by using the slicing in a list.
- We can also fetch the value from a list through negative numbers similar to
strings. - A list of strings can also be created.
- We can also create a list that can store values of different data types. Like it
can store integer value, float value, string value etc, in a single list.
- A list of lists can also be created which means a list can also store different
lists in it as well.
#2 - Several operations can also be performed using it and it has many in-built
functions and methods to use
. - nums. shows all the functions that are available with the list. - Ctrl + Space
can also be used to show the methods.
- append method is used to add a new value to the end of a list. - clear will
clear the entire list. - insert method can add a value in between the list at the
specified index.
- A particular element can also be deleted through the remove method.
- pop method will also remove the element through the index value and
return that deleted element as well. - If you don't specify the index value in the
pop method, it will delete and return the last element from the list.
- del is a command through which you can delete a sub-list or multiple values
from a list. del list name[start:end]
- extend method is used to add multiple values or a sub-list in a list.
- sort method is used to get listed in the sorted order. nums.sort()
#3 - min() function is used to get the minimum value present in a list.
- max() function is used to get the maximum value of a list.
- sum() function returns the sum of all of the values present inside the list.
#1 Tuples:- Tuple is almost similar to a list in which we can store multiple
values. - Tuples are Immutable and we can change values in them.
- To define a tuple, () round brackets are used.
- We can fetch the values from a tuple using the index value that can be given
in a square bracket.
- Tuple will give an error when you tried to change a value in it.
#2 - count method is used to count the occurrences of an element in a tuple. It
counts the number of times that an element is present in a tuple. e.g., If an
element of value 5 is present two times in a tuple, then the count method
returns 2.
#3 - We can use tuples when we want a list of multiple values but we do not
want to change it. - Iteration in the tuple is faster than the list.
#4 Sets:- - Set is a collection of unique elements.
- To define the set, we use the {} curly brackets. - Set never follows the
sequence.
- When we print the set, then the sequence of values in output will be different
from the sequence of input.
- Duplicate values present in a set will be printed only once in an output.
- Set uses the concept of Hash. Hash is used to improve the performance as it
fetches the values as fast as possible.
- Indexing is not supported in sets as it does not follow sequencing.
- Values can not be changed in a set also because index value is not supported.
#1 Tuples:- Tuple is almost similar to a list in which we can store multiple
values. - Tuples are Immutable and we can change values in them.
- To define a tuple, () round brackets are used.
- We can fetch the values from a tuple using the index value that can be given
in a square bracket
. - Tuple will give an error when you tried to change a value in it.
#2 - count method is used to count the occurrences of an element in a tuple. It
counts the number of times that an element is present in a tuple. e.g., If an
element of value 5 is present two times in a tuple, then the count method
returns 2.
#3 - We can use tuples when we want a list of multiple values but we do not
want to change it.
- Iteration in the tuple is faster than the list.
#4 Sets:- - Set is a collection of unique elements.
- To define the set, we use the {} curly brackets.
- Set never follows the sequence.
- When we print the set, then the sequence of values in output will be different
from the sequence of input.
- Duplicate values present in a set will be printed only once in an output.
- Set uses the concept of Hash. Hash is used to improve the performance as it
fetches the values as fast as possible.
- Indexing is not supported in sets as it does not follow sequencing.
- Values can not be changed in a set also because index value is not supported.
#1 - Every variable has its address.
- In Python, the id() function is used to get the address of a variable.
- We can also assign the value of one variable to any other variable.
- In python, whenever you create multiple variables and if they have the same
data then they will point towards the same box or same memory area.
- Everything is an object in Python.
- Variables are also known as tags as we tag the value with a variable.
- If the same variable store multiple values, then that variable will point
towards the new memory area where the new value is get stored.
#2 - If there is any data present in the memory that is not referenced by any
variable, then that will be removed from the memory by the Garbage collector.
#3 - The value of variables can be changed but the value of the constant
remains the same.
- In python, we represent constants through capital letters.
- type() function is used to get the data type of value of a variable.
- Besides in-built data types, we can also create our own types.
i) NoneType: This is a special data type that represents the absence of a value.
It is similar to null in other languages.
ii) Numbers: These can be integers, floating-point numbers, or complex
numbers.
iii) Booleans: These are values that represent True or False.
iv) Lists: These are ordered collections of objects, enclosed in square brackets.
v) Tuples: These are similar to lists, but are immutable (i.e., their contents
cannot be changed), and are enclosed in parentheses.
vi) Sets: These are unordered collections of unique elements, enclosed in curly
braces.
vii) Strings: These are sequences of characters, enclosed in single or double
quotes.
viii) Ranges: These are immutable sequences of numbers, and are commonly
used to iterate over a sequence of numbers in a for loop.
ix) Dictionaries: These are collections of key-value pairs, enclosed in curly
braces.
i)None Type a=None type(a)
ii)Numbers int: if you want to assign a integer value to a variable a=5 type(a)
float: if you want to assign a float value to a variable num =2.5 type(num)
complex:
if you want to assign a complex value to a variable num =2+9j type(num)
# type conversion: if you want to convert one data type to another data type
a=5.6
b=int(a)
type(b)
# output :
int k=float(b)
type(k) # output : float
c=complex(4,5)
type(c
) # output : complex
iii)boolean: if you want to assign a variable with a boolean value a= True
type(a)
# output : bool bool=3 less then5 True type(bool) Sequence data types : if you
want to assign a variable with multiple values List, Tuple, Set, String, Range.
iv) List if you want to assign a variable with multiple values and you want to
change the values -- In Python, a list is a collection of ordered and mutable
elements enclosed in square brackets. Lists are one of the most commonly
used data structures in Python because of their versatility and flexibility.
lst=[25,36,45,12]
type(lst)
# output : list
v) Tuple: if you want to assign a variable with multiple values and you do not
want to change the values make immutable
-- In Python, a tuple is a collection of ordered and immutable elements
enclosed in parentheses. Tuples are similar to lists, but they cannot be
modified once they are created, which makes them useful for storing data that
should not be changed during the program's execution.
t=(25,36,45,12,7)
type(t)
# output : tuple
vi) Set: if you want to assign a variable with multiple values and you donot
want to change the values and you donot want to duplicate values
-- In Python, a set is an unordered collection of unique elements enclosed in
curly braces. Sets are useful for storing data that should not contain duplicates,
such as a list of users on a website.
s={25,36,45,12,25,36}
type(s)
# output : set
#output: {36, 12, 45, 25}
vii) String: if you want to assign sequence of characters to a variable
-- In Python, a string is a sequence of characters enclosed in single or double
quotes. Strings are immutable, which means that they cannot be modified
once they are created.
str = "hello"
type(str)
# output : str
we are not talk about char data type in python st='a' # every character is a
string in python
viii) Range: if you want to assign a variable with multiple values and you don't
want to change the values and you want to generate a sequence of numbers
-- In Python, a range is a sequence of numbers that is immutable and iterable.
Ranges are commonly used to iterate over a sequence of numbers in a for
loop.
range(10)
# range data type type(range(10))
# output : range list(range(2,10,2))
# output : [2, 4, 6, 8]
ix) Dictionary: if you want to assign a variable with multiple values and you
donot want to change the values and you want to assign a key to each value
-- In Python, a dictionary is a collection of key-value pairs enclosed in curly
braces. Dictionaries are useful for storing data that is associated with a key,
such as a list of users on a website and their corresponding email addresses.
d={1:'a',2:'b',3:'c'}
type(d) d1={'navin':'samsung','rahul':'iphone','kiran':'oneplus'}
d1.values()
# output : dict_values(['samsung', 'iphone', 'oneplus'])
d1.keys()
# output : dict_keys(['navin', 'rahul', 'kiran']) d['rahul']
#output : 'iphone' d1.get('kiran') #output : 'oneplus'
#1 - Types of operators in Python:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Unary operators
- Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication, division, etc.
- Assignment operation is performed with the help of equal to(=), in which we
can assign a value to the variable.
- We can also do the assignment by short-hand which means performing an
arithmetic operation and then assigning the value both at the same time.
- We can also assign the values in one line for two variables. a,b = 5,6 - Unary
operator takes a single operand in an expression or a statement.
- Comparison can be performed with the help of relational operators.
- Comparison operators return a boolean value or True or False.
#2 - If you want to combine two or more conditions and then check the
relation between them, then logical operators are used.
- Logical operators include And, Or and Not.
- Logical operators follow the truth table for And, Or, and Not operators.
- And the operator returns True when both conditions are true otherwise
returns False. Or the operator returns True when any of the conditions or both
the conditions are True otherwise it returns False. Not the operator reverses
the value of the output.
In programming, the number system is a way of representing numbers using
different bases.
The most commonly used number systems in programming are the decimal
(base 10), binary (base 2), octal (base 8), and hexadecimal (base 16) systems.
a)Decimal system: This is the number system we use in our everyday lives. It
uses 10 digits (0-9) to represent numbers.
b)Binary system: This system uses only two digits (0 and 1) to represent
numbers. It is commonly used in computer systems because digital devices
work with binary signals.
c)Octal system: This system uses 8 digits (0-7) to represent numbers. It's often
used in computer programming because it's a compact way to represent binary
numbers.
d)Hexadecimal system: This system uses 16 digits (0-9 and A-F) to represent
numbers. It's commonly used in computer programming and web
development to represent colors and memory addresses. Converting different
number systems:
Decimal to binary: Divide the decimal number by 2 and write down the
remainder. Keep dividing by 2 and writing down the remainders until you get
to 0 at quotient.
Then, read the remainders in reverse order to get the binary number.
e.g
51
2|51 |1
2|25 |1
2|12 |0
2|6 |0
2|3 |1
2|1 |1
|0 |1
reverse order: 110011
Binary to decimal: Multiply each digit in the binary number by the
corresponding power of 2 (starting with 2^0 on the right). Add up the results to
get the decimal number.
e.g 11011
2^4 2^3 2^2 2^1 2^0
1*16 1*8 0*4 1*2 1*1
16+8+0+2+1=27
It is Same for octal and hexadecimal(Not in this lecture but for your
knowledge)
Decimal to octal: Divide the decimal number by 8 and write down the
remainder. Keep dividing by 8 and writing down the remainders until you get
to 0. Then, read the remainders in reverse order to get the octal number.
e.g 51
8|51 |3
8|6 |6
8|0 |0
reverse order: 360
Octal to decimal: Multiply each digit in the octal number by the corresponding
power of 8 (starting with 8^0 on the right). Add up the results to get the
decimal number.
e.g 360
8^2 8^1 8^0
3*64 6*8 0*1
192+48+0=240
Decimal to hexadecimal: Divide the decimal number by 16 and write down the
remainder. If the remainder is greater than 9, replace it with the corresponding
letter (A-F). Keep dividing by 16 and writing down the remainders until you get
to 0. Then, read the remainders in reverse order to get the hexadecimal
number.
e.g 51
16|51 |3
16|3 |3
16|0 |0
reverse order: 33
Hexadecimal to decimal: Multiply each digit in the hexadecimal number by the
corresponding power of 16 (starting with 16^0 on the right). If a digit is a letter,
replace it with the corresponding value (A=10, B=11, etc.). Add up the results
to get the decimal number.
e.g 33
16^1 16^0
3*16 3*1
48+3=51
Only for Interest (Not in this lecture) Converting from octal to binary and
binary to octal can be done using a simple method. Conversion from Octal to
Binary:
To convert an octal number to binary, we can simply replace each digit in the
octal number with its equivalent three-digit binary number.
Here are the octal-to-binary conversions for each octal digit:
0 = 000
1 = 001
2 = 010
3 = 011
4 = 100
5 = 101
6 = 110
7 = 111
For example, to convert the octal number 725 to binary:
7 = 111
2 = 010
5 = 101
So, 725 in octal is equivalent to 111010101 in binary.
Conversion from Binary to Octal:
To convert a binary number to octal, you can group the binary digits into sets
of three (starting from the right) and replace each set with its equivalent octal
digit. Here are the binary-to-octal conversions for each set of three binary
digits:
000 = 0
001 = 1
010 = 2
011 = 3
100 = 4
101 = 5
110 = 6
111 = 7
For example, to convert the binary number 101011011 to octal:
101011011

533
we get 533 in octal.
Use of method in python to direclty convert number system:
Decimal to binary: bin()
e.g bin(51)
'0b110011'
# 0b represent binary formate
binary to decimal: int()
e.g
int('0b110011',2)
51
Decimal to octal: oct()
e.g
oct(51)
'0o63' # 0o represent octal formate
octal to decimal: int()
e.g
int('0o63',8)
51
Decimal to hexadecimal: hex()
e.g
hex(51)
'0x33' # 0x represent hexadecimal formate
hexadecimal to decimal: int()
e.g
int('0x33',16)
51
#1 - In bitwise operations, the integers are first converted into binary and then
operations are performed by bitwise operators on each bit or corresponding
pair of bits.
- The result is returned in decimal format by the bitwise operators. - There are
six types of binary operators:-
1. Complement (~)
2. And (&)
3. Or (|)
4. XOR (^)
5. Left Shift 6. Right Shift
#2 - Complement operator is also known as tilde(~) operator.
- Complement simply do the reverse of binary form. If a bit is 0 then it makes it
1 and vice-versa.
- Reverse of each bit of a number returns the 1's complement.
- We can store only positive numbers in our system and that's why we find the
2's complement of each negative number. 2's complement = 1's complement
+1
#3 -AND operator will return true if both the conditions are true while the OR
operator will return true if at least one condition is true.
#4 - XOR operator will return 1 or true when there is an odd number of 1 bit
present in operations and if there is an even number of 1, then it will return 0.
#5 - Leftshift operator shift bits on the left-hand side. The right-shift operator
shifts bits on the right-hand side. - Leftshift add the bits while the right-side
removes the bits.
math module in Python provides a wide range of mathematical functions.
-- math module is a built-in module in Python.
-- math module is used to perform mathematical operations.
-- math module is used to perform mathematical operations like square root,
power, floor, ceil, etc.
-- for using math module we have to import it first # import math
-- then we can use math module function like math.sqrt(25) or
-- we can use alias name like m=math then we can use m. m.sqrt(25) if we
import math as m or
-- we can import only required function like from math import sqrt,pow
sqrt(25)
pow(2,3)
Here are some of the most commonly used ones methods of math module:
math.sqrt(x): Returns the square root of x.
math.pow(x, y): Returns x raised to the power y.
math.ceil(x): Returns the smallest integer greater than or equal to x.
math.floor(x): Returns the largest integer less than or equal to x.
math.exp(x): Returns the exponential value of x.
math.log(x[, base]): Returns the natural logarithm (base e) of x or the logarithm
of x with the specified base.
math.sin(x), math.cos(x), math.tan(x): Returns the trigonometric sine, cosine,
or tangent of x, respectively.
Here are some of the most commonly used ones attributes(constant) of math
module:
math.pi: Returns the value of pi.
math.e: Returns the value of e.
math.inf: Returns a floating point positive infinity.
math.nan: Returns a floating point “not a number” (NaN) value. using help
function we can get all the information about math module help(math)
#1 How to get user input
-- Getting user input in Python is straightforward. You can use the input()
function to get input from the user. The input function takes a single
argument, which is the prompt message displayed to the user.
e.g
name = input("Please enter your name: ")
x=input("Enter first number: ");
y=input("Enter second number: ");
z=x+y; print(z);
#2 input function
-- In Python, the input() function is used to accept user input from the
command line or console. name=input("Enter your name:"); print(name);
-- In this example, the input() function prompts the user to enter their name.
Whatever the user types in response is stored in the name variable.
-- Note that the input() function always returns a string, so if we want to use
the user's input as a number, we'll need to convert it using the appropriate
type-casting function (e.g., int() for integers or float() for floating-point
numbers).
#3 Types of input data
-- The input() function always returns a string, regardless of what the user
enters. we may need to convert the input to a different data type if you want
to perform calculations or other operations on it.
e.g
x=input("Enter first number: ");
a=int(x);
the input entered by the user is converted to an integer using the int() function
in this example.
#4 when to use index value
-- If you want to get a single character from the user, we can use the input()
function and index the result.
e.g
ch=input('enter a character: ');
print(ch[0])
ch=input('enter a character: ')[0];
print(ch);
#5 eval function eval function
-- The eval() function in Python is used to evaluate an expression entered by
the user as a string. The eval() function returns the result of the expression as a
value.
e.g
x=eval(input("Enter an expression: "));
typeOf = type(x);
print(typeOf);
#6 Passing values from command line
-- sys module provides access to any command-line arguments via the sys.argv
list. we can pass arguments to a Python script from the command line using
the sys.argv list. The first argument in the list is always the name of the script
itself.
suppose we have a file named Mycode.py in file we have written code import
sys # without this line you will get error
x=sys.argv[1];
y=sys.argv[2];
z=x+y;
print(z);
in command line we have to run this file
#python3 Mycode.py 9 5
0 12
Note: Mycode is count as 0th argument
9 is count as 1st argument
5 is count as 2nd argument
#1 –
CPU has three parts:
CU (Control Unit),
ALU ( Arithmetic Logic Unit) and
MU ( Memory unit).
- MU is used to store variables and data.
- ALU has two parts:
1. AU - Arithmetic Unit ( it performs mathematical calculations)
2. LU - Logical Unit ( it makes a computer think something)
#2 If statement:
- - In programming, we have to apply conditions as per the logic of the
code. In python, conditions can be applied through the if keyword.
- Use of the if keyword specifies the flow of execution of the code.
- Based on the condition of the problem statement, if keyword helps to
decide which set of statements should be executed.
Syntax:- if (condition): statement;
- The statements of the if block will be executed only when the
condition of the if statement is true. If the condition is false then it will
skip the execution of statements present inside the if block.
- If consists of a block where you can write multiple statements. In
python, it is also known as Suite.
#2 Indentation:- - In Python, we have to follow certain indentations that
specify the conditions that are present inside a certain block.
- Indentation simply means a certain number of spaces at the beginning
of a code line. - Indentation increases the readability of the code.
#3 Else block:-
- We can also use multiple if blocks in a code.
- Multiple uses of the if block decrease the efficiency of a code as the
condition will be checked again and again in each if block.
- To make the code efficient, we use the else block.
- If the condition of the if block is true then the else block will be
skipped. And if the condition of the if block is false then the else block
will be checked and executed.
#4 Nested if and else statements:-
- Nested if and else statements are also allowed in Python.
- if statement can also be checked inside other if statement. This
conditional statement is called a nested if statement.
- In nested, the inner if condition will be checked only if the outer if
condition is true and that helps to see multiple conditions to be satisfied.
- Round brackets for putting a condition in the if statement is optional.
#5 if, elif and else statements:-
- elif stands for if-else.
- The if-elif statement is a shortcut of if..else chain.
- If the if condition s false, then the condition inside the elif will be
checked and executed.
- While using if-elif statement at the end else block is added that will be
executed when none of the above if-elif statements is true.

#1 - We can execute a statement multiple times, by using the loops.


- There are two types of a loop:
1. For loop
2. While loop
- In the while loop, we need a counter to count the number of times, a
statement can be executed.
- We also have to put a condition in a while loop to repeat a statement
until the given condition is satisfied.
- The while Loop. With the while loop, we can execute a set of statements
as long as a condition is true.
- When the condition becomes false, the line immediately after the loop
in the program is executed.
- The value of the counter will increase or decrease until the condition
gets false.
#2 - Syntax of the while loop:
- counter variable while (condition): statements; incrementation/
decrementation
- So, there must be three things in a while loop:-
1. Initialization
2. Condition
3. Increment / Decrement
- Nested while loops can also be used in Python.
- Nested while loop simply means that a loop inside another loop. #3 - To
print the values in the same, we use (end=" "). The value will not come in
the new line after using it.
- Passing the whitespace to the end parameter (end=' ') indicates that the
end character has to be identified by whitespace and not a new line.
#1 break: The break statement is used to terminate a loop prematurely
when a certain condition is met. Once the break statement is
encountered inside a loop, the loop is immediately terminated and the
program continues with the next statement after the loop.
for i in range(1, 6):
if i == 3:
break
print(i)
output:
1
2
#2 continue: The continue statement is used to skip the current iteration
of a loop and move on to the next iteration, without executing the
remaining code in the loop for the current iteration.
for i in range(1, 6):
if i == 3:
continue
print(i)
output:
1
2
4
5
#3 pass: The pass statement is a placeholder statement that is used to
indicate that no action should be taken. It is often used as a placeholder
when writing code that will be filled in later.
for i in range(1, 6):
if i == 3:
pass
else:
print(i)
output:
1
2
4
5
#1 - We can also create a blank array and can take the values for it from
the user.
- First, we have to take the length of an array from the user.
- input() function takes the value in the form of a string, so we have to
change it into an integer using int().
- We can run a loop in a range of length of an array given by the user. At
each iteration, we can take a value to be inserted in an array.
- append() is a function that is used to add a value or an element in an
array.
#2 - To search for any value in an array or to check the index number at
which the value is present, we need to increment the value of an
iterator variable in every iteration.
- When the condition of comparison gets true, we stop the loop to
iterate further and print the value of an iterator variable.
- The iterator variable will return an index number of the value, you have
searched for.
#3 - index() function can also be used to get the index number of a value
in an array.
-- If you want to work with multidimension arrays from array('i', [1,2,3],
[4,5,6]) print(arr)
# you get error -- array which are using not supporting multidimension
arrays
-- thats why you need to use numpy arrays which are supporting
multidimension arrays
-- by default numpy are not installed in python Install numpy from cmd:
-- you need to install numpy using pip install numpy
-- install using command pip install numpy in cmd(command prompt)
Install numpy in pycharm:
-- in pycharm we need use shortcut ctrl+alt+s and simply going to setting
-- and then going to project interpreter and then click on + sign and
search numpy and install it from numpy import * #importing numpy
arr=array([1,2,3,4,5,6]) print(arr)
-- Ways of creating arrays in numpy: we have 6 way of creating arrays in
numpy
a)array()
b)linspace()
c)arange()
d)logspace()
e)zeros()
f)ones()
from numpy import *
arr =array([1,2,3,4,5])
print(arr) print(arr.dtype)
# int32 arr =array([1,2,3,4,5.0])
print(arr.dtype)
# float -- automatically it will convert the data type to float
arr =array([1,2,3,4,5],float)
print(arr.dtype)
# float
-- we can also specify the data type of array
b) linspace() -- it is used to create an array with equal interval between
the elements -- syntax:
linspace(start,stop,num=50,endpoint=True,retstep=False,dtype=None)
arr=linspace(0,15,16)
# here it break the range into 16 equal parts
-- by default it will take 50 parts arr =linspace(0,15) print(arr) c) arange()
-- it is used to create an array with equal interval between the elements
-- syntax:
arange(start,stop,step,dtype=None)
arr =arange(1,15,2)
print(arr)
-- it will create an array with start value 1 and end value 15 with step size
2
arr=arange(1,15,2.5)
d) logspace() -- it is used to create an array with equal interval between
the elements in log scale
-- syntax:
logspace(start,stop,num=50,endpoint=True,base=10.0,dtype=None)
arr=logspace(1,40,5)
print(arr)
e) zeros() -- it is used to create an array with all zeros
-- syntax:
zeros(shape,dtype=float,order='C') arr= zeros(5) print(arr)
f) ones() -- it is used to create an array with all ones
-- syntax:
ones(shape,dtype=float,order='C')
arr=ones(5)
print(arr)
# if i want work with
int arr=ones(4,int)
print(arr)

#1
- We can add any value in each element of an array.
- We can also add values of two arrays.
- The addition of two arrays is known as Vectorized Operation.
- We can also find the values of each element of an array of
mathematical operations such as sin, cos, tan, log, sqrt etc.
- Sum of every element of an array can also be calculated by using the
sum() function.
- Minimum value can also be get from an array through the min()
function.
- Maximum value can be get from an array by using the max() function.
- Unique elements from an array and the sorted array can also be get.
- Concatenation of two arrays can also be performed by using the
concatenate function. This function combines two arrays.
#2
- Two variables can be pointed towards a single array. It means both
variables are pointing to the same memory address where the array is
stored.
- In Python, Aliasing happens whenever one variable's value is assigned
to another variable.
- view() is a function that helps to create a new array at a new location.
It means arrays should be present at the different memory addresses.
- By using the view() functions, two variables will point towards two
different arrays.
#3
- In python, two copying techniques are available i.e.,
1. Shallow Copy
2. Deep Copy
- In shallow copy, it will copy elements but it means both arrays are
dependent on each other.
- In shallow copy, if we update an element in one array then the changes
would also be reflected in another array.
- In a deep copy, two different arrays are not linked with each other in
any way.
- In a deep copy, we use the function known as a copy() instead of using
the view() function.
- copy() function provides a deep copy of an array.

-- formal argument
-- actual argument
Actual arguments have 4 types:
1)position
2)keyword
3)default
4)variable
length argument Position argument:
-- During a function call, values passed through arguments should be in
the order of parameters in the function definition.
This is called positional arguments.
e.g def person(name,age):
print(name)
print(age)
add(5,6)
keyword argument:
-- During a function call, values passed through arguments don’t need to
be in the order of parameters in the function definition. Keyword
arguments can achieve this.
-- All the keyword arguments should match the parameters in the
function definition.
e.g
person(age=28,name='navin')
default argument:
-- Default arguments are values that are provided while defining
functions.
-- The assignment operator = is used to assign a default value to the
argument.
-- Default arguments become optional during the function calls.
-- If we provide a value to the default arguments during function calls, it
overrides the default value.
-- The function can have any number of default arguments.
-- Default arguments should follow non-default arguments.
e.g
def person(name,age=28):
print(name)
print(age)
person('navin')
variable length argument:
-- if you want to pass multiple value in a function call we can use variable
length argument
def sum(a,*b):
print(a)
print(b)
c=a
for i in b:
c=c+i
print(c)
sum(5,6,34,78)

-- Keyword variable length argument


-- we have talk about variable length argument in previous chapter
Variable length argument :
-- A variable-length argument is a feature that allows a function to
accept an arbitrary number of arguments.
The syntax for defining a variable-length argument in Python is to use an
asterisk (*) before the parameter name.
e.g
def person(name,*data):
print(name)
print(data)
person('navin',28,9765432)
keyword variable length argument:
-- keyword variable length argument is a feature that allows a function
to accept an arbitrary number of keyword arguments.
-- use a double asterisk (**) to define a variable-length argument that
accepts keyword arguments. For example:
-- the **kwargs parameter allows the function to accept an arbitrary
number of keyword arguments. The function can then loop over the
dictionary of keyword arguments and do something with them.
e.g
def person(name,**data): #**kwargs
print(name)
for i, j in data:
print(i,j) #i is key and j is value
person('navin',aget=28,city='Mumbai',mob=9865432)

In this lectre we are discussing:


#1 Scope of variable
#2 Local variable
#3 Global variable
#4 Global keyword
#5 Global() function
#1 Scope of variable
-- scope of variable means where we can access the variable
-- there are two types of scope of variable
1. local scope
2. global scope
#2 Local variable
-- local variable means variable which is defined inside the function
-- we can access the local variable inside the function only
-- we cannot access the local variable outside the function
Local Scope:
When a variable or function is defined inside a function, it is said to be in
the local scope of that function.
Variables defined in the local scope are only accessible within that
function and are destroyed once the function completes execution.
Local variables have the highest priority in accessing over global
variables of the same name.
def func(): x = 10
print(x)
func()
-- the variable x is defined inside the function, and it can only be
accessed within the function.
#3 Global variable
-- global variable means variable which is defined outside the function
-- we can access the global variable inside the function
-- we can access the global variable outside the function
x = 10
def func():
print(x)
func()
-- the variable x is defined outside the function, and it can be accessed
within the function. #4 Global keyword
-- if we want to access the global variable inside the function and we
want to change the value of global variable inside the function then we
have to use global keyword.
x = 10
def func():
global x
x = 15
print(x)
func()
-- in this case no new variable is created inside the function, but the
global variable x is accessed and modified inside the function.
#5 Global() function
-- if we want to access the global variable inside the function and we
want to change the value of global variable inside the function then we
have to use global() function.
e.g
x = 10
def func():
x = 15
print("local x: ",x)
y = globals()['x']
print("global x: ",y)
globals()['x'] = 20
-- using globals()['x'] we can access the global variable x inside the
function and we can change the value of global variable x inside the
function.

In this lecture we will learn:


- Recursion in Python
- How to call a function inside the same function?
- How to set the limit for recursion in Python? –
Use of sys library functions
- Why recursion is useful?
#1 - Recursion means calling a function from itself.
- To print a statement of a function multiple times, we can call a function
inside the same function.
- By default, a function inside a function will execute infinite times. -
Maximum limit for recursion is 1000 in python, so it will give an error
after exceeding its limit.
- Limit can also be changed by doing some customization.
- If a code goes into recursion without a condition and it goes to infinite
times, then it may hang the system and that limit is set in python.
- We can also print the limit of recursion by using the function
getrecursionlimit() available in the sys library.
- We can change the limit for a recursion by using the setrecursionlimit()
function.
- We can set the limit to any number by providing it in the
setrecursionlimit() method.
- We have to make the variable global to access it if it is defined outside
the scope.
- Recursion is used to perform several tasks in many projects.
#2
- A complicated function can be split down into smaller sub-problems by
using the recursion.
- Recursive functions make the code look simple and effective.

You might also like