Basic Python for DBA – part 2
Function in python
script
def currency_converter(rate,euros):
dollars=euros*rate
return dollars
print(currency_converter(100,1000))
def minutes_to_hours(minutes):
hours = minutes / 60
return hours
print(type(minutes_to_hours(70)))
def minutes_to_hour(seconds,minutes=70):
hours = minutes / 60 +seconds / 3600
return hours
print(minutes_to_hours(300))
def age_foo(age):
new_age=float(age)+50
return new_age
age = input(“Enter your age: “)
print(age_foo(age))
Output:
100000
<class ‘float’>
5.0
Enter your age: 30
80.0
File handling in python
script:
file=open(“example.txt”,’w’)
file.write(“Line 0\n”)
print(“My first file write”)
file.close()
file=open(“example.txt”,’a’)
file.write(“Line 1\n”)
file.write(“Line 2\n”)
print(“My Second file write”)
file.close()
file=open(“example.txt”,’a’)
l=[“Line 3″,”Line 4″,”Line 5”]
for item in l:
file.write(item+”\n”)
print(“My 3rd file write”)
file.close()
file=open(“example.txt”,’a’)
file.write(“Line 6”)
print(“My 4th file write in apped mode”)
file.close()
file= open(“example.txt”,’r’)
content=file.read()
print(“My first time file read”)
print(content)
file= open(“example.txt”,’r’)
content=file.readlines()
for i in content:
content=i.rstrip(“\n”)
print(“My second time file read”)
print(content)
file.close()
output:
My first file write
My Second file write
My 3rd file write
My 4th file write in apped mode
My first time file read
Line 0
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
My second time file read
Line 6
Commenting code block
script:
“””
This script creates empty files
“””
###comenting
print(“This is test for checking comment”)
output:
This is test for checking comment
Handing Date and Time
script:
import datetime
x = datetime.datetime.now()
print(x)
print(x.year)
print(x.strftime(“%A”))
x = datetime.datetime(2020, 5, 17)
print(x)
x = datetime.datetime(2018, 6, 1)
print(x.strftime(“%B”))
output:
2020-08-31 20:17:42.719442
2020
Monday
2020-05-17 00:00:00
June