❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayArokya Naresh

File Handling in Python

14 August 2024 at 11:48

File Handling in Python
Modes
Read Mode 'r'
Write Mode 'w'
Append(Editable) 'a'
to read binary file 'rb'
To delete a file use remove()

To open a source file in readmode

Eg;
with open('source.txt','r') as file:

print(file,type(file))

To get to know the type of the file
with open('source.txt','r') as file:
print(file,type(file))

To create a new file or over-write use Write mode

Eg:
with open('source1.txt','w') as file:
file.write('e f g h')
file.write('i j k l')

To append more info we use append mode

Eg:
with open('source1.txt','a') as file:
file.write('m n o p')

saved file will be
e f g hi j k lm n o p

To check whether file present or not
import os

if os.path.isfile('source1.txt'):
print('source1 founded')
else:
print('source1 not founded')

o/p:
source1 founded

Again to read the content of that file

with open('source1.txt','r') as source_file:
content=source_file.readline()
print(content)

o/p

e f g hi j k lm n o p

To read binary file 'rb'
with open('binary.txt','rb') as source_file:

To delete a file

import os
os.remove('source1.txt')

Tuple and Sets in Python 08.08.2024

8 August 2024 at 17:06

Tuple(eg1-photoframe.A family going to trip and capturing photos)

In Tuple,values cannot be changed
but we can assign tuple to a list
We can multiply the tuple but cant modify
We can concatenate two tuples
We can acces using Indexing
Unpacking
We can convert tuple into a list

Tuple Creation-once created we cannot change.

o_trip=('Ooty','2024-1-1','Mountain')
m_trip=('Munnar','2024-1-3','falls')
kumarkom_trip=('kumarakom','2024-1-5','dinner')
print('Ooty trip',o_trip,type(o_trip))

photo_album=[o_trip,m_trip,kumarkom_trip]
print(photo_album)

location=o_trip[0]
print('Location',location)

print(m_trip)
location,date,visted=m_trip #tuple created
print(m_trip)

how to identify tuple-one variable assigned with many values is considered as tuple

Checking Tuple values are present
eg
double_o_fun=o_trip*2
print(double_o_fun)

O/p
('Ooty', '2024-1-1', 'Mountain', 'Ooty', '2024-1-1', 'Mountain')-->() braces say tuple

To check length of the Tuple
eg.

print(len(photo_album))
o/p
3

We can change Tuple into a List
eg

o_trip=('Ooty','2024-1-1','Mountain')
m_trip=('Munnar','2024-1-3','falls')
kumarkom_trip=('kumarakom','2024-1-5','dinner')

o_list=list(o_trip)
print(o_list)

o/p
['Ooty', '2024-1-1', 'Mountain']-->[] braces say List

SET-(Union,Intersection,Difference)
We cannot add duplicate items
We can add values
We can remove values
we can check values are present
It has unique values
Here we cannot use indexing bcoz its unordered

Tuple Creation

my_garden={'Rose','Lily','Jasmine'}
print(my_garden,type(my_garden))
o/p
{'Rose', 'Lily', 'Jasmine'}

adding more values

my_garden.add('Marigold')
print(my_garden)
o/p
{'Rose', 'Lily', 'Jasmine', 'Marigold'}

adding duplicate value

my_garden.add('Rose')
print(my_garden)
o/p
{'Rose', 'Lily', 'Jasmine', 'Marigold'}

remove value

my_garden.remove('Rose')
print(my_garden)
o/p
{'Lily', 'Jasmine', 'Marigold'}

to check whether specific values are present

is_rose_in_mygarden='Rose' in my_garden
print(is_rose_in_mygarden)
o/p
False

is_marigold_in_mygarden='Marigold' in my_garden
print(is_marigold_in_mygarden)
o/p
True

Intersection -to find common values with two set

my_garden={'Rose','Lily','Jasmine'}
print(my_garden)

n_garden={'Rose','Lotus','Hibiscus'}
print(n_garden)

comon_flowe=my_garden.intersection(n_garden)
print(comon_flowe)

o/p-

{'Rose', 'Lily', 'Jasmine'}
{'Hibiscus', 'Rose', 'Lotus'}
{'Rose'}

Differences -to find differnce with two set
my_garden={'Rose','Lily','Jasmine'}
print(my_garden)

n_garden={'Rose','Lotus','Hibiscus'}
print(n_garden)

diff_flowe=my_garden.difference(n_garden)
print(diff_flowe)

o/p
{'Rose', 'Lily', 'Jasmine'}
{'Hibiscus', 'Rose', 'Lotus'}
{'Lily', 'Jasmine'}

Union -to combine tuple
my_garden={'Rose','Lily','Jasmine'}
print(my_garden)

n_garden={'Rose','Lotus','Hibiscus'}
print(n_garden)

union_flowe=my_garden.union(n_garden)
print(union_flowe)

o/p

{'Rose', 'Jasmine', 'Hibiscus', 'Lily', 'Lotus'}

methods in python 31.07.2024

1 August 2024 at 12:30

Methods in LIST

1.Append method

this append method will add items/info at the end of the list

Eg:
package=['Apple','Mango','Banana']
print(package)

package.append('Kiwi')
print(package)

o/p
['Apple', 'Mango', 'Banana']
['Apple', 'Mango', 'Banana', 'Kiwi']

2.insert method

If incase you need to add the items/info in the middle so we can use insert() method

package=['Apple','Mango','Banana']
print(package)

package.insert(1,'Guava') #1 is the index position where we can add items/info
print(package)

o/p
['Apple', 'Mango', 'Banana']
['Apple', 'Guava', 'Mango', 'Banana']

3.Remove method

package=['Apple','Mango','Banana']
print(package)

package.remove('Mango')
print(package)

o/p:
['Apple', 'Mango', 'Banana']
['Apple', 'Banana'

4.Pop method

This POP method will removes last items/info in the list
Also deleted items/info will be returned or assigned to a variiable

Eg:
package=['Apple','Mango','Banana']
print(package)

package.pop()
print(package)

O/P
['Apple', 'Mango', 'Banana']
['Apple', 'Mango']

5.Index method()
To find the Index position we use index() method
Eg:
package=['Apple','Mango','Banana']
print(package)

x=package.index('Mango')
print(x)
o/p
['Apple', 'Mango', 'Banana']
1

6.sort() method

It is used to sort the items/values in the list in Alphabetic order

Eg:
package=['Apple','Mango','Banana']
print(package)

package.sort()
print(package)

O/P
['Apple', 'Mango', 'Banana']
['Apple', 'Banana', 'Mango']

7.reverse() method

It is used to reverse the items/values in the list

Eg
package=['Apple','Mango','Banana']
print(package)

package.reverse()
print(package)

O/P
['Apple', 'Mango', 'Banana']
['Banana', 'Mango', 'Apple']

Python tutorial 25.07.2024

25 July 2024 at 11:54

SLICING
we can hop btwn letters in the index

        H   e   l   l   o   m   o   b   i   l   e

Positive Indexing 0 1 2 3 4 5 6 7 8 9 10
Negative Indexing -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Eg1:
msg='HelloMobile'
print(msg[0:11:2]) -->2 denotes hop (i.e no. of hop inbtwn letter )
print(msg[0:11:3])

o/p
Hlooie
Hlol

Iterable-is a container of value which we can iterate by using loop

eg:
loop='Apple'
for d in loop[1:]:
print(d)

A
p
p
l
e

Here loop is that container which has values Apple.To get to know what is in that loop we use for loop which we can iterate

Python Index tutorial 22.07.2024

25 July 2024 at 11:52

Index

String-Sequence of characters
each character have each position called as index
Index values starts from 0
Spaces inbetween each word also calculator
Indexing has positive and negative indexing
Negative indexing -1 starts from end of the character

Eg:
word='Message'

        M   e   s   s   a   g   e

Positive Indexing 0 1 2 3 4 5 6
Negative Indexing -7 -6 -5 -4 -3 -2 -1

word[3]
s

len(word)
6

Slicing

string[startingindex:before value to end]

string[startingindex:before value to end:direction] -->this reverse the direction of the string

string[]-this prints the entire values

Eg:

        H   e   l   l   o   m   o   b   i   l   e

Positive Indexing 0 1 2 3 4 5 6 7 8 9 10
Negative Indexing -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

msg='HelloMobile'
print(msg[2:5]) #postive index
print(msg[-5:-2]) #negative index
print(msg[::-1])reverse the string
print(msg[-2:-5:-1]) #reverse la print aagum
print(msg[5:])
print(msg[:-5])

o/p
llo
obi
elibomolleH
lib
Mobile
HelloM

Python Functions 17.07.2024

21 July 2024 at 15:51

Functions

repeated step can be executed with functions

Funtion Structure:

def name(argument):
Statement..
Statement..

return value

def-define function
def functionname(contains a list of values passed to the function)
function body must be indented
this is executed each time the function is called
return values

Function has bulid-in function and user-defined functions

Eg-Calculator prgm
num1=float(input('Enter value for num1 '))
num2=float(input('Enter value for num2 '))
choice=input('Operation to be done:add/sub/mul/div/mod ')

def add(num1,num2):
add=num1+num2
print (add)

def sub(num1,num2):
sub=num1-num2
print(sub)

def mul(num1,num2):
mul=num1*num2
print(mul)

def div(num1,num2):
div=num1//num2
print(div)

if choice=='add':
add=num1+num2
print(add)

elif choice=='sub':
sub=num1-num2
print(sub)

elif choice=='mul':
mul=num1*num2
print(mul)

elif choice=='div':
div=num1//num2
print(div)

else:
print('option not available')

Python Operators and Conditional 15.07.2024

21 July 2024 at 15:49

Operators
Operator and Conditions

Add +
Sub -
Mul *
Div // floor division
Mod % to get remainder
Exponent **

eg:
a=int(input('Enter value for a '))
b=int(input('Enter value for b '))

add=a+b
print(add)

sub=a-b
print(sub)

mul=a*b
print(mul)

div=a//b
print(div)

mod=a%b
print(mod)

exp=2 ** 3 #2 power 3
print(exp)

Condition
if
else
elif

eg1:Calculator prgm

num1=float(input('Enter value for num1 '))
num2=float(input('Enter value for num2 '))
choice=input('Operation to be done:add/sub/mul/div/mod ')

if choice=='add':
add=num1+num2
print(add)

elif choice=='sub':
sub=num1-num2
print(sub)

elif choice=='mul':
mul=num1*num2
print(mul)

elif choice=='div':
div=num1//num2
print(div)

elif choice=='mod':
mod=num1%num2
print(mod)

elif choice=='exp':
exp=num1**num2
print(exp)

else:
print('option not available')

eg2:Pass or Fail
Using OR operator

mark=int(input('Enter your Mark: '))

if mark >= 91 or mark==100:
print('Grade A')
elif mark > 81 or mark==90:
print('Grade B')
elif mark >= 71 or mark==80:
print('Grade C')
elif mark > 61 or mark==70:
print('Grade D')
elif mark >= 46 or mark==60:
print('Grade E')
elif mark <= 45:
print('Fail')
else:
print('Mark value is invalid')

Using AND operator
mark=int(input('Enter your Mark: '))

if mark >= 91 mark <=100:
print('Grade A')
elif mark > 81 mark <=90:
print('Grade B')
elif mark >= 71 mark <=80:
print('Grade C')
elif mark > 61 mark<=70:
print('Grade D')
elif mark >= 46 mark<=60:
print('Grade E')
elif mark <= 45:
print('Fail')
else:
print('Mark value is invalid')

Conditionals:

For Condition Check in Python,we can use 0 or 1
0 means false -1/1 means True

eg:
Passmark=int(input('Enter your mark: '))

if Passmark >45 :
print('Pass')
else:
print('Fail')

Global Variable-accesed with anywhere in the program
Local Variable-can be accessed only with function of the program
eg:Global Variable

Tiffan='IdlySambar' #global variable

def Morningmenu1(): #def function
Tiffan='Kitchadi' #local variable
print(Tiffan)

def Morningmenu2():
print(Tiffan)

Morningmenu1() #methodcalling
Morningmenu2()

Python tutorial 11.07.2024

11 July 2024 at 12:14
  1. Numeric Types (int, float, complex) whole number-integers decimal number-float real+imaginary number-complex(space is not mandatory)eg:5+2j or 5 + 2j both are same

to check what datatype we can use type()
eg:type(1)
o/p int

  1. Text Type (strings)
    strings-collection of charcters,numbers,space
    using quotation we can represent a string

  2. Boolean Type (bool)
    True
    False
    if loop is active or not

  3. None Type (None)
    None-we cannot create a empty variable

  4. How to check a data type ?
    By using type()

  5. What is a variable ?
    container of data value

  6. How to define it

  7. valid, invalid variables
    can start or join with underscore _
    no special characters

  8. assigning values
    eg:var=123
    AB 13

  9. multiple assignment
    eg: name,age='AB',13 -->tuple datatype
    print(name,age)
    o/p:AB 13

  10. unpacking
    eg:emp_name,emp_id=AB,1001,152
    print(emp_name,emp_id)
    o/p: ValueError: too many values to unpack

  11. variable types
    from above eg1:print(type(emp_name))
    o/p:class str
    eg1:print(type(emp_id))
    o/p:class int

  12. Constants
    defining a value that remains same throughout the end of the progam.
    eg:PI=3.14 this is a constant value
    constant value defined by CAPITAL LETTER

NOTE:
Python is case sensitive
dynamic datatype will allocate different memory

is used for comments

Python tutorial (#print #printcommand #python)10.07.2024

10 July 2024 at 11:23

sep operator(used to seperate word with sepearte with spcial characters like-,*)

concatenation-add two strings

escape sequence-used to print pattern

Escape sequences allow you to include special characters in strings.
To do this, simply add a backslash () before the character you want to escape.

Raw string-used to print what exactly to be printed. this helps to print systempath

In python,whatever input is given output will be a string so we need to do casting

we cannot print string and integer together
eg;
print('abc'+123)
this gives an error so we need todo typecasting

print('abc'+str(123))
o/p abc123

printing with single,double,triple quote

String Multiplication-we can multiply single word with '*'
eg;
print('hello '*5)

Format
name='ABC'
print('My name is '+name)

❌
❌