technical skills grow

Responsive Ads Here

Sunday, August 23, 2020

Python

 PIP is python package manager .PIP is used for download  .

Write first program in python .

Part 1: 

 #vim first.py


#first program in python

print ("Hello to python")
 save and exist from file .

output :- Hello to Python


print("India is best country")
print ("I love India")
Output :
India is best country
I love India

#I want to print both line Using end keyword
print("India is best country", end="")
print ("I love India")

Ouput : India is best countryI love India
#If you give space with end = " "  
print("India is best country", end=" ")
print ("I love India")

Ouput : India is best country I love India

Part 2: Comments, Escape Sequences & Print Statement

Use Single Line & Multi Line comment in python


print("Single line comment")
#Single line comment


print("Multi line comment")
"""
HOW TO USE
Multi line comment
IN PYTHON

"""


 

Part 3 : Predefined function

st="india is best 23 country"
print (st.replace("23",""))
Output :india is best country
 
st="india is best 23 country"
 
print(st.capitalize())  #first letter capital  
Output 
#India is best 23 country
 
print(st.find("23"))      #It is 14 place
#Output 14 
print(st.upper()) # INDIA IS BEST 23 COUNTRY
 
Output: INDIA IS BEST 23 COUNTRY

print(st.lower())
 
Output : india is best 23 country

print(st.isalnum())
Output : False
st1="Indiaisbestcountry"
print(st1.isalnum())
Output : False

st3="Indiaisbes tcoutry"
print(st3.isalpha())
 
Output : False

st4="Indiaisbes t coutry"
print(st4.endswith("ry")) #End with ry
 
Output : True 
st4="Indiaisbes t coutry"  

print(st4.count("i"))  #Count total i 
Output : 3
count,funcation,endswith
 

Part 4: Variables, Datatypes and Typecasting 


#Print string or integer
x = 10
y = "Tom"
print(x)
print(y)

#add two no in python
x = 10
y = 20
print("Add two No-",x + y);

 

Part 5: Type of Variable 

#1.string   --- "This is good boy"
#2.Integer -- 1 , 2, 4 like that
#3.Float -- 1.3 ,5.6

variable


x = 50
y = "Welcome to Python"
print(x)
print(y)
print("___________________________Second Program_________________________")

a=1
c=4
print("Add Two no -", a + c )
print("___________________________________Third Program_______________________")
#print 10 times in single line
print(10 * "Hello world")
#print 10 time in next line
print(10 * "Hello world\n")

Part 6: String Slicing And Other Functions

st="India is best country"
print(len(st))
Output : 21
#print string starting indexing from zero to last character
# I n d i a ....
# [0][1][2][3][4] ....
#frist starting point 0:print lenth : skip values
print(st[0:14])
Output : India is best
print (st[0:5:2])
Output : Ida

#Reverse string in python

print(st[::-1])
#Output : yrtnuoc tseb si aidnI

Part 7: Typecasting

print("Type casting variable convert string to integer")
x = "50"
y = "10"
print(int(x)+int(y))

output : 60

print ("convert into again in string")

print(100 * str(int(x)+int(y)))
#Output
___________________________convert into again in string_________________________
60606060606060606060606060606060606060606060606060606060606060606060606060606060606060606

 Part 8 : Give input by user

#Give input from user
print("Please Enter No")
no = input()

print ("You are enter",no)
 
Output
Please Enter No
10
You are enter 10

#Add two no
print("Please Enter first no")
no1 = input()
print("Please Enter second no")
no2 = input()
print ("sum of two no -",int(no1) + int(no2))

Please Enter first no
20
Please Enter second no
30
sum of two no - 50

PART 9#Python Lists And List Functions

ex:1
STATE_NAME=["UP","MP","HP","HARYANA",76]
print(STATE_NAME[0])

TEMP_MAX=[2,6,1,10,7,18]
TEMP_MAX.sort()
#TEMP_MAX.reverse()
print(TEMP_MAX)
OUTPUT :
UP
[1, 2, 6, 7, 10, 18]
ex : 2
TEMP_MAX=[2,6,1,10,7,18]
TEMP_MAX.sort()
TEMP_MAX.reverse()
print(TEMP_MAX)
#OUTPUT :
#UP
[18, 10, 7, 6, 2, 1]
ex :3   [Starting_List:Last_no : Jump No]
TEMP_MAX=[2,6,1,10,7,18]
print(TEMP_MAX [::2])
 
#OUTPUT : [2, 1, 7]

length function :

TEMP_MAX=[2,6,1,10,7,18]
print(len(TEMP_MAX))
#OUTPUT : 6

MAX Function :

TEMP_MAX=[2,6,1,10,7,18]
print(max(TEMP_MAX))
#OUTPUT : 18

Append Function

TEMP_MAX=[2,6,1,10,7,18]
TEMP_MAX.append(100)
print(max(TEMP_MAX))
Output :[2, 6, 1, 10, 7, 18, 100] 

MULTIPLE VALUES ADD

 
TEMP_MAX=[2,6,1,10,7,18]
TEMP_MAX.append(100)
TEMP_MAX.append(300)
TEMP_MAX.append(200)

print((TEMP_MAX))

Output :[2, 6, 1, 10, 7, 18, 100, 300, 200]

INSERT FUNCATION

#First Place is insert value index[1] . it is also follow index [0][1][2][3][4] 
TEMP_MAX=[2,6,1,10,7,18]
TEMP_MAX.insert(1,90)
print((TEMP_MAX))
#OUTPUT : [2, 90, 6, 1, 10, 7, 18]
#IT IS REMOVE VALUES 1 from list
REMOVE Funcation
TEMP_MAX=[2,6,1,10,7,18]
TEMP_MAX.remove(1)
print((TEMP_MAX))
#OUTPUT : [2, 6, 10, 7, 18]

POP Funcation

TEMP_MAX=[2,6,1,10,7,18]
TEMP_MAX.pop()
print((TEMP_MAX))
#OUTPUT : [2, 6, 10, 7, 18]

#Tuple in Python

#mutable : You can't change but in list you can change

tp =(1,4,5,6)
tp [1]=90
print(tp)
TypeError: 'tuple' object does not support item assignment 
tp =(1,4,5,6)
print(tp)
Output:(1, 4, 5, 6)

Example : SWAP TWO NO IN PYTHON

a=10
b=20

a,b=b,a
print("Swap Two no -",a,b)
Swap Two no - 20 10


 

Part 10 :Dictionary & Its Functions

 d1 = {"Tarun":"DBA","Arpti":"Executive","Vikash":"Network",

      "STATION_DATA":{"MAX_TEMP":"30","RH":"10","SUM_RAIN":"40"}}

print (d1["Tarun"])
print (d1["STATION_DATA"])
print (d1["STATION_DATA"]["MAX_TEMP"])

#ADD MORE ITMES

d1["Ankit"] = "QC"
print (d1)
#Output :
#{'Tarun': 'DBA', 'Arpti': 'Executive', 'Ankit': 'QC', 'STATION_DATA':
# {'RH': '10', 'SUM_RAIN': '40', 'MAX_TEMP': '30'}, 'Vikash': 'Network'}

#Remove value

del d1["Arpti"]
print(d1)
#Output :
# {'Tarun': 'DBA', 'Ankit': 'QC', 'STATION_DATA': {'RH': '10', 'SUM_RAIN': '40', 'MAX_TEMP': '30'},
# 'Vikash': 'Network'}

 #COPY FUNCATION

d1 = {"Tarun":"DBA","Arpti":"Executive","Vikash":"Network",
"STATION_DATA":{"MAX_TEMP":"30","RH":"10","SUM_RAIN":"40"}}
#d2 is pointr and d1 also pointer so it is not make copy of d1
d2=d1
#Now we are use copy funcation its makes copy in d3
d3=d1.copy()
del d1["Arpti"]
print(d2)
#output
# {'Vikash': 'Network', 'STATION_DATA': {'RH': '10', 'MAX_TEMP': '30', 'SUM_RAIN': '40'}, 'Tarun': 'DBA'}

print(d3)
#output
# {'Vikash': 'Network', 'STATION_DATA': {'RH': '10', 'MAX_TEMP': '30', 'SUM_RAIN': '40'}, 'Tarun': 'DBA', 'Arpti': 'Executive'}

 #UPDATE VALUES

d1 = {"Tarun":"DBA","Arpti":"Executive","Vikash":"Network",
"STATION_DATA":{"MAX_TEMP":"30","RH":"10","SUM_RAIN":"40"}}
d1.update({"KALU":"Linux"})
print (d1)
#output
#{'Tarun': 'DBA', 'Arpti': 'Executive', 'STATION_DATA': {'MAX_TEMP': '30', 'SUM_RAIN': '40', 'RH': '10'}, 'KALU': 'Linux', 'Vikash': 'Network'}

 

d1 = {"Tarun":"DBA","Vikash":"Network"}
print(d1.keys())
#output
#dict_keys(['Vikash', 'Tarun'])
print(d1.items())
#output
#dict_items([('Vikash', 'Network'), ('Tarun', 'DBA')])

#Find the Run time values from Dictionary

print("Find the latter ")
d1= {"A":"Apple","B":"Banana","C":"Cat","D":"Dog"}
f1=input()
print("Meaning :-",d1[f1])
Output :
Find the latter
C
Meaning :- Cat

print("Enter the Age")

Part 11 :If Else & Elif Conditionals In Python

IF Else USE In Python

age = int(input())
if age > 18:
print("You can drive")
elif age < 18:
print("You can't drive")
elif age == 18:
print("You have to give test")
Output : Enter the Age
20
You can drive

Example 2:

list=[1,3,4,5,6]
if 5 in list:
print ("Yes in the list")

Output:- Yes in the list
 

Example 3:

 list=[1,3,4,5,6]

if 5 not in list:
print ("Yes in the list")
else:
print("Not in the list")
Output:- Not in the list
Example :Enter the valid age 
print("ENTER YOUR AGE:")
age= int(input())
if (7<age<=100):

if (age>18):
print("you can drive")
elif age==18:
print ("we can not decide here. come to RTO")
else:
print ("you can not drive")

else:
print("enter valid age")

Calculator

print("Enter the two no")
print("Enter the first no")
a=int(input());
print("Enter the Second no")
b=int(input());
print("What you want * + - /")
val=input()
if val=="*":
val1=a*b
print(val1)
elif val=="+":
val1=a+b
print(val1)
elif val=="-":
val1=a-b
print(val1)
elif val=="/":
val1=a/b
print(val1)

else:
("Bye")

Part 12 :For Loops In Python 

example :

list1 =(1,2,3,4,5,6,7,8,9,10)
for a in list1:
print(a)

Output:


1
2
3
4
5
6
7
8
9
10

Example :

list = [ ["A",1 ],["B",2],["C",3],["D",4],["E",5] ]

for itam,key in list:

print(itam,"AND",key)

Ouput:
A AND 1
B AND 2
C AND 3
D AND 4
E AND 5

#Task I want to print All iteam greater then 6

list1 =(1,2,3,4,5,6,7,8,9,10)
for a in list1:
if a > 6:
print(a)
Output :
7
8
9
10

Print Start using loop

for  i in range(10):
for j in range(i):
print("*" , end=' ')
print()

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *  

Part 15 :Python Operators

Type of Operators

1.Arithmetic Operators         -       +   -   *   /     %

2.Assignment Operators       -         =

3. Logical Operators             -         and  or  not

4.Identity Operators             -        is , is not

5.Membership Operators      -        in , in not

6.Bitwise operators               -        &   ||   <<   >>

   

Part 14 : While Loops In Python

#User of While loop

i=0
while i < 5 :
print (i)
i=i+1;
Output :
0
1
2
3
4

#Print output in State line While loop using End

i=0
while i < 5 :
print (i,end =" ")
i=i+1;
#Output : 0 1 2 3 4


Part 15 : Break & Continue Statements In Python

 

#Without break output

i=0
while i <= 25 :
print (i,end =" ")
i=i+1;
#Output : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25


#With break output

i=0
while i <= 50 :
print (i,end =" ")
if i == 15:
break
i=i+1;
#Output : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

#With Continue output


i = 0
while i < 9:
i = i + 1
if i == 3:
continue
print(i,end= " ")

 Quize :

while (True):
i = int(input("Enter the bike speed :"))
if i > 100:
print("You have crossed the limit drive slow")
break

else:
print("Again enter the speed")
continue
output:
Enter the bike speed :50
Again enter the speed
Enter the bike speed :10
Again enter the speed
Enter the bike speed :100
Again enter the speed
Enter the bike speed :101
You have crossed the limit drive slow

 

Part 16 : Functions And Docstrings  

 User define functions for use def :

def fun():
print("Welcome to funcation")
fun()
Output: Welcome to funcation

#We are calling functions tree time it will be print tree times

def fun():
print("Welcome to funcation")
fun()
fun()
fun()

Output :
Welcome to funcation
Welcome to funcation
Welcome to funcation

# Input from user

a = int(input("Enter the first value : "))
b = int(input("Enter the second value : "))

def fun(a, b):
t = (a + b)
return t
t = fun(a , b)
print ("Sum of two values :" ,t )
#print( t )

def fun1 ( a , b):
mul = (a * b )
return mul
mul = fun1(a ,b)
print("Multiple of two values :", mul )
 
Output :
Enter the first value : 10
Enter the second value : 20
Sum of two values : 30
Multiple of two values : 200
 

#Doc string use :

It is used for show function nature which type of function

a = int(input("Enter the first value : "))
b = int(input("Enter the second value : "))

def fun(a, b):
"""This function is calculate the two no"""
t = (a + b)
return t
t = fun(a , b)
#print ("Sum of two values :" ,t )
print (fun.__doc__ )
print(t)
Output :Enter the first value : 10
Enter the second value : 30
This function is calculate the two no
40

Part 17: Try Except Exception Handling In Python

a = input(" Enter the value 1 ")
b = input(" Enter the value 2 ")
try:
print("", int(a) + int(b) )
except Exception as e:
print(e)

Output :
Enter the value 1 10
Enter the value 2 e
invalid literal for int() with base 10: 'e'

 

Part 18 : How to play with File IO 

r  -  Open file for reading

w - Open file for writing

x  -  Create file if not exist

a - Add more content to

t  -  text mode

b - binary mode

+ - read and write mode 

(a) How to read data from text file .

vim csv.text 

Welcome to python programmer 

vim read.py

f = open("csv")
c = f.read()
print (c)
f.close()
Output :
Welcome to python programmer

Print line one by one 

f = open("csv")  # type:
c = f.read()
for line in c:
print(line, end="")
# f.close()

# Output :
Hello This is my file
Hello This is my wife
Hello this is my car
HEllo this is my new house

Readline function 

#You will use readline function it will be print one by one line


f = open("csv") # type:
print(f.readline(), end="")
print(f.readline(), end="")
print(f.readline(), end="")

# Output :
#Hello This is my file
#Hello This is my wife
#Hello this is my car

(b) Write file in python

I have blank file like a.txt . I want to write some line in this file used it code

f = open ("a.txt","w")

f.write("This is my new line ")

cat a.txt 

This is my new line

Note :

Now I have two file a.txt and b.txt . I want to read a.txt file and write data from a.txt to b.txt 

#write data in csv file
f = open("b", "w")
#Read data from txt file
rd = open("a","r")
k = rd.read()
f.write(k)
print(rd)
# f.write (k)

# f.write ("I love python")
f.close()

Append Line

f = open("csv", "a")
rd = open("txtfile","r")
k = rd.read()
f.write(k)
#count = f.write(k)  #Use when you want to count total no of value in file
#print(count)

f.close()

Read Write line

f = open("csv", "r+")
print(f.read())
f.write("I love also linux\n")

Seek(), tell() & More On Python Files

Seek(): function is used for reset the pointer  .

Tell(): Is used for tell pointer place .

#Use seek function
rd = open("csv")
print(rd.tell())
a = rd.read()
print (a)
f = open("csv","a")
f.write("This python file \n")
print(rd.tell())
rd.close()
f.close()
Output :
0
This is new lineThis python fileThis python fileThis python fileThis python fileThis python fileThis python file
This python fileThis python file

147

