Click here to view and download handwritten notes
Click here to view and download notes given by Professor
1) Function¶
A) Defining and Calling a function¶
In [3]:
def sum(): #defining a function i.e "sum" is a name where we used ():
print(232+23)
sum() # calling a function
255
B) Returning Results¶
In Python, functions can return values using the return statement. The return statement is used to exit a function and return a value to the caller. Here's a basic example:¶
In [11]:
def sqare(a):
return a**2
x=sqare(5)
print(x)
25
C) Returning Multiple values¶
In Python, you can return multiple values from a function by separating them with commas.¶
In this example, the num function returns three values (x, y, and z). When the function is called, these values are packed into a tuple and returned. The caller then unpacks the tuple into individual variables (x_value, y_value, and z_value) for further use.¶
In [15]:
def num():
x=12
y=23
z=33
return x,y,z
sa=num()
x_value,y_value,z_value=sa
print("x:",x_value)
print("y:",y_value)
print("z:",z_value)
x: 12 y: 23 z: 33
D) Built-in Functions¶
The Python built-in functions are defined as the functions whose functionality is pre-defined in Python.¶
a) abs() Returns the absolute value of a number¶
In [16]:
x=-12
y=23
print(abs(x)) #use of abs() function
print(abs(y))
12 23
b) int(),float(),str()¶
In [21]:
x=23.2
print(int(x)) #int() are used to convert the float into integers
y=23
print(float(y)) #float() are used to convert the integers into float
z=123
print(str(z)) #str() are used to convert the integers into string
23 23.0 123
In [24]:
pow(2,3) #its look like 2^3,pow(base:2, exp:3, mod=None)
Out[24]:
8
In [26]:
x=122,32
print(min(x))
print(max(x))
32 122
In [31]:
x=3.1415893
print(round(x))
print(round(x,3)) #round(number:x, ndigits=None:3)
3 3.142
In [40]:
x=5
y=2
print(x/y)
print(divmod(x,y)) #return (2,1) where 2 is quotient and 1 is remainder
2.5 (2, 1)
In [45]:
x=122
print("it was a binary version of 122:",bin(x))
print("it was a octal of 122:",oct(x))
print("it was a hexadecimal of 122:",hex(x))
it was a binary version of 122: 0b1111010 it was a octal of 122: 0o172 it was a hexadecimal of 122: 0x7a
In [43]:
y=122
print("its was the memory add:",id(y))
its was the memory add: 140734928705752
In [47]:
y="A"
print("the unicode code point of 'A' is:",ord(y))
the unicode code point of 'A' is: 65
In [48]:
x=["sahil","sahani",232,233]
print(len(x))
4
In [60]:
sum=([1,2,3,4,5]) #returns 15
In [64]:
help(print)
Help on built-in function print in module builtins: print(*args, sep=' ', end='\n', file=None, flush=False) Prints the values to a stream, or to sys.stdout by default. sep string inserted between values, default a space. end string appended after the last value, default a newline. file a file-like object (stream); defaults to the current sys.stdout. flush whether to forcibly flush the stream.
In [63]:
help(len)
Help on built-in function len in module builtins: len(obj, /) Return the number of items in a container.
E) Parameters and Arguments¶
In [67]:
def add_numbers(x, y): # 'x' and 'y' are parameters
result = x + y
return result
result = add_numbers(3, 5) # '3' and '5' are arguments
print(result)
8
F) Recursive Function¶
The term Recursion can be defined as the process of defining something in terms of itself. In simple words, it is a process in which a function calls itself directly or indirectly.¶
In [5]:
add=lambda x,y,z:x*y+z**2 #syntax: lambda arguments: expression
add(2,4,5)
Out[5]:
33
In [2]:
sub=lambda x,y=20: x-y
sub(5)
Out[2]:
-15
In [3]:
add=lambda x,y=10:x+y
add(10,20)
Out[3]:
30
In [4]:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
2) Operators¶
In [2]:
x=20
y=10
print(x+y) #addition between two operends
print(x-y) #subtract the second operand from the first operand.
print(x*y) #multiply one operand with the other.
print(x/y) #It returns the quotient after dividing the first operand by the second operand.
print(x%y) #It returns the reminder after dividing the first operand by the second operand.
30 10 200 2.0 0
In [4]:
x=10
x+=20 #It increases the value of the left operand by the value of the right operand and assigns the modified value back to left operand.
y=10
y=y+20 #same as y+=20
print(x)
print(y)
30 30
In [5]:
#-=(minus equal to)
x=20
x-=5
print(x)
15
In [6]:
#*=(multiple equal to)
x=5
x*=5
print(x)
25
In [7]:
#/=(divide equal to)
x=5
x/=2
print(x)
2.5
In [8]:
#%= (remainder equal to)
x=20
x%=10
print(x)
0
In [11]:
#Negation (-): Negates the value of the operand.
x = 5
y = -x # y is now -5
print(y)
#Identity (+): Used to indicate a positive value. It doesn't actually change the value of the operand.
x = 5
y = +x # y is still 5
print(y)
-5 5
In [12]:
#Equal to (==): Checks if two operands are equal
x=67
y=67
print(x==y) #True because both operends are equal
z=67
u=66
print(z==u) #False because both are not equal to each other.
True False
In [14]:
#Not equal to (!=): Checks if two operands are not equal.
x=10
y=20
print(x!=y) #True, both are not equal to each other
z=10
u=10
print(z!=u) #False, both are equal to each other
True False
In [15]:
#Greater than (>): Checks if the left operand is greater than the right operand.
x=10
y=5
print(x>y) #True,10 is greater then 5
z=5
u=10
print(z>u) #False, 5 is not greater then 10
True False
In [16]:
#Less than (<): Checks if the left operand is less than the right operand.
x=5
y=10
print(x<y) #True, 5 is smaller then 10
z=10
u=5
print(z<u) #False, 10 is not smaller then 5
True False
In [19]:
#Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right operand.
x=10
y=10
print(x>=y) #True, 10 is greater than or equal to 10
z=20
u=15
print(z>=u)
True True
In [20]:
#Less than or equal to (<=): Checks if the left operand is less than or equal to the right operand.
x = 5
y = 7
print(x <= y) # result is True
True
In [21]:
# Logical AND (and):
#Returns True if both operands are true.
#Returns False if at least one operand is false.
x=5
print(x>2 and x<10) #True
y=5
print(x>10 and x<20) #False
True False
In [22]:
#Logical OR (or):
# Returns True if at least one operand is true.
# Returns False if both operands are false
x=5
print(x>3 or x<2) #True
y=5
print(x>10 or x<2) #False
True False
In [24]:
#Logical NOT (not):
# Returns True if the operand is false.
# Returns False if the operand is true.
x=5
print(not(x>2 and x<10))
y=5
print(not(x>3 or x<2)) # as per 'or' operator is True but when we used 'not' is shows the opposite and same for 'and' operator
False False
In [27]:
#Performs a bitwise AND operation.
x=10
y=8
print("in the form of binary:",bin(x&y),"and","in the form of int:",x&y)
in the form of binary: 0b1000 and in the form of int: 8
In [28]:
#Performs a bitwise OR operation.
x=10
y=8
print("in the form of binary:",bin(x|y),"and","in the form of int:",x|y)
in the form of binary: 0b1010 and in the form of int: 10
In [29]:
#Performs a bitwise exclusive OR (XOR) operation.
x=10
y=8
print("in the form of binary:",bin(x^y),"and","in the form of int:",x^y)
in the form of binary: 0b10 and in the form of int: 2
In [31]:
#Inverts the bits of a number.(Bitwise NOT (~))
x=10
print("in the form of bin:",bin(~x),"and","in the form of int:",~x)
# ~x = -x -1
# ~10 = -10 -1
# = -11
in the form of bin: -0b1011 and in the form of int: -11
In [35]:
#Left Shift (<<):Shifts the bits of a number to the left by a specified number of positions.
x=10
print(bin(10))
print("in the form of bin:",bin(x<<2),"and","in the form of int:",x<<2)
0b1010 in the form of bin: 0b101000 and in the form of int: 40
In [36]:
#Right Shift (>>):Shifts the bits of a number to the right by a specified number of positions.
x=10
print("in the form of bin:",bin(x>>2),"and","in the form of int:",x>>2)
in the form of bin: 0b10 and in the form of int: 2
In [39]:
#in operator:
# Returns True if a value is found in the sequence.
# Returns False otherwise
x=["sahil","sahani","vicky"]
print("sahil" in x) #True
print("apple" in x) #False
#not in operator:
# Returns True if a value is not found in the sequence.
# Returns False if the value is found.
print("apple" not in x) #True
print("sahil" not in x) #False
True False True False
In [42]:
x=["apple","banana","cherry"]
if "apple" in x:
print("Yes, apple is there")
if "orange" not in x:
print("no orange found")
Yes, apple is there no orange found
In [43]:
#Returns True if the operands are the same object.
#Returns False if the operands are different objects.
x = [1, 2, 3]
y = [1, 2, 3]
z = x
print(x is y) # False, because x and y are different objects
print(x is z) # True, because x and z refer to the same object
False True
In [44]:
# Returns True if the operands are different objects.
# Returns False if the operands are the same object.
a = "hello"
b = "world"
c = "hello"
print(a is not b) # True, because a and b are different objects
print(a is not c) # False, because a and c refer to the same object
True False
I) Precedence of Operators¶
J) Associativity of Operators¶
np.array(iterable): Create an array from a list or other iterable.¶
np.zeros(shape): Create an array of zeros with the specified shape.¶
np.ones(shape): Create an array of ones with the specified shape.¶
np.arange(start, stop, step): Create an array with evenly spaced values within a given range.¶
np.linspace(start, stop, num): Create an array with evenly spaced values over a specified range.¶
In [54]:
#python program to demonstrate
#arrays
#creating an array cantaining int data type
import numpy as np
arr1=np.array([1,2,4,5,6])
print("int data type:",arr1)
#array cantaining string data type
arr2=np.array(["sahil","sahani","boy"])
print("str data type:",arr2)
#arry containing float data type
arr3=np.array([12.3,23.3,2.33,3.3])
print("float data type:",arr3)
#Boolen data type
arr4= np.array([True,False])
print("Boolen data type:",arr4)
type(arr1)
int data type: [1 2 4 5 6] str data type: ['sahil' 'sahani' 'boy'] float data type: [12.3 23.3 2.33 3.3 ] Boolen data type: [ True False]
Out[54]:
numpy.ndarray
A) Indexing and Slicing¶
In [55]:
import numpy as np
arr1=np.array([1,3,4,6,7])
print(arr1[2]) #indexing
4
In [57]:
#advanced indexing
import numpy as np
arr2=np.array([23,45,65,67,23,55])
print(arr2[arr2>50])
[65 67 55]
In [69]:
#slicing = sequence[start:stop:step]
import numpy as np
arr3=np.arange(21)
print(arr3)
print(arr3[10:20]) #start(10):stop(20)
print(arr3[10:20:2]) #start(10):stop(20):steps(2)
print(arr3[::-1])
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20] [10 11 12 13 14 15 16 17 18 19] [10 12 14 16 18] [20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0]
B) Mathmatical operation¶
In [72]:
import numpy as np
arr_1=np.array([1,2,3,4])
arr_2=np.array([2,4,6,4])
print(arr_1+arr_2) #addition
print(arr_1-arr_2) #subtruction
print(arr_1*arr_2) #multiplication
print(arr_1/arr_2) #divison
[3 6 9 8] [-1 -2 -3 0] [ 2 8 18 16] [0.5 0.5 0.5 1. ]
In [78]:
import numpy as np
a=np.array([12,34,55,33])
b=a #aliasing a as b
print(a,"memory add:",id(a))
print(b,"memory add:",id(b))
[12 34 55 33] memory add: 2477936679536 [12 34 55 33] memory add: 2477936679536
D) Attributes of an array¶
In [77]:
# ndim attributes
import numpy as np
arry=np.array([[12,23,23,22],[22,23,23,21]])
print("its show the dimensions of array:",arry.ndim)
#This array attribute returns the number of array dimensions.
print("its shows the shape of array:",arry.shape) # its shows the rows and colums
print("its shows the size of array:",arry.size)
#The total number of elements of the array.
print("its shows the data type of array:",arry.dtype)
#An object describing the data type of the elements in the array.
its show the dimensions of array: 2 its shows the shape of array: (2, 4) its shows the size of array: 8 its shows the data type of array: int32
4) Strings¶
In Python, a string is a sequence of characters enclosed within either single quotes (') or double quotes ("). Strings are used to represent text data and are one of the fundamental data types in Python¶
In Python, strings are immutable, meaning that their values cannot be changed after they are created.¶
In [80]:
#creating an string
str1="hello world"
print(str1[0]) #indexing
print(str1[0:10:2]) #slicing
print(str1[::-1])
h hlowr dlrow olleh
In [81]:
print("hello" in str1) #checking the membership
True
In [82]:
print("sahi" not in str1) # True,because sahi is not there
True
A) Functions¶
In [88]:
# lower() function
# Converts a string to lowercase.
str2="SAHIL SAHANI"
x=str2.lower()
print(x)
sahil sahani
In [89]:
#upper()function
# Converts a string to uppercase.
str3="sahil sahani"
x=str3.upper()
print(x)
SAHIL SAHANI
In [95]:
# Checks whether a string starts with a particular substring.
str4="i am a boy"
x=str4.startswith("i")
print(x)
True
In [96]:
# Checks whether a string ends with a particular substring.
str4.endswith("boy")
Out[96]:
True
In [97]:
# Checks whether all characters in a string are lowercase.
str4.islower()
Out[97]:
True
In [98]:
# Checks whether all characters in a string are uppercase.
str2.isupper()
Out[98]:
True
In [99]:
# Returns the length of a string.
len(str4)
Out[99]:
10
In [100]:
# Converts the first character of a string to uppercase and the rest to lowercase.
str4.capitalize()
Out[100]:
'I am a boy'
In [103]:
# checks whether a string consists only of alphabetic characters.
str5="sahil"
str5.isalpha()
Out[103]:
True
In [110]:
# Checks whether a string consists only of alphanumeric characters.
str6="sahil9423"
str6.isalnum()
Out[110]:
True
In [111]:
# Checks whether a string consists only of digits.
str7="1223324"
str7.isdigit()
Out[111]:
True
In [119]:
# Splitting a sentence into words
sentence = "Python is a versatile programming language"
words = sentence.split()
print("Words:", words)
# Splitting a CSV string into a list of values
csv_data = "apple,orange,banana"
fruits = csv_data.split(",")
print("Fruits:", fruits)
Words: ['Python', 'is', 'a', 'versatile', 'programming', 'language'] Fruits: ['apple', 'orange', 'banana']
In [120]:
# Joining a list of words into a sentence
words = ['Python', 'is', 'awesome']
sentence = ' '.join(words)
print("Sentence:", sentence)
# Joining a list of values into a CSV string
fruits = ['apple', 'orange', 'banana']
csv_data = '*'.join(fruits)
print("CSV Data:", csv_data)
Sentence: Python is awesome CSV Data: apple*orange*banana
B) Repeating and Concatenation of string¶
In [121]:
# Repeating Strings:
## You can use the multiplication operator (*) to repeat a string a certain number of times.
# Repeat a string
original_string = "Hello"
repeated_string = original_string * 3
print("Repeated String:", repeated_string)
Repeated String: HelloHelloHello
In [122]:
# Concatenating Strings:
## Concatenation is the process of combining two or more strings into a single string. You can use the + operator for concatenation.
# Concatenate strings
string1 = "Hello"
string2 = "World"
concatenated_string = string1 + " " + string2
print("Concatenated String:", concatenated_string)
Concatenated String: Hello World
C) Comparing the strings¶
In [1]:
# Equality (== operator):
str1 = "hello"
str2 = "world"
if str1 == str2:
print("Strings are equal")
else:
print("Strings are not equal")
Strings are not equal
In [2]:
# Inequality (!= operator):
str1 = "hello"
str2 = "world"
if str1 != str2:
print("Strings are not equal")
else:
print("Strings are equal")
Strings are not equal
In [3]:
# Case-insensitive comparison:
str1 = "Hello"
str2 = "hello"
if str1.lower() == str2.lower():
print("Case-insensitive comparison: Strings are equal")
else:
print("Case-insensitive comparison: Strings are not equal")
Case-insensitive comparison: Strings are equal
In [4]:
# String comparison using >, <, >=, and <=:
str1 = "apple"
str2 = "banana"
if str1 < str2:
print("str1 comes before str2")
elif str1 > str2:
print("str1 comes after str2")
else:
print("str1 and str2 are equal")
str1 comes before str2
In [5]:
# Substring check:
main_str = "Hello, world!"
sub_str = "world"
if sub_str in main_str:
print("Substring found")
else:
print("Substring not found")
Substring found
D) Removing space¶
In [42]:
# Using replace() method:
original_string = "Hello World"
no_spaces = original_string.replace(" ", "") #original_string.replace(old, new, count=-1, /)
print(no_spaces)
HelloWorld
In [7]:
# Using join() and split() methods:
original_string = "Hello World"
no_spaces = ''.join(original_string.split())
print(no_spaces)
HelloWorld
E) Find substrings¶
In [8]:
#Using in keyword:
main_string = "Hello, world!"
sub_string = "world"
if sub_string in main_string:
print("Substring found")
else:
print("Substring not found")
Substring found
F) Counting substrings¶
In [9]:
# Using count() method:
# The count() method can be used to count the occurrences of a substring within a string.
main_str="sahani,sahil,sahani"
sub_str="sahani"
count=main_str.count(sub_str)
print(count)
2
G) Changing Case¶
In [10]:
# Lowercase (lower() method):
original_string = "Hello World"
lowercase_string = original_string.lower()
print(lowercase_string)
hello world
In [11]:
# Uppercase (upper() method):
original_string = "Hello World"
uppercase_string = original_string.upper()
print(uppercase_string)
HELLO WORLD
In [12]:
# Title case (title() method):
original_string = "hello world"
title_case_string = original_string.title()
print(title_case_string)
Hello World
In [14]:
# Swap case (swapcase() method):
original_string = "Hello World"
swapped_case_string = original_string.swapcase()
print(swapped_case_string)
hELLO wORLD
In [15]:
# Capitalize (capitalize() method):
original_string = "hello world"
capitalized_string = original_string.capitalize()
print(capitalized_string)
Hello world
Keep in mind that these methods return a new string with the case changed, and the original string remains unchanged. If you want to modify the original string in place, you would need to reassign the result to the original variable.¶
In [17]:
original_string = "Hello World"
original_string = original_string.lower() # Modify original string in place
print(original_string)
print("after appling lower()",original_string)
hello world after appling lower() hello world
H) Checking Starting and Ending¶
In [18]:
main_string = "Hello, world!"
prefix = "Hello"
if main_string.startswith(prefix):
print(f"The string starts with '{prefix}'.")
else:
print(f"The string does not start with '{prefix}'.")
The string starts with 'Hello'.
In [19]:
main_string = "Hello, world!"
suffix = "world!"
if main_string.endswith(suffix):
print(f"The string ends with '{suffix}'.")
else:
print(f"The string does not end with '{suffix}'.")
The string ends with 'world!'.
I) Sorting and Searching in strings¶
In [20]:
# Sorting Characters in a String:
# Using sorted() function:
original_string = "hello world"
sorted_string = ''.join(sorted(original_string))
print(sorted_string)
dehllloorw
In [21]:
# Searching for Substring in a String:
main_string = "Hello, world!"
substring = "world"
if substring in main_string:
print("Substring found")
else:
print("Substring not found")
Substring found
J) Formatting the strings¶
In [22]:
# You can concatenate strings using the + operator.
name = "John"
age = 25
# Using string concatenation
formatted_string = "My name is " + name + " and I am " + str(age) + " years old."
print(formatted_string)
My name is John and I am 25 years old.
In [23]:
# You can use the format() method to insert values into a string
name = "John"
age = 25
# Using format()
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
My name is John and I am 25 years old.
In [24]:
# you can also use f-strings for string interpolation:
# Using f-strings (Python 3.6 and later)
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
My name is John and I am 25 years old.
K) working with strings¶
In [27]:
# Creating Strings:
# Single and double quotes can be used to create strings
string1 = 'Hello, world!'
string2 = "Python is great!"
# Triple quotes are used for multiline strings
multiline_string = """This is a
multiline string."""
print(string1)
print(string2)
print(multiline_string)
Hello, world! Python is great! This is a multiline string.
In [28]:
# String Concatenation:
str1 = "Hello"
str2 = "World"
result = str1 + ", " + str2
print(result)
Hello, World
In [29]:
# String Slicing
original_string = "Hello, world!"
substring = original_string[7:12] # Extracting a substring
print(substring)
world
In [30]:
# String Length:
length = len("Hello, world!")
print(length)
13
In [31]:
# String Methods:
text = " Python Programming "
trimmed_text = text.strip() # Remove leading and trailing whitespaces
lowercase_text = text.lower()
uppercase_text = text.upper()
capitalized_text = text.capitalize()
print(trimmed_text)
print(lowercase_text)
print(uppercase_text)
print(capitalized_text)
Python Programming python programming PYTHON PROGRAMMING python programming
In [32]:
# String Formatting:
name = "John"
age = 25
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
My name is John and I am 25 years old.
In [33]:
# Searching in Strings:
main_string = "Hello, world!"
substring = "world"
if substring in main_string:
print("Substring found")
else:
print("Substring not found")
Substring found
In [40]:
# String Splitting and Joining:
csv_data = "John,Doe,25"
split_data = csv_data.split(',')
print(split_data)
list_of_strings = ['Hello', 'World']
joined_string = ' '.join(list_of_strings)
print(joined_string)
['John', 'Doe', '25'] Hello World
In [41]:
# String Repetition:
repeated_string = "abc" * 3
print(repeated_string)
abcabcabc
In [ ]: