Python introduction and features


Python के सृजनकर्ता(creator) Guido van Rossum है। यह general purpose, हाई लेवल, डायनामिक, interpreted व objected oriented programming language है जो की 1991 में release की गयी।

Python से क्या किया जा सकता है?

Python का उपयोग कर निम्न applications develop किये जा सकते है।
  1. Software development
  2. Web development

Python Features

  1. Python cross platform सपोर्ट करता है याने इसका उपयोग अलग अलग operating system पर किया जा सकता है जैसे Windows, Linux, Mac OS इत्यादि।
  2. Object Oriented होने के कारण जिन्होंने c++, java, .NET सीखा हुए है वो Python बहुत आसानी से सीख सखते है।
  3. Python open source है इसका मतलब ये free है उपयोग करने के लिए।
  4. यह interpreted language होने के कारण rapid application development में उपयोग किया जाता है।

Download Python

आप python को python की official वेबसाइट से डाउनलोड कर उपयोग कर सकते है। यह फ्री है उपयोग के लिए।
Python Download link: https://python.org

Hello world python example

print("Hello World")

Python versions list and release date

Python 3.8.014 October 2019
Python 3.7.48 July 2019
Python 3.727 June 2018
Python 3.623 December 2016
Python 3.513 September 2015
Python 3.416 March 2014
Python 3.329 September 2012
Python 3.220 February 2011
Python 3.127 June 2009
Python 3.03 December 2008
Python 2.73 July 2010
Python 2.61 October 2008
Python 2.519 September 2006
Python 2.430 November 2004
Python 2.329 July 2003
Python 2.221 December 2001
Python 2.115 April 2001
Python 2.016 October 2000
Python 1.65 September 2000
Python 1.531 December 1997
Python 1.425 October 1996
Python 1.312 October 1995
Python 1.210 April 1995
Python 1.0January 1994
Python 0.9.020 February 1991





Python download and install steps


Python को डाउनलोड करने के लिए python की official website https://www.python.org/downloads/ में जाकर सीधे डाउनलोड कर सकते है या फिर google.com में “Python download” लिखकर google करे और search results में python की official website से डाउनलोड करें।




Python_download
Python की website open होने पर आपको yellow color में button दिखेगा जो भी latest version होगा वो डिस्प्ले होगा, उस पर click करने से डाउनलोड start हो जायेगा।




Python official website
डाउनलोड कम्पलीट होने पर file पे double click कर open करने से installation start हो जायेगा, थोड़ी ही देर में installation complete होने पर installation successful का message दिखेगा।
Start menu के search में python type करने पर आपको python और उसके साथ अन्य जो install हुआ है वो लिस्ट करेगा search results में, आप उसमे IDLE editor दिखेगा और python shell देखेगा। IDLE editor का यूज़ कर python के प्रोग्राम डेवेलोप कर सकते है।

Python comments

# symbol से Python में comments दिए जाते है।
Comments का उपयोग code को समझाने के लिए किया जाता है के कौन सा कोड किस कार्य के लिए लिखा गया है ।

Single line comment

# use hash/pound for comment


print('single line comment example')  #comment can be written this way also

Multiline comment

#multiline
#comment
#example

print('multiline comment example')

Python Keywords





keywords reserved words होते है जिनके मायने पहले से निर्धारित होते है निर्धारित operations के लिए, इनको variable के नाम जैसे उपयोग नहीं किया जा सकता है। Python में निम्न keywords उपलब्ध है।
andasassetbreakclass
continuedefdelelifexpect
forfromifimportin
islamdanonlocalorglobal
passraisenotnonetry
truefalsefinallyreturnelse

Python Variables





Variables का उपयोग कर python में data को store या hold किया जाता है। Python में variables को declare किये बिना ही उपयोग किया जा सकता है।
age = 20

variable के नाम रखने के नियम





  1. variable का नाम underscore या letter से शरू होना चाहिए।
  2. variable का नाम नंबर से शरू नहीं कर सकते है।
  3. case sensitive होते है variable के नाम python में।
  4. variable के नाम में alpha-numeric characters व underscore ही उपयोग किये जा सकते है।

Assign value to variable





age = 25
name = "Microsoft"
PI = 3.14 

Print/Output variable valueage = 25





name = "Microsoft"
PI = 3.14 

print(age)
print(name)
print(PI)

Python numbers





Python तीन तरह के numbers सपोर्ट करता है।
  1. int
  2. float
  3. complex

Examplea = 100 # int





b = 21.8   # float 
c = 12j    # complex number
अगर आप type जानना चाहते है तो type() function का उपयोग कर सकते है।
a = 100    # int
b = 21.8   # float 
c = 12j    # complex number

print(type(a))
print(type(b))
print(type(c))

Python strings





string character का sequence होते है इसमें letter, numbers व special symbol उपयोग किया जा सकते है। Python में string को double quotes व single quotes दोनों में रखा जा सकता है।
Python में string bytes का array है।

Example





print("Hello World")  # string in double quote
print('Hello World')  # string in single quote
ऊपर दिए हुए example में देख सकते है के एक string को double quote व दूसरे string को single quote में रखा गया है दोनों उपयोग valid है python में।

Multiline Strings





Multiline string के लिए तीन double quotes का उपयोग करना होता है python में।
a = """Hello world
How are you....."""
print(a)

Access single character form stringचूँकि string character का array है इसलिए हर एक character को index का उपयोग कर access किया जा सकता है।





str_hello = "Hello world";
print(str_hello[0]);

Python casting





Variable में Data के type को किसी और data type में बदलने को casting या type casting कहते है और python में ये आसानी से किया जा सकता है निम्न का उपयोग करकर।
  1. int()
  2. float()
  3. str()

1) int()





दिए हुए नंबर (चाहे वो whole number हो या floating number) को integer में convert करता है।

Example





a = int(23.4) #outputs 23
b = int('232') #outputs 232

2) float()





float() का उपयोग कर number को float में convert कर सकते है।

Example





a = float(23) #outputs 23.00
b = int('232.22') #outputs 232.22

3) str()दिए हुए नंबर float values को string में convert करने के लिए।





s - str("22.12") #outputs 22.12
t = str("hello 1234") #outputs hello 1234

Python Scope





Variable का scope बताता है के variable को प्रोग्राम में कहाँ उपयोग किया जा सकता है इसी के आधार पर यह निम्न है।
  1. Local scope
  2. Global scope

Local scope





variable को जब function के अंदर क्रिएट किया जाता है तो वह variable उसी function के अंदर उपयोग किया जा सकता है उसके बहार नहीं इसी को local scope कहते है।
def sum():
  a = 300   #variable with local scope 
  print(a)

sum()

Global scopeजब variable को प्रोग्राम में function के बहार क्रिएट किया जाते है और यह variables पूरे प्रोग्राम में कही भी उपयोग किये जा सकते है, ऐसे variables को Global variables कहते है।





gb = 200  #variable with global scope 
def sum():
  a = gb   
  print(a)

sum()

Comments are closed.

Python operators





Operators का उपयोग कर variable(operands) की value को manipulate किया जा सकता है, Python में निम्न operators उपलब्ध है।
  1. Arithmetic operators
  2. Assignment operators
  3. Logical operators
  4. Comparison operators
  5. Identity operators
  6. Bitwise operators
  7. Membership operators

1) Arithmetic operators





+variables में नंबर्स को जोड़ने के लिए
variables में नंबर्स को घटाने के लिए
*variables में नंबर्स को गुणा के लिए
/variables में नंबर्स को भाग के लिए
%variables में नंबर्स को में भाग के बाद शेष के लिए
**Exponent निकलने के लिए।
//Floor division के लिए।

2) Assignment Operators





=variable में value assign करने के लिए।
(Right hand side की value left hand side assign होती है)
+=variable की वैल्यू में right हैंड साइड की वैल्यू ऐड करता है।
x += 15 इसका मतलब x = x + 15
-=variable की वैल्यू में right हैंड साइड की वैल्यू subtract करता है।
x -= 15 इसका मतलब x = x – 15
*=variable की वैल्यू में right हैंड साइड की वैल्यू multiply करता है।
x *= 15 इसका मतलब x = x * 15
/=variable की वैल्यू को right हैंड साइड की वैल्यू से divide करता है।
x /= 15 इसका मतलब x = x / 15
%=variable की वैल्यू को right हैंड साइड की वैल्यू से divide कर
शेष(remainder) return करता है।
//=variable की वैल्यू को right हैंड साइड की वैल्यू से floor division करता है।
x //= 15 इसका मतलब x = x // 15
**=exponential calculation variable पर परफॉर्म
कर left hand side के variable में value assign करता है।
x**=20 इसका मतलब x = x ** 15