Seek()

rd = open("csv")

print(rd.readline())
rd.seek(0)
print(rd.readline())
Output:
This is new lineThis python fileThis python fileThis python fileThis python fileThis python fileThis python file

This is new lineThis python fileThis python fileThis python fileThis python fileThis python fileThis python file


Using With Block To Open Python Files:

With is use regarding to we can handel file without close  

# f = open("csv","w")
# f.write("This is new line")
with open("csv") as f:
a = f.read(4)
print(a)
Output : - this
  

Program : Daily Routine Plane using file handling

from datetime import datetime
def getdate():
# datetime object containing current date and time
now = datetime.now()
# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
return dt_string

file = int(input("Read file press 1 or entry data press 2"))
person = input("Enter the person name")
if file == 1:
RF = open(person,"r")
p= RF.read()
print(p)
else:

c = int(input("Press 1 for Food and 2 for Exercise"))
if c == 1:
meal = input("Enter the meal")
# def food(meal):
f = open(person , "a")
f.write(str(str(getdate())) + " : " + "Meal- " + meal + "\n")
else:
# def exercise(ex):
ex = input("Enter the exercise name")
f = open(person , "a")
# f.write(ex)
f.write(str(str(getdate())) + " : " + "Ex- " + ex + "\n")
Output  

Read file press 1 or entry data press 21
Enter the person nameTarun
05/09/2020 00:56:44 : Roti
05/09/2020 00:59:35 : butter fly

05/09/2020 01:01:20 : Meal-Rice

Part 19 :Scope, Global Variables and Global Keyword 

a = 10  # Global Variable
b = 5 # Global Variable
# We can use this variable inside in function
def fun1(a, b):

return a * b

print("Multiple of two values :", fun1(a, b))

Use Global Keyword

 

a = 10  # Global Variable
b = 5 # Global Variable


# We can use this variable inside in funcation

def fun1(a, b):
val = a + 10
return a * b

print("Multiple of two values :", fun1(a, b))
#We can't change Value of a variable in funcation. So we need Gloabl keyword.

a = 10  # type: # Global Variable
b = 5 # Global Variable
c= 0

# We can use this variable inside in funcation

def fun1(c , b):
global a
c = a + 10
return c * b

print("Multiple of two values :", fun1(c, b))

Anonymous/Lambda Functions In Python

lambda function is used for one liner function in python

example :

Add = lambda x, y : x + y

print (Add(10,50)

Output : 50

F-Strings & String Formatting In Python

Val1 = "Men Power"
Val2 = 10

x = "Hello Your have only %s %s "%( Val1 , Val2)
print (x)
Output :  Hello Your have only Men Power 10 

F- String is support 3.6 not 3.5

Val1 = "Men Power"
Val2 = 10

x = f"Hello Your have only {Val1} {Val2}"
print (x)
Output :  Hello Your have only Men Power 10
 

How can you enter the multiple argument in Python

Solution We can use *agrs 

We can enter the value run time 

x = list( input("Enter a multiple value: ").split())
def fun1(*args):
print(args[0])
val = [x]
fun1(*val)

Output :Enter a multiple value: Tarun Rohit Sachin
['Tarun', 'Rohit', 'Sachin']

Ex: 1
def fun1(*args):
print(args[0])
val = ["Tarun ,Rohit ,Raja ,Amit ,Ashu"]
fun1(*val)

Ex- user foor loop

#x = list( input("Enter a multiple value: ").split())
def fun1(*args):
for itme in args:
print (itme)
val = ["Tarun ,Rohit ,Raja ,Amit ,Ashu"]
fun1(*val)

output :
Tarun ,Rohit ,Raja ,Amit ,Ashu

How to create Virtual Environment & Requirements in Python click here .. 

 

Part 20 :Enumerate Function

I want to print  odd value items 

 ll = ["A","B","C","D"] 

for index, item in enumerate(ll):

 if index%2 == 0:

 print(item)

 output :A  C

 

No comments:

Post a Comment

Powered by Blogger.

Labels

Contact Form

Name

Email *

Message *

Search This Blog

Blog Archive

Ad Code

Responsive Advertisement

Recent Posts