Q- how to Print Hello World
print("Hello World")
Variables in python -------
age = 30 #variable should be intutive so that we can learn any time
print(age)
Note: Shift+Enter is shortcut to run command
2) '#' this is for writing the comment in python
Rules for Variables---
- Variable can not be start with any number like - 1age
- Number can use in between and end with variable like - age1 age2
- Special characters are not allowed expect _ (underscore) like - age_my
- Space not allowed in variable
- Python is case sensitive
- Integer = age1 to age3 is basically integer , Integer is basically full number
lets check = type(age1) #it will give u print int - float= basically decimal values
Interest = 30.24
type(Interest) #answer is float - Message = Sequence of character is basically and type will be string ,Note: If we are using quote "" the it will string
Message="My Name Is Divyanshu"
type(Message) #print will str #we can use any quote 'I can use this' , "also use this" but whenever we've multiline string then will use '''triple quote''' - Boolean = 2 values are available here True and False
Like = data = False #here data is basically variable and false is data type
type(data) #give u type of data, print bool
bool
- Addition = +
num1 = 20
num2 = 37
result = num1+num2
print(result) #/another way direct: print(num1+num2), without storing data on new var - Substraction = -
num1 = 50
num2 = 20
result = num1-num2
print(result) #/another way direct: print(num1-num2), without storing data on new var - Multiplication = *
num1 = 20
num2 = 39
result = num1 * num2
print(result) #/another way direct: print(num1*num2), without storing data on new var - Integer Division = // #this is basically integer division
num1 = 20
num2 = 3
result = num1 // num2
print(result) #/another way direct: print(num1//num2), without storing data on new var
answer = 6, bcse it will not give u float value - Float Division = / #this is basically float division
num1 = 20
num2 = 3
result = num1 / num2
print(result) #/another way direct: print(num1/num2), without storing data on new var
answer = 6.66666666667 , bcse it is float division - Power = **
num1 = 2
num2 = 5
result = num1 ** num2
print(result) - Modulus = % #it will give u remainder
num1 = 20
num2 = 3
result = num1 % num2
print(result)
answer = 2 , it is remainder
- to give age1 type so we've to typecast here
- age1 = int(input())
- len(string) = basically this is for find length of the character
string = "Divyanshu Khare" #space is also count as string
len(string) #it will give u length of the string - ls = collection of item (list)
Defined by [ ] square bracket
Example: ls[1,2,3,4,5,6]
type[ls] #it will give u type of variable - max = find maximum number of list
ls[1,2,4,5,6]
max(ls)
print(max) - min = minimum number of list
ls[1,2,3,4,5,6,7]
min(ls) - sum = sum of numbers
ls[1,2,3,4,6,7,8]
sum(ls) - len(ls) = give u lenth of list
len(ls) - max(string) = it will give u maximum ASCII value's character
string = ("Divyanshu")
max(string) - min(string) = it will give u minimum ASCII value's character
string = ("Divyanshu")
min(string)
Note: ASCII is american standard value of number's in computer - sorted(ls) = it will sort list in accending order
- sorted(ls,reverse = True) = it will sort list in decending orders
- round() = it will round off
round(number,what place u want to round)
example: round(12356.54645,2)
12356.55 #it will give u this as a answer - abs() = it will give u any number as a absolute(positive Number)
abs(-23538) - f = format string
example:
name = "divyanshu"
age = 30
profession = "Data Science"
introduction = f"{name} is {age} year old professional working as {profession}"
print(introduction)
- if else
- cibil_score = int(input("Enter Cibil Score:"))
if(cibil_score>600):
print("u re eligible for loan")
else:
print("u re not eligible") - elif = when we have more than 2 conditions
color = input("Enter color - Red, Green, Yellow")
if color == "Red":
print("Stop")
elif color == "Yellow":
print("Wait")
else:
print("Go") - loops (control structure) -- repeatation of the task
exmple: string = "Data Science"
for i in string:
print(i)
example: for i in range (0,101):
print(i)
example to print square: for i in range(0,100,2) :
print(i)
example :
ls = [1,2,3,4,5,6,7,8]
for i in ls:
print(i) - while = it will run if condition is True/ Tab tk chlega jab tk condition true hai
i = 1
while i < 10:
print("Divyanshu khare")
i = i +1 - Control the loop
>> Break: it will stop all iteration once requirement finished (Stop Iteration)
ls = [1,2,3,4,5,6,7,8,9,10]
for i in ls:
if i == 6:
print("Yes")
break
>>Continue : it will stop that particular iteration only and will jump on another iteration
ls = [1,2,3,4,5,6,7,8,9,10]
for i in ls:
if i == 6:
print("Yes")
continue
>>Pass : if will do nothing, it will not break anything
ls = [1,2,3,4,5,6,7,8]
for i in ls:
if i > 0:
pass #do nothing
else:
print("Negative Number")
>>> DATA STRUCTURE IN PYTHON [this is not algorithm]
- List
- tuples
- set
- dictionary
- String operations
- Indexing = process of fetching character from the collection
- Example:
string = "String"
string[2] - Slicing = process of fetching sequence of character / process of fetching sub-string from the given string
- Example:
string = "Data Science" #lets say I want to fetch data from this string
string[start index:end index + 1] #this is index
string[0:3 + 1] - Example 2 : If i want to slicing from right to left
string = "Data Science"
string[-11: -9] - Example 3: 👉 "If I want to slice by skipping 1 character."
string = "Data Science"
string[5:12:2] - Example 4: I want to reverse print and I dont want to put first index
string = "Data Science"
string[::-1] #If I don’t enter the first index, it will start from the 0th index - In-built function for string
string = "Data"
type(string) - len(string) = length of the string
- convert string into lowercase =
- string = "DIVYANSHU"
string.lower() - convert string into uppercase =
- string = "divyanshu"
string.upper() - convert string into capitalize
- string = "divyanshu"
new_string = string.capitalize()
print(new_string) - #Ye Python ka built-in method hai jo string ke first letter ko capital (uppercase) me badal deta hai #
capitalize()se jo naya result (modified string) milta hai, wo new_string me store ho jata hai. - lstring.islower() -- it will check whether string is lowercase or uppercase
- lstring = "DivyanshuJi" #lstring is basically variable
lstring.islower() - string.isupper() --- it will check whether string is uppercase or lowercase
- ustring = "this is small"
ustring.isupper() - string.isdigit() --- it will check whether string is digit or not ?
- numstring = "435345" #this is check string is number or not
numstring.isdigit() #numstring is basically variable name of string - string.swapcase() -- it will swap the case of given string
- string = "this is small case"
string.swapcase() - string.replace("word to change", "word with change")
- string = "Data science"
string.replace("a", "d") #main data sience me 'a' word ko 'd' se change kr rha - string.split() == it will split string, ("jaha se split krna hai, by default space se krta hai")
- string = "Divyanshu@khare"
string.split("@")
- ls = [1,2,34,5,6,7,"mango"]
type(ls) #to check the data type - len(ls) == #check length of list
- ls[3] =#it will give u value of this index from length
- ls [::-1] = #reverse list
- list concatination =
ls1 = ["apple", "mango"]
ls2 = ["another"]
ls3 = ls1+ls2
print(ls3) - ls.append("apple") -= #add single element on list from end of the list
- ls.extend(["grapes", "gyan"]) = #add multiple element on the list from end
- ls.insert(index number,"element") = #it will add on specific index
- ls.index("grapes") = it will give u positive index of the element
- ls.remove("element name") = #it will remove first occurrence element wise remove, we cant remove directly all element
- ls.sort() = #sort list in accending orders
- ls.sort(reverse=True) = #sort list in descending order, it will change existing list
- sorted(ls) #it will not change existing list
- ls.pop(index number) = #it will remove element from index
- ek baar ban जाने ke baad uske elements badle nahi ja sakte
- Tuple is Immutable
- Tuple ek data structure hai — jaise list, lekin immutable hoti hai
- tuple me wo inform store krte hai jaha ham chahte hai koi bhi program intensionally ya unintensonally change na kar sake
- tuple () is bracket se define krte hai
example: tup = (3,4,6,7,8544,76,34,5)
type(tup) - max(tup) = #give u maximum value of tuple
- mix(tup) = #give u minimum value of tuple
- sum(tup) =#give u sum of tuple
- sorted(tup)
- list >> tuple >> list == typecasting list to tuple and tuple to list
tup1 = tuple(ls)
tup1 - tup.sort()
- del = #i want to remove element from list index wise
ls = [2,3,5,6,7,4]
del ls[3] #it will not return anything
file handling
>> f.read() #it will help to read or access the file
.append() Excel sheet में एक नई row add करने के लिए use होती है।import csv → CSV फाइल को पढ़ने के लिए Python का built-in मॉड्यूल है।
with open("titanic.csv", mode="r") as f: → titanic.csv फाइल को read mode में खोल रहे हैं।
csv.reader(f) → फाइल की हर लाइन को एक लिस्ट की तरह पढ़ेगा।
next(reader) → पहली row (header) को निकाल देगा ताकि वो दोबारा लूप में ना आए।
enumerate(reader) → हर पंक्ति के साथ उसका index (i) देगा।
print(i, row) → हर रिकॉर्ड को उसकी क्रम संख्या (index) के साथ प्रिंट करेगा।
>> Execption handling
Try- Except Block -
try:
result = 10/0
print("This line will not be executed bcoz of error")
except ZeroDivisionError:
print("you cant divide by zero")
Ans: yes
>>RAISE == jab exception customized raise krna hai, jo system raise nhi krega main apne requirement ke according raise krna chahta hu
def withdraw (balance, amount): if balance-amount < 1000: raise Exception("Withdrawin denied: Minimum balance of 1000 INR to be maintaned") else: remaining = balance - amount return balance-amounttry: remaining_amount=withdraw(balance=1000, amount=2000) print(f"After transaction remaining balance is {remaining_amount}")except Exception as e: print(f"Traction failed: {e}")
return ka matlab
-
Python me return ka kaam hai: function ke andar se koi value bahar bhejna
-
Matlab function calculate karke result wapas main program me deta hai
def = function define krta hai / define keyword hai
withraw = function ka naam, apne according
(Balance, amount) = is argument
Return: Function ye value bahar bhejta hai → try block me remaining_amount variable me store hoti hai
Try blockk
>>withdraw(balance=5000, amount=2000)
-
Ye function call hai.
Matlab hum withdraw function ko execute kar rahe hain aur usme:
5000 :balance
2000 : amount
- remaining_amount
- function ka return value remaining_amount variable me store ho rha hai
- Mtlb withdraw ke baad bacha hua paisa ab is variable me hai
>>Built-in Modules #math#random#datetime#os#sys
>> import math #lets say i want to get square rootmath.sqrt(34) #yaha 34 ka square nikal rhe
>>import random #module has function to generate random datarandom.random() #generate random decimal number (0-1 range tak)
random.randint(1,100)
>>from datetime import datetime #it will give u date timedatetime.now()
>>import os #files check krne ke liyeos.getcwd() #file ka path check krne ke liye
>
numpy =numerical python , numpy ke strct numeric import krke use kr skte hai
import numpy as np = #np is a shortname /np ki jgh kuch v de skte hai, np is a alias ise hamne isliye likha taaki in future jab bhi hame numpy likhna ho to pura likhne ke bajaye np likh ke hi upyog kr paye
numpy jis Data sturcture pe based hai >>>>>>>>>>>
>>Array ---------import numpy as nparr =np.array([2,3,4,5,6,]) #list input me le rha, arr is basically variable name type(arr)arr.ndim #check dimension of array, other way to check dimension , last bracket jitna hai utni dimension>> 2 / Multi Dimension Array ------arr2 = np.array([[1,2,3], [5,46,67]])arr2.ndim #arr2 is array's name and ndim will help to check dimension>> arr2.shape == #it will help us to check rows and columns of arraysarr2 = np.array([[1,2,3], [5,46,67]])arr2.ndimarr2.shape
>> arr2.size ==== it will give u no of elements of array in rows onlyarr2 = np.array([[1,2,3,5], [5,46,67,5]])arr2.ndimarr2.shapearr2.size #no of elements
>> arr2.dtype>>zeros_array = np.zeros((row_number, column_number)) import numpy as np zeros_array = np.zeros((10,4)) #it will give u float 0 according to row and column print(zeros_array)
>>ones_array = np.ones((row_number, column_number)) import numpy as np ones_array = np.ones((6,4)) #it will give u float number 1 according to row and column print(ones_array)>>full_array = np.full((row_number, colum_number, fill_value = value_number) here full_array is variable name
np.full = function name it will update full row number like 3, column number like 4
fill_value = Ye parameter batata hai ki array ke sabhi elements me kya bhara jayeExample: full_array = np.full((6,4), fill_value = 23)print(full_array)>>np.random.rand(dimension_number)example: r_array=np.random.rand(5)
np.random.rand = Ye NumPy ke random module ka function hai.Ye function 0 aur 1 ke beech random numbers generate krta hai.(dimension_number) Ye batata hai ki kitne random numbers chahiye.
>> np.round(r_array,number_round_in)example:r_array=np.random.rand(5)np.round(r_array,2)example:arr = np.arange(1,11)print(arr)
#yah NumPy का function है जो 1 से लेकर 10 तक की संख्याएँ generate करेगा। bcse end number 11 will not count
>> Indexing for single dimension arrayimport numpy as nparr = np.array([1,3,4,8,5,])arr[2] #2 is basically index of array
>> Slicing for double dimension arrayimport numpy as nparr = np.array([[1,2,3], [5,46,67]])arr[1:2] #1 = start , 2 is end #this is for single dimension
Example: this is for multidimentional array#slicing in multidimentional array, lets suppose I want to slice 2 3 5 6#arr2[start_row:end_row+1,start_column:end_column+1]arr2 = np.array([[1,2,3,4], [4,5,6,9], [7,8,9,10]])arr2[0:2,1:3]
>> Iteration ----------- just like literation in loopfor i in arr2: print(i);
>> Joining -- if I've more than 1 array than how I can merge#lets suppose ek hospital me 2 ward hai general and ICU jiske data ko jodna haigeneral = np.array([[98,43,5345], [42,45,32]])icu = np.array([[98,92,73], [89,42,52]])np.concatenate((general,icu),axis = 1) #side by side (row wise merge)
2nd Example: merge column wisegeneral = np.array([[1,2,3], [5,6,7]])np.concatenate((general,icu), axis = 0)
>> SPLITINGimport numpy as nparr = np.arange(1,11)arr #run arrnp.array_split(arr,3) #3 is basically number of split in how many part we want to split, it is function to split array, it will split array into equal part
arr2 = np.arange(1,11)arr2np.split(arr2,2) #it will work when equal divisible possible only
>>ARRAY SORTINGimport numpy as nparr = np.array([1,2,46,7,86])np.sort(arr) it will sort array, by default axis will be 0 #row_wise sorting
#coulmn_wise sorting import numpy as nparr = np.array([[1,2,46,7,86], [32,4324,543,4324,4324]]) np.sort(arr, axis = 1)arr
>> Searching = import numpy as nparr3 = np.array([1,2,46,7,86]) np.where(arr3>40) #stands for conditional search, it will give u index of that value which is greater than 40
>> np.nonzero(arr) = i will return index of that value whereable u've non zero , basically it will not give u 0 number's indeximport numpy as nparr = np.arange(1,11)np.nonzero(arr)
>>Filteration = how to filter the dataimport numpy as nparr = np.array([13,5,64,10,78,10])arr[arr>7] #it will return element which is greater than 7
>>Mathematical Operations in Numpy
x=np.array([[2,4], [6,10]])y = np.array([[12,23], [34,8]])x+y #======= it will add x +y
>> x//y = integer divisionx=np.array([[2,4], [6,10]])y = np.array([[12,23], [34,8]])x//y #======= it will divide x by y
>> np.divide(x,y) = float divisionimport numpy as npx=np.array([[2,4], [6,10]])y = np.array([[12,23], [34,8]])np.divide(x,y) #=it will give u float division
>> np.multiply(x,y) #it will multiply
>>matrix = rows multiply by column #condition ye hai = number of column of first array should be equal to the number of second arrayarr1 = np.array([[2,4],[1,3]]) arr2 = np.array([[3,6],[7,3]]) np.matmul(x,y) # matmul is function for matrix multiplication, (2×3) + (4×7) = 6 + 28 = 34
>>reshape array = #array can be reshape if size before and after reshaping are sameExample: lets suppose I have 14 dimension array, I want to make two dimension array (2,7) but (2,8) isme ham nhi kar skte arr = np.arange(1,15)print(arr)reshape_array= arr.reshape(2,7) # this is function and shape is 2 and 7, reshape_array this is variable where I'm storing reshaped arrayWhy? Two change dimension --- one dimension to 2 dimension
>>another way to reshapereshape_array= arr.reshape(2,-1) #basically -1 is only a placeholder it will calculate automatically #automatic dimension calculator
>>another way to reshape = from 3 dimension to 1 dimensionreshape_array = arr.reshape(-1) #पूरे array को एक single dimension (1D array) में convert कर दो। , -1 is basically placeholder and arguments
>>Mathematical Operations1)temp = np.array([23,32,35,54,54])print(temp)np.mean(temp) #calculate avg
2) np.min(temp) #find minimum(3)np.std(temp) #standard deviation means array के values औसत (mean) से कितना दूर या फैले हुए हैं।
4)np.percentile(temp,40) #to find percentage5)np.sum(temp) #to sum6) np.median(temp) #to find like beech ka number7)np.prod(temp) #product of all elements product (गुणा)
Comments
Post a Comment