Basic Python for DBA – part 1
The following cheat scripts can be referred to learn basic python quickly
You can validate in Jupyter Notebook
Variables in python
Script:
my_string = 'Hello, World!'
my_flt = 45.06
my_bool = 5 > 9 #A Boolean value will return either True or False
my_list = ['item_1', 'item_2', 'item_3', 'item_4']
my_tuple = ('one', 'two', 'three')
my_dict = {'letter': 'g', 'number': 'seven', 'symbol': '&'}
print(my_string)
print(my_flt)
print(my_bool)
print(my_list)
print(my_tuple)
print(my_dict)
Output:
Hello, World!
45.06
False
['item_1', 'item_2', 'item_3', 'item_4']
('one', 'two', 'three')
{'letter': 'g', 'number': 'seven', 'symbol': '&'}
General Strings in python
Script:
print("Sammy" * 9)
my_str = "Sammy likes declaring strings."
print(my_str)
print("Sammy says, \"Hello!\"")
print('Sammy\'s balloon is red.')
print("""This string spans multiple lines.""")
print(r"Sammy says,\"The balloon\'s color is red.\"")
Output:
SammySammySammySammySammySammySammySammySammy
Sammy likes declaring strings.
Sammy says, "Hello!"
Sammy's balloon is red.
This string spans multiple lines.
Sammy says,\"The balloon\'s color is red.\"
Different String operations in python
Script:
ss = "Sammy Shark"
print(ss.upper())
print(ss.lower())
number = "5"
letters = "abcdef"
print(number.isnumeric())
print(letters.isnumeric())
open_source = "Sammy contributes to open source."
print(len(open_source))
balloon = "Sammy has a balloon."
print(" ".join(balloon))
print("".join(reversed(balloon)))
print(",".join(["sharks", "crustaceans", "plankton"]))
print(balloon.split())
print(balloon.split("a"))
print(balloon.replace("has","had"))
Output:
SAMMY SHARK
sammy shark
True
False
33
S a m m y h a s a b a l l o o n .
.noollab a sah ymmaS
sharks,crustaceans,plankton
['Sammy', 'has', 'a', 'balloon.']
['S', 'mmy h', 's ', ' b', 'lloon.']
Sammy had a balloon.
Other Strings operation in python
Script:
ss = "Sammy Shark!"
print(ss[4])
print(ss[-3])
print(ss[6:11])
print(ss[:5])
print(ss[7:])
print(ss[-4:-1])
print(ss[0:12:2])
print(ss[0:12:4])
print(ss.count("a"))
likes = "Sammy likes to swim in the ocean, likes to spin up servers, and likes to smile."
print(likes.count("likes"))
print(ss.find("m"))
Output:
y
r
Shark
Sammy
hark!
ark
SmySak
Sya
2
3
2
String Formatting
script:
print("Sammy has {} balloons.".format(5))
open_string = "Sammy loves {}."
print(open_string.format("open source"))
new_open_string = "Sammy loves {} {}." #2 {} placeholders
print(new_open_string.format("open-source", "software"))
#Pass 2 strings into method, separated by a comma
print("Sammy the {} has a pet {}!".format("shark", "pilot fish"))
print("Sammy the {1} has a pet {0}!".format("shark", "pilot fish"))
sammy = "Sammy has {} balloons today!"
nBalloons = 8
print(sammy.format(nBalloons))
output:
Sammy has 5 balloons.
Sammy loves open source.
Sammy loves open-source software.
Sammy the shark has a pet pilot fish!
Sammy the pilot fish has a pet shark!
Sammy has 8 balloons today!
Data Type Conversion
script:
f = 57
print(float(f))
b = 125.0
c = 390.8
print(int(b))
print(int(c))
user = "Sammy"
lines = 50
print("Congratulations, " + user + "! You just wrote " + str(lines) + " lines of code.")
Output:
57.0
125
390
Congratulations, Sammy! You just wrote 50 lines of code.
Tuples basic
script: t_first=(10,20,30) t_second=(40,50,60) t_combine=t_first+t_second print(t_combine) t_concat=t_combine*3 print(t_concat) var1=t_combine[2] print(var1) var2=t_combine[0:3] print(var2) print(len(t_combine)) len_tup=len(t_combine) var3=t_combine[3:len_tup] print(var3) output:
(10, 20, 30, 40, 50, 60)
(10, 20, 30, 40, 50, 60, 10, 20, 30, 40, 50, 60, 10, 20, 30, 40, 50, 60)
30
(10, 20, 30)
6
(40, 50, 60)
List Basic
script:
my_list=[(1,2,3),('A','B','C'),(True,False)]
print(my_list)
print(my_list[0])
my_list.extend([7,8])
print(my_list)
my_list.insert(1,'DEBASIS')
print(my_list)
output:
[(1, 2, 3), ('A', 'B', 'C'), (True, False)]
(1, 2, 3)
[(1, 2, 3), ('A', 'B', 'C'), (True, False), 7, 8]
[(1, 2, 3), 'DEBASIS', ('A', 'B', 'C'), (True, False), 7, 8]
Complex List operations
script:
fish = ['barracuda','cod','devil ray','eel']
fish.append('flounder')
print(fish)
fish.insert(0,'anchovy')
print(fish)
more_fish = ['goby','herring','ide','kissing gourami']
fish.extend(more_fish)
print(fish)
fish.remove('kissing gourami')
print(fish)
print(fish)
print(fish.index('herring'))
fish_2 = fish.copy()
print(fish_2)
fish.reverse()
print(fish)
print(fish.count('goby'))
fish_ages = [1,2,4,3,2,1,1,2]
print(fish_ages.count(1))
fish_ages.sort()
print(fish_ages)
fish.clear()
print(fish)
output:
['barracuda', 'cod', 'devil ray', 'eel', 'flounder']
['anchovy', 'barracuda', 'cod', 'devil ray', 'eel', 'flounder']
['anchovy', 'barracuda', 'cod', 'devil ray', 'eel', 'flounder', 'goby', 'herring', 'ide', 'kissing gourami']
['anchovy', 'barracuda', 'cod', 'devil ray', 'eel', 'flounder', 'goby', 'herring', 'ide']
['anchovy', 'barracuda', 'cod', 'devil ray', 'eel', 'flounder', 'goby', 'herring', 'ide']
7
['anchovy', 'barracuda', 'cod', 'devil ray', 'eel', 'flounder', 'goby', 'herring', 'ide']
['ide', 'herring', 'goby', 'flounder', 'eel', 'devil ray', 'cod', 'barracuda', 'anchovy']
1
3
[1, 1, 1, 2, 2, 2, 3, 4]
[]
List to Tuple and Tuple to List Conversion
script:
my_tuple=(10,20,30,40,50)
lst=list(my_tuple)
cnt=0
for i in lst:
i=i+10
lst[cnt]=i
cnt=cnt+1
my_tuple=tuple(lst)
print(my_tuple)
output:
(20, 30, 40, 50, 60)
Dictionary
script:
my_dict={'FRUIT':('APPLE','BANNANA','MANGO','GUAVA'),'cost':(85,54,120,70)}
print(my_dict)
print(my_dict['FRUIT'])
print(my_dict.keys())
print(my_dict.values())
output:
{'FRUIT': ('APPLE', 'BANNANA', 'MANGO', 'GUAVA'), 'cost': (85, 54, 120, 70)}
('APPLE', 'BANNANA', 'MANGO', 'GUAVA')
dict_keys(['FRUIT', 'cost'])
dict_values([('APPLE', 'BANNANA', 'MANGO', 'GUAVA'), (85, 54, 120, 70)])
SET operations
script:
my_Set={1,1,'A','A',True,True}
print(my_Set)
output:
{1, 'A'}
Import module
script:
import random
for i in range(10):
print(random.randint(1, 25))
output:
14
1
3
4
7
10
1
9
11
10
Conditional loop
script:
a = 5
if a < 5:
print("less than 5")
else:
print("equal or greater than 5")
if a < 5:
print("less than 5")
elif a == 5:
print("equal or greater than 5")
else:
print("Greater than 5")
def age_foo(age):
new_age=float(age)+50
return new_age
age =float( input("Enter your age: "))
if age < 150:
print(age_foo(age))
else:
print("How is that possible!")
output:
equal or greater than 5
equal or greater than 5
Enter your age: 130
180.0
For Loop
script:
emails=['we@gmail.com','you@gmail.com','we@gmail.com']
for email in emails:
print(email)
emails=['we@gmail.com','you@gmail.com','we@gmail.com']
for item in emails:
if 'gmail' in item:
print(item)
my_list1=[1,2,3,4,5,6]
my_list2=[6,5,4,3,2,1]
cnt=0
for l1 in my_list1:
if l1>my_list2[cnt]:
print("L1 element value "+str(l1)+ " greater than "+ str(my_list2[cnt]))
if l1<my_list2[cnt]:
print("L1 element value "+str(l1)+ " less than "+ str(my_list2[cnt]))
cnt=cnt+1
output:
we@gmail.com
you@gmail.com
we@gmail.com
we@gmail.com
you@gmail.com
we@gmail.com
L1 element value 1 less than 6
L1 element value 2 less than 5
L1 element value 3 less than 4
L1 element value 4 greater than 3
L1 element value 5 greater than 2
L1 element value 6 greater than 1
Input
script:
planet=input("Enter you planet:")
print(planet)
def currency_converter(rate,euros):
dollars=euros*rate
return dollars
r=input("Enter rate: ")
e=input("Enter euro: ")
currency_converter(float(r),float(e))
output:
Enter you planet:8 8 Enter rate: 50 Enter euro: 5 250.0
While loop
script:
password=' '
while password != 'python123':
password=input("Enter password: ")
if password == 'python123':
print("You are logged in!")
else:
print("Sorry,try again!")
output:
Enter password: python
Enter password: python123
You are logged in!
For in list
script:
names=['james','john','jack']
email=['gmail','hotmail','yahoo']
for i,j in zip(names,email):
print(i,j)
output:
james gmail
john hotmail
jack yahoo