3) Comparison operator





==दो operands की वैल्यू check करता है के बराबर है के नहीं
अगर बराबर है तो true return करता है नहीं तो false
!=दो operands की वैल्यू check करता है के बराबर है के नहीं
अगर बराबर नहीं है तो true return करता है नहीं तो false
<>true return करता है अगर बराबर नहीं है।
<अगर एक operand की वैल्यू दूसरे से छोटी है
तो true return करता है।
>अगर एक operand की वैल्यू दूसरे से बड़ी है तो true return करता है।
<=अगर एक operand की वैल्यू दूसरे से छोटी और बराबर है
तो true return करता है।
>=अगर एक operand की वैल्यू दूसरे से बड़ी और बराबर है
तो true return करता है।

4) Logical operators





andयह Logical AND operator है इसमें अगर दोनों statements
true है तो condition true होती है।
orयह Logical और operator है इसमें अगर दोनों statement
में से किसी एक statement true है तो condition true होती है।
notअगर इसमें operand true है तब condition False होगी।

5) Identity operators





isअगर दोनों variables एक ही object है
तो यह true return करेगा।
isnotअगर दोनों variables एक ही object
के नहीं है तो यह true return करेगा।

6) Bitwise operators





&अगर दोनों बिट 1 है तो 1 सेट करता है।
|अगर दोनों में से कोई एक बिट 1 है तो 1
सेट करता है।
^सभी bits को 1 सेट करता अगर दोनों में से
कोई एक बिट 1 है।
~सभी bits को उल्टा(Inverse) करता है।
मतलब सभी 0 को 1 और 1 को 0 करता है।
<<right operand में दिए हुए bits के अनुसार left operand
value को left shift करता है।
>>right operand में दिए हुए bits के अनुसार
left operand value को right shift करता है।

7) Membership operators





inदिए हुए sequence में दी हुई value
present है तो true return करता है।
not inदिए हुए sequence में दी हुई value
present नहीं है तो true return करता 

Python Decision making




Decision making का उपयोग कर condition के आधार पर statements को execute किया जाता है। Python में निम्न का उपयोग कर Decision making कर सकते है।
  1. if
  2. if else
  3. if elif
Decision making में अगर condition true होती है तो ही statements execute होते है अन्यथा नहीं होते।

1) if




दिया हुआ condition true है तो ही if के statements execute होंगे।
age = 20

if age >= 18:
  print('eligible for vote')

2) if else




if else में अगर if में दिया हुआ condition true है तो if के statements execute होंगे अगर false है तब ही else में दिए हुए statements execute होंगे।
else में condition नहीं दी जाता है।
age = 20

if age > 18:
  print('eligible for vote')
else
  print('not eligible for vote')

2) if elif




if else में अगर if में दिया हुआ condition true है तो if के statements execute होंगे अगर false है तब ही elif में दिया हुआ condition चेक होगा और वो true है तब उसमें दिए हुए statements execute होंगे, नहीं तो else में दिए हुए statements execute होंगे।
elif जितनी बार चाहे उपयोग किया जा सकता है पर ये हमेशा if के बाद ही आता है।
else optional है इसका मतलब यह है के इसका उपयोग किया जा सकता है और नहीं भी।
else हमेशा आखरी में ही उपयोग किया जाता है।
weather = 'rainy'

if weather == 'rainy':
  print('rainy season')
elif weather == 'winter':
  print('winter season')
else
  print('summer season')

4) Nested IfPython में दूसरी languages की तरह if के अंदर if का उपयोग किया जा सकता है इसे ही nested if कहते है।




a = 30
b = 10
if a == 30:
  if b >=10:
     print('a = 30 and b = 10')
 print('a = 10')

Python loops




loop का उपयोग program में statements को दिए हुए condition के आधार पर repeat करने के लिए किये जाते है। python में loops के प्रकार निम्न है।
  1. for
  2. while
  3. nested loops

1) for loop




days = ["sunday", "monday", "tuesday", "thursday", "friday", "saturday"]
for x in days:
  print(x)

2) while loop




no = 1
while no < 10:
  print(no)
  no += 1

3) Nested loops




दूसरी programming languages की तरह python में ही loop को दूसरे loop के अंदर लिखा जा सकता है इसे ही nested loop कहते है।

Exampleno = [1, 2, 3, 4, 5, 6, 7]




days = ["sunday", "monday", "tuesday", "thursday", "friday", "saturday"]

for x in no:
  for y in days:
  print(y, x)

Python jump statements




Jump statements का उपयोग कर प्रोग्राम में control को एक जगह से दूसरी जगह transfer किया जाता है। Python में मुख्यता इनका उपयोग लूप में होता है। python में निम्न jump statements उपलब्ध है।
  1. break
  2. continue

break




break स्टेटमेंट का उपयोग लूप से control को बहार ट्रांसफर करने के लिए किया जाता है, मुख्यता break को लूप में condition के साथ उपयोग किया जाता है।
l1 =[1,2,3,4,5,6,7,8,9,10]  
count = 1;  
for no in l1:  
    if no == 7:  # if matches, break statement exits the loop
        break 
   print(no) 
ऊपर दिए हुए उदहारण में अगर no == 7 मैच हो जाता है तो break statement प्रोग्राम के control को लूप के बहार ट्रांसफर कर देगा।

Output




1 2 3 4 5 6

continue




continue का उपयोग लूप के cycles या iteration को skip करने के लिए उपयोग किया जाता है। मुख्यता continue को लूप में condition के साथ उपयोग किया जाता है।
l1 =[1,2,3,4,5,6,7,8,9,10]  
count = 1;  
for no in l1:  
    if no == 5:  # if matches, skips loop cycle
        continue
   print(no) 
ऊपर दिए हुए उदहारण में अगर no == 5 मैच हो जाता है तो continue statement लूप के cycle को स्किप करेगा जिससे 5 प्रिंट नहीं होगा।

Output1 2 3 4 6 7 8 9 10

Python functionsFunction statements का set होता है जो के specific task को करने के लिए बनाया जाता है। Python program में function का उपयोग करने के निम्न फायदे है।







  1. Readability बढ़ती है।
  2. code redundancy या duplicacy नहीं होती है।
  3. Debug करना आसान हो जाता है।

function का उपयोग निम्न तरीके से होता है।

1) Define/Create a function

Function को उपयोग करने के लिए सबसे पहले function को create/define किया जाता है।
def my_first_function():
  print("Hello world")

2) Call a function

Function को create करने के बाद उपयोग करने के लिए function को call किया जाता है।
def my_first_function():
  print("Hello world")

my_first_function() # function call

Parameters in function

Function में parameters भी दिए जा सकते है, जिसके ज़रिये function को call करते समय input दिया जा सकता है।

Example

def my_first_function(greeting):
  print("Hello world " + greeting)

my_first_function('Good morning')

my_first_function('Good afternoon')

my_first_function('Good evening')

Default value

function में calling के दौरान अगर argument नहीं दिया गया है तो function definition में parameter में assign की हुई value का उपयोग किया जाता है, इसे ही default value कहते है।
def my_first_function(greeting = 'Good night'):
  print("Hello world " + greeting)

my_first_function('Good morning') # Outputs Good morning

my_first_function() # Outputs Good night because no value is passed
                    # during function call. Hence default value is used.

Keyword Arguments

key = value का उपयोग कर python में arguments भेजे जा सकते है।
def my_first_function(name1, name2):
  print("Hello " + name1)
  print("Hi" + name2)

my_first_function(name2 = 'Ram', name1 = 'Shyam')
keyword में arguments किसी भी order में भेज सकते है।

Variable-length/Arbitary arguments

अगर हमें नहीं पता है के कितने arguments भेजने है तो इस तरह की स्तिथियो में Variable-length arguments का उपयोग किया जाता है।
Python में Variable-length arguments बताने के लिए * (asterisk symbol) का उपयोग किया जाता है। इस symbol को variable के पहले लगाना होता है।
def my_first_function(*greetings):
  print("Hello world " + greeting[0]) #outputs Good morning

my_first_function('Good morning', 'Good afternoon' , 'Good Evening', 'Good night')
इन arguments को index द्वारा access किया जाता है।

Return a value from function

Python में function से value को return कराया जा सकता है इसके लिए return keyword का उपयोग करना होता है।
def my_first_function(x):
  return x+2;

a = my_first_function(10)
print(a) #outputs 12

Lambda function Python




Python में lambda function को नाम नहीं दिया जाता और ये anonymous function होते है जो के lambda keyword का उपयोग कर define किये जाते है।
lambda function को एक ही expression में लिखा जाता है साथ ही जितने चाहे उतने arguments दिए जा सकते है जो evaluate होकर value को return करता है।

Syntax




lambda arguments : expression

Example




sum = lambda a : a + 10
print("total = ", sum(20))   

Why use lambda function?




Lambda function anonymous होते है इसलिए इनको नाम नहीं देना होता साथ ही ये automatically value को return कर देते है execute होने के बाद मतलब यह है के return keyword का उपयोग नहीं करना पड़ता है।
Lambda function को normal function के अंदर भी उपयोग किया जा सकता है।

Python ListList python में अलग अलग type का डेटा स्टोर या होल्ड करने के लिए उपयोग किया जाता है, list में डेटा को comma से separate रखते है और यह डेटा square brackets[] के अंदर रखा जाता है।




Create a list

list1 = ["Hello", 200, "India"]
list2 = ["Hello", "world", "India"]

Access list items

python में list के items को access करने के लिए index या फिर लूप का उपयोग कर सकते है।
list1 = ["Hello", 200, "India"]
print(list1[2]) #outputs India
print(list1[0]) #outputs Hello

Modify/Change list item

List में value को index का उपयोग कर update किया जा सकता है।
list1 = ["Hello", 200, "India"]
print(list1[1]) #outputs 200 before update

list1[1] = 500 # modified to 500 from 200
print(list1[1]) #outputs 500 after update

Access list using loop

list1 = ["Hello", 200, "India"]

for itms in list1:
  print(itms)

Delete List Items/Elements

List से item को delete करने के लिए del statement का उपयोग किया जाता है।
list1 = ["Hello", 200, "India"]

del list1[1]

print(list1[1]) #outputs India

Check item exists in list

list1 = ["Hello", 200, "India"]

if "Hello" in thislist:
  print('yes Hello exists')

Count items in list

list में अगर गिनना हो के कितने items है तो len() का उपयोग कर जान सकते है।
list1 = ["Hello", 200, "India"]

print(len(list1)) #outputs 3

Add item to list

list1 = ["Hello", 200, "India"]
list1.append("Cloud")
print(list1)

Insert item at specific index in list

list1 = ["Hello", 200, "India"]
list1.insert(2, "Cloud")
print(list1)

Python tuples




Python में tuple, list की ही तरह अलग अलग items को स्टोर या होल्ड करने के लिए उपयोग की जाती है सिर्फ अंतर इतना ही है के list के items को modify किया जा सकता है और tuples के items को modify नहीं किया जा सकता है।
Tuple में items comma से separated रहते है और parenthesis में रखे जाते है।
tuple1 = ("Hello", "Hi", 200)
print(tuple1)

Access tuple items




tuples के items को index का उपयोग कर access किया जा सकता है।
tuple1 = ("Hello", "Hi", 200)
print(tuple1[1]) #outputs Hi

Modify and Delete Tuple Elements




Tuple immutable है इसलिए इसमें item को directly modify करना या delete करना संभव नहीं है, पर आप tuple को list में convert कर modify या delete items को कर सकते है।

Modify




tuple1 = ("Hello", "Hi", 200)
print(tuple1)

list1 = list(tuple1)
list1[1] = "World"
tuple1  = tuple(list1)

print(tuple1)

Check item exists in tuple




tuple1 = ("Hello", "Hi", 200)

if "Hi" in tuple1:
  print("Hi is there")

Access tuple item using loop




tuple1 = ("Hello", "Hi", 200)

for itms in tuple1:
  print(itms)

Join tuples




tuple1 = ("Hello", "Hi", 200)
tuple2 = (22, world")

tuple3 =tuple1 + tuple2
print(tuple3)

Get tuple lengthlen() का उपयोग कर जाना जा सकता है tuple में कितने items है।




tuple1 = ("Hello", "Hi", 200)

print(len(tuple1))

Python Set




Python में set unordered items का collection है जो के comma से separated रहते है curly braces के अंदर रखे जाते है।
क्यूंकि सेट unordered है output के दौरान कौन सा item पहले या बाद में आएगा ये बताया नहीं जा सकता है।

Create a set




set1 = {200, 300, 400}
print(set1)

Access set elements




Set के items को index का उपयोग करके एक्सेस नहीं किया जा सकता है, सभी items को लूप का उपयोग कर एक्सेस करना होता है।
set1 = {200, 300, 400}

for itms in set1:
print(itms)

Add items in set




item को set में ऐड करने के लिए add() का उपयोग किया जाता है जो के एक ही item को एक बार में add कर सकता है।
set1 = {200, 300, 400}

set.add(500)
print(set1)

Add more than one item in set




set में एक से अधिक items को ऐड करने के लिए update() का उपयोग किया जाता है।
set1 = {200, 300, 400}

set.update([500,600,700,800])
print(set1)

Count items in set




Set में items को count करने के लिए len() का उपयोग किया जाता है।
set1 = {200, 300, 400}

print(len(set1))

Remove/delete item in set




Set से item को remove करने के लिए python में दो functions उपलब्ध है।
  1. remove()
  2. discard()

remove()




जिस item को remove कर रहे है अगर वो नहीं है set में तो remove() error देगा।
set1 = {200, 300, 400}
set1.remove(300)
print(set1)

discard()




जिस item को remove कर रहे है अगर वो नहीं है set में तो remove() error नहीं देगा।
set1 = {200, 300, 400}
set1.discard(300)
print(set1)

pop()




यह भी item को remove करने के लिए उपयोग किया जाता है पर set unordered होने की वजह से कौन सा item remove होगा नहीं बताया जा सकता है।
set1 = {200, 300, 400}
set1.pop()
print(set1)

Empty or clear all items in set




set के सभी items को एक साथ remove किया जा सकता है clear() का उपयोग करके।
set1 = {200, 300, 400}
set1.clear()
print(set1)

Delete Set




del keyword का उपयोग कर set को पूरी तरह delete किया जा सकता है।
set1 = {200, 300, 400}
del set1
print(set1)

Join or union two setsset1 = {200, 300, 400}




set2 = {500, 600, 700}

set_joined = setl.union(set2)
print(set_joined)

Python Dictionary




Python में dictionary key : value pairs का unordered collection होता है, जिसके items को index का उपयोग कर access किया जा सकता है। Dictionary के items को modify भी किया जा सकता है।
Dictionary में key value colon से separated होते है और अलग-अलग key values comma से separated होते है और इन्हे curly braces में रखा जाता है।

Create a dictionary




dictionary1 = {
  "Name": "Ram",
  "age": "25"
}
print(dictionary1)

Access dictionary items




Dictionary में items को उनकी key का उपयोग कर access कर सकते है।
dictionary1 = {
  "Name": "Ram",
  "age": "25"
}
print(dictionary1["Name"])
print(dictionary1["age"])
get() का उपयोग कर भी dictionary के items को access किया जा सकता है।
dictionary1 = {
  "Name": "Ram",
  "age": "25"
}
print(dictionary1.get("Name"))
print(dictionary1.get("age"))

Access dictionary items using loop

Access dictionary keys




dictionary1 = { "Name": "Ram","age": "25"}

for itms in dictionary1:
  print(itms)

Access dictionary values




dictionary1 = { "Name": "Ram","age": "25"} 
for itms in dictionary1.values():
   print(itms) 

Add items in dictionary




dictionary1 = { "Name": "Ram","age": "25"}
dictionary1["occupation"] = "Cricketer";
print(dictionary1["occupation"])

Change or modify dictionary items




dictionary1 = { "Name": "Ram","age": "25"}
print(dictionary1["Name"])

dictionary1["Name"] = "Shri Ram"
print(dictionary1["Name"])

Check key exists in dictionary




dictionary1 = { "Name": "Ram","age": "25"}
if "Name" in dictionary1:
  print(dictionary1["Name"])

Delete or remove dictionary items




pop() का उपयोग किया जाता है item को dictionary से remove करने के लिए, इसमें जिस item को remove करना है, उसकी key पास की जाती है argument में।
dictionary1 = { "Name": "Ram","age": "25"}
dictionary1.pop("age")
print(dictionary1)

Remove last inserted item from dictionary




dictionary1 = { "Name": "Ram","age": "25"}
dictionary1.popitem()
print(dictionary1)

Delete item with key




dictionary1 = { "Name": "Ram","age": "25"}
del dictionary1["age"]
print(dictionary1)

Delete complete dictionary




अगर आपने dictionary में delete करते समय key नहीं दी है तो पूरी dictionary delete हो जाएगी।
dictionary1 = { "Name": "Ram","age": "25"}
del dictionary1
print(dictionary1) #error

Empty dictionary




dictionary के सभी items को remove कर dictionary को clear कर देता है।
dictionary1 = { "Name": "Ram","age": "25"}
dictionary1.clear()
print(dictionary1)

Copy Dictionarydictionary1 = { "Name": "Ram","age": "25"}




dictionary2 = dictionary1.copy()
print(dictionary2)

Python Classes and Objects




Class एक ब्लूप्रिंट है जिसका उपयोग कर object create किये जाते है। class में data member और member function होते है। data member variable होते है जो data को स्टोर करते है वही member function methods होते है जो data member पर operations परफॉर्म करते है।

Create class




class को क्रिएट करने के लिए class keyword का उपयोग किया जाता है।
class FirstClass:
  a = 5

Add methods in class




class Employee:
  def __init__(self, empname, age):
    self.empname = empname
    self.age = age

  def printName(self):
    print("Employee name is " + self.empname)

e1 = Employee("Ram", 25)

print(e1.empname)
print(e1.age)
e1.printName()

Create Object from class




obj = FirstClass()
print(obj.a)

__init__() Function__init__() यह होता है इसे initialization method भी कहते है जो python call करता है जैसे ही class का object क्रिएट होता है।




class Employee:
  def __init__(self, empname, age):
    self.empname = empname
    self.age = age

e1 = Employee("Ram", 25)

print(e1.empname)
print(e1.age)

Python Inheritance




Inheritance का उपयोग कर parent class की सभी properties(data member व member function) को child class में उपयोग किया जाता है।
Parent class जो inherit की जाती है उस class को कहते है और child class वो class है जो दूसरे क्लास को inherit करती है।

Exampleclass ParentClass: # parent class name




   price = 100
   def __init__(self):
      print "Hello parent constructor"

   def myParentMethod(self):
      print 'parent method'

   def setAmount(self, amt):
      Parent.price = amt

   def getAmount(self):
      print "price is :", Parent.price

class ChildClass(Parent): # child class name
   def __init__(self):
      print "Hello child constructor"

   def myChildMethod(self):
      print 'Inside child method'

c = ChildClass()       # Create object of child
c.myChildMethod()      # calls child method
c.myParentMethod()     # calls parent's method
c.setAmount(1200)      # again parent's method call to set amount
c.getAmount()          # again parent's method call to get amount

Python Modules




python में module python की फाइल होती है जिसमे python का code लिखा हुआ होता है इसे code लाइब्रेरी भी कहा जा सकता है जिसका उपयोग दूसरी python फाइल में किया जा सकता है।
इसके उपयोग से एक ही code को बारबार नहीं लिखा पड़ता है और प्रोग्राम की readability बढ़ती है।

Create a module




module बनाने के लिए फाइल को नाम देकर .py extension से सेव कर ले।
उदहारण के लिए hello.py नाम रख लेते है, जिसमे sayhello नाम का function है।
module में functions के साथ variables का उपयोग भी किया जा सकता है।
def sayhello(name):
  print("Hello, " + name)

Using Python module




module को प्रोग्राम में उपयोग करने के लिए import keyword का उपयोग किया जाता है।
import hello

hello.greeting("Ram")

Renaming a module name




अपने python के सोर्स फाइल में module के नाम को बदल का उपयोग कर सकते है।

Syntax




import <module-name> as <your-specific-name>   

Exampleimport hello as hi





hi.greeting("Ram")

Python Date and Time




date time का उपयोग कर python में date time की जानकारी ली जा सकती है और इन्हे सेट भी किया जा सकता है।
date time के लिए datetime module को import करना होता है।
import datetime

Display current date time




import datetime

dt = datetime.datetime.now()
print(dt)

Create datetime object

Create date




Python में date को क्रिएट करने के लिए datetime() का उपयोग किया जाता है जो के तीन arguments (year, month, day) लेता है।
import datetime

x = datetime.datetime(2019, 12, 17)

print(x)

Create time




Python में datetime() से time को क्रिएट करने के लिए arguments में hour, minute, second, microsecond, tzone पास करना होता है।

Formatted time




asctime() function का उपयोग कर time को फॉर्मेट किया जाता है।
import time;  
  
print(time.asctime(time.localtime(time.time())))  

Sleep()प्रोग्राम के execution को दिए हुए समय तक रोकने के लिए उपयोग किया जाता है।




import time  
for i in range(0,10):  
    print(i)  
    time.sleep(1)  
ऊपर दिए हुए उदहारण में लूप हर नंबर को 1 सेकंड के बाद प्रिंट करेगा।

Python file handling




Python में file handling का उपयोग कर files को create open read write व delete किया जा सकता है।

Open() function




open() function का उपयोग कर files को create, read व write कर सकते है। मुख्यता यही function पूरी file handling में उपयोग किया जाता है।

Syntax




fileobject = open(<file-name>, <access-mode>, <buffering>) 

Create new file




new file create करने के लिए open() function में access mode x सेट करना होता है।
fileobj  = open("myfile.txt","x");  
  
print(fileobj)  
  
if fileobj:  
    print("File created successfully")

Write file




file में लिखने के लिए open() function में access mode w सेट करना होता है। अगर file create नहीं हुई है तो create कर देगा। अगर फाइल में content पहले से है तो overwrite कर देगा।
fp= open("myfile.txt","w")   
fp.write("Hello world how are you")
fp.close()

Append file




फाइल में content पहले से है और उसमे और content ऐड करना है तब append access mode का उपयोग किया जाता है।
fp= open("myfile.txt","a")   
fp.write("Hello world how are you")
fp.close()

Read file




फाइल से content को रीड करने के लिए open() function में access mode r सेट करना होता है।
fp= open("myfile.txt","r")   
print(f.read())
fp.close()

Read first 10 characters




fp= open("myfile.txt","r")   
print(f.read(10))
fp.close()

Read first Line from file




fp= open("myfile.txt","r")   
print(f.readline()) # read first line
fp.close()

Read all lines from file




fp= open("myfile.txt","r")   

for lines in fp:
  print(lines) 

fp.close()

Close a file




files में operations perform करने के बाद फाइल को close करना बहुत ज़रूरी होता है। इसके लिए close() function का उपयोग किया जाता है।
fp = open("myfile.txt", "r")
print(fp.read())
f.close()

Delete a file




Python में फाइल को delete करने के लिए os module को import करना होता है।
import os
os.remove("myfile.txt")

Create Folder/Directory




os module के mkdir() function का उपयोग कर folder को create कर सकते है।
import os
os.rmdir("myfiles")

Delete Folder/Directory




os module के rmdir() function का उपयोग कर folder को delete कर सकते है।
import os
os.rmdir("myfiles")

File exist or notimport os




if os.path.exists("myfile.txt"):
  print('file exists')
else:
  print("file does not exist")

Python Command Line Input




python में Command prompt का उपयोग कर यूजर से input लिया जा सकता है।

Exampleinput() function का उपयोग कर python में Command prompt से input लिया जा सकता है।




print("Enter your age")
age = input()  #ask user to iput
print ('age is ', age)

Comments are clos

JSON Python




JSON data interchange format है, इसका उपयोग डेटा को exchange करने के लिए उपयोग होता है।
Python में None, list, tuple, dict, string, int, float, True, False को json string में convert किया जा सकता है।
Python में को उपयोग करने के लिए json module को import करना होता है सोर्स फाइल में।
import json

Convert data into JSON




json की dumps() function का उपयोग कर json string में डेटा को convert किया जा सकता है।
import json

# Python dictionary:
employee = {
  "name": "Ram",
  "age": 28,
  "city": "Mumbai"
}

jsn_str = json.dumps(employee) # convert into JSON:

print(jsn_str) #  outputs JSON string

Convert JSON into objectimport json




employee =  '{ "name":"Ram", "age":33}' # JSON object

y = json.loads(employee) # parse employee

print(employee["age"]) # outputs Python dictionary

Comments are closed.