Python Basics
Python Basics
88/11
Out[8]: 8.0
Data Types
In [9]: #modulo operator gives the remainder of a divison
Common data types include:
14 % 3
int (for integer) Out[9]: 2
float
str (for string)
In [10]: #power
list 3**2
tuple
dict (for dictionary) Out[10]: 9
set
bool (for Boolean True/False) In [11]: #Order of operation pemdas
2+3*10+5
Out[11]: 37
In [50]: from [Link] import Image, display
display(Image(filename='C:/Users/Gayathri/Pictures/Screenshots/data_type.pn
g')) In [1]: (2+3)*(10+5)
Out[1]: 75
Variable Assignment
Variables must start be written in lowercase
Should not start with either a number or a symbol
Must not contain keywords
Spaces are not allowed and should be represented by an underscore
Python is dynamically typed which means the same variable name can be assigned to different data types
or values i.e reassignment
In [2]: a = 5
Numbers
In [3]: a
In [6]: #integer
Out[3]: 5
2+3
Out[6]: 5 In [4]: a = 20
Out[7]: 40
In [8]: a = "Snape" In [29]: mul
Out[29]: 12
In [9]: a
Python lets you add, subtract, multiply and divide numbers with reassignment using +=, -=, *=, and Out[31]: 2.0
/= .
In [27]: sub
Out[27]: 8
In [28]: mul = 3
Out[71]: 'bcdefghijkl'
In [61]: st = 'sequence of char'
len(st)
In [73]: cur_str[:10] #from the start till j
Out[61]: 16
Out[73]: 'abcdefghij'
Out[74]: 'abcdefghijkl'
Strings have an index value starting from 0.
01234
In [76]: cur_str[2:6] #go from c all the way till f with a default step size of 1
Out[63]: 'Manifestation' In [77]: cur_str[2:6:2] #go from c all the way till f with a step size of 12
Out[77]: 'ce'
In [64]: my_string[0]
Out[79]: 'abcdefghijk'
In [80]: cur_str[-1:] #display only last letter In [91]: fun_str = 'I am an AI Engineer'
fun_str
Out[80]: 'l'
Out[91]: 'I am an AI Engineer'
In [81]: cur_str [::-1] #String reversal
In [92]: fun_str.upper()
Out[81]: 'lkjihgfedcba'
Out[92]: 'I AM AN AI ENGINEER'
In [93]: fun_str.lower()
String is immutable
Out[93]: 'i am an ai engineer'
The elements in a string cannot be changed or replaced once it is assigned
In [84]: s_first = s[1:] #use slicing to change the element String Formatting
s_first
Out[84]: 'lue'
String formatting helps to inject the items into a string i.e interpolation instead of chaining them through a plus
In [86]: #String concatenation sign i.e. concatenation
s = 'c' + s_first
s There are three ways
Out[87]: 'raiseabove'
%s and %r used to convert anything to a string. Similarly str() and repr() function is used for string
representation. Multiple formatting
%r is used to include the apostrophe and escape sequences in the output whereas %s shows the output
In [16]: print("Alex has %d barrels of %s weighing around %3.3f litres" %(2.2,'liquo
displaying the intended functionality of the apostrophe and escape sequences. r',5.78190))
In [6]: print("This is a work of %s" %'art') Alex has 2 barrels of liquor weighing around 5.782 litres
print("This is a work of %r" %'art')
%s converts any integer, float to a string In [17]: print("The {2} {0} {1} ".format('brown','fox','quick'))
%d converts any number to a integer with a roundoff
The quick brown fox
In [11]: print("Earthquake magnitude was around %1.0f richter" %6.2360) Alignment , padding and precision with float
veggies | quantity In .format() method, 10.4f gives 10 characters to before decimal point (incase of less than 10 characters ,
Onion | 12 whitespace is added) and 4 digits after the decimal point (incase of more digits, it is rounded off whereas if it
Tomato | 10 is less, padding is done)
We can include < , ^ , > assignment for left , center, right alignment In f string literals ,the same 10.4f is represented by {10.6} Here 6 is the number of digits required in total and
there is no padding
In [27]: print("{0:<11} | {1:^8} | {2:>15}".format('veggies','quantity','price'))
print("{0:<11} | {1:^8} | {2:>15}".format('Onion',12,24)) In [35]: weight = 23.45678
print("{0:<11} | {1:^8} | {2:>15}".format('Tomato',10,30)) print("Her weight is around {0:10.4f}".format(23.45678))
print(f"Her weight is around {weight:{10.6}}")
veggies | quantity | price
Onion | 12 | 24 Her weight is around 23.4568
Tomato | 10 | 30 Her weight is around 23.4568
We can also include padding character along with alignment We can also use 10.4f method in f string literal
In [28]: print("{0:=<11} | {1:-^8} | {2:+>15}".format('veggies','quantity','price')) In [39]: # do not forget to remove the curly braces around width and precision while
print("{0:=<11} | {1:-^8} | {2:+>15}".format('Onion',12,24)) using .format method in a f-string literal
print("{0:=<11} | {1:-^8} | {2:+>15}".format('Tomato',10,30)) weight = 23.45
print(f"Her weight is around {weight:10.4f}")
veggies==== | quantity | ++++++++++price
Onion====== | ---12--- | +++++++++++++24 Her weight is around 23.4500
Tomato===== | ---10--- | +++++++++++++30
Lists
Formatting using string literals
We can pass the variables instead of arguments in f string literals Creation of lists
Lists can have elements of same data type or different data [Link] are ordered sequence of characters.
In [31]: name = 'Gary'
print(f"My name is {name}" )
In [43]: my_list1 = [1,2,3]
My name is Gary
In [44]: my_list2 = ['Arithmetic',5,0.28] In [59]: # we can add two lists together
In [46]: my_list1
Out[46]: [1, 2, 3]
List duplication
In [47]: #length function is used to find the length of the list The * is used to duplicate elements in a list
len(my_list1)
Out[60]: ['Arithmetic',
5,
0.28,
Indexing and slicing of lists 'elbow',
'shire',
Index position starts from 0. 0,
9.45,
In [48]: my_list2[2] 'sequel',
2356,
Out[48]: 0.28 'Arithmetic',
5,
0.28,
In [50]: my_list3 = ['elbow','shire',0,9.45,'sequel',2356]
'elbow',
'shire',
my_list3[2:]
0,
Out[50]: [0, 9.45, 'sequel', 2356] 9.45,
'sequel',
2356]
In [51]: my_list3[:4]
Out[64]: 'added permanently' Out[82]: ['Arithmetic', 5, 0.28, 'elbow', 'shire', 0, 9.45, 'sequel', 2356]
In [65]: my_list1
In [83]: my_list1
Sort Out[83]: [1, 2, 3]
sort() method to sort the list in alphabetical or ascending order
In [84]: my_list1[2] = 4
Out[85]: [1, 2, 4]
In [67]: name_list.sort()
In [68]: name_list
Nested lists
Out[68]: ['d', 'i', 'o', 'r', 'x']
In [86]: lst1 = [1,2,3]
In [69]: num_list.sort()
In [87]: lst2 = [4,5,6]
In [70]: num_list
In [73]: newest_list.sort() #sort method not supported when there are different obje Out[90]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
cts in a list
In [91]: listed[0][1] #to get the number 2
--------------------------------------------------------------------------
- Out[91]: 2
TypeError Traceback (most recent call las
t)
<ipython-input-73-fb62abb9f973> in <module> In [92]: listed[2][0] #to get the number 7
----> 1 newest_list.sort() #sort method not supported when there are diffe Out[92]: 7
rent objects in a list
Dictionaries
Reverse
Dictionaries are unordered sequence of elements. They follow key value pairs.
In [79]: newest_list.reverse() # this is permanent
In [105]: dict1['key1'] = 'sound'
When to use a dictionary and list? dict1
Dictionary is used when we need quick retrival of data whereas list is used when we need to know the
Out[105]: {'key1': 'sound'}
location of data
In [96]: my_dict3
Out[96]: {'name': 'Gayathri', Similarly other arithmetic operations such as additon,subtraction, multiplication , division can also be done on
'age': 27, dictionaries
'weight': 68.35,
'scores': [91, 92, 93],
In [112]: dict2 = {'k1':34,'k2':56}
'dict': {'k1': 'good', 'k2': 11, 'k3': 9.1}}
dict2
Out[98]: 'Gayathri'
In [113]: dict2['k1'] = dict2['k1']-21
In [100]: my_dict3['scores'][1]
In [115]: dict2
Out[100]: 92
Out[115]: {'k1': 13, 'k2': 56}
In [101]: my_dict3['dict']
Out[101]: {'k1': 'good', 'k2': 11, 'k3': 9.1} Assignment operation can also be done
In [117]: [Link]()
Adding elements to a dictionary [Mutable]
Out[117]: dict_keys(['key1', 'key2'])
Out[104]: {}
In [119]: [Link]() In [6]: #Indexing
tup3[2]
Out[119]: dict_items([('key1', 'sound'), ('key2', 'horn')])
Out[6]: 3
In [7]: tup3[3][1]
Nested dictionaries
Out[7]: 6
In [122]: new_dict = {'outkey':{'inkey':{'innerkey':100}}}
new_dict In [8]: tup3[-1]
Out[122]: {'outkey': {'inkey': {'innerkey': 100}}} Out[8]: [5, 6, 7]
Out[14]: (1, 1, 4, 7, 9, 3, 5, 5)
Tuples are ordered sequence of characters similar to lists
Tuples are immutable that is they cannot be changed In [15]: #Index method allows only the display of position of first occurence of the
Tuples have only two methods element
[Link](5)
Tuples can have more than one object type
Out[15]: 6
Out[32]: True
In [18]: set1 = set() #empty set
In [33]: a = None
In [19]: set1 print(a)
Out[20]: {2}
I/O Files
In [22]: [Link](3)
IPython writing a file
In [23]: set1
In [3]: %%writefile [Link]
Out[23]: {2, 3} Hi, this is my first time creating a file in python
Writing [Link]
In [24]: [Link](2) #set only takes unique objects
set1
Out[24]: {2, 3}
Opening a python file
In [25]: [Link]('struck')
In [5]: #Saved in the same directory as the .py script
fileopen = open('[Link]')
In [26]: set1
The output is a blank space because the cursor is at the end of the line and we are supposed to make it point
to the beginning of the document so that it can reread.
Boolean
In [8]: [Link](0) #argument 0 shows the beginning of the line i.e start of f
ile at index 0
Boolean has two values 'True' and 'False' meaning 1 and 0. It also has a placeholder value 'None'
Out[8]: 0
In [14]: # 'w' and 'w+' lets you read and write into a file
In [28]: [Link]()
myfile = open('[Link]','w+')
Out[15]: 30 In [32]: [Link]() #the lines written before `w` operation have been deleted
Out[16]: ''
Appending to a file
In [17]: [Link](0)
[Link]() Passing the argument 'a' opens the file and puts the pointer at the end, so anything written is appended. Like
Out[17]: 'This is an open ended argument' 'w+', 'a+' lets us read and write to a file. If the file does not exist, one will be created.
Out[23]: 26
In [37]: print([Link]())
In [26]: [Link](0) ['What is gonna happen here?\n', 'Who knows and who cares?\n', 'Do you?']
Out[26]: 0
In [38]: [Link](0)
print([Link]())
In [45]: myfile = open('[Link]') != If values of two operands are not equal, then (a != b) is true
[Link]() condition becomes true.
Out[45]: 'What is gonna happen here?\nWho knows and who cares?\nDo you? So this > If the value of left operand is greater than the value of (a > b) is not true.
is happiness\n' right operand, then condition becomes true.
In [46]: [Link]() < If the value of left operand is less than the value of (a < b) is true.
right operand, then condition becomes true.
>= If the value of left operand is greater than or equal to (a >= b) is not true.
Iterating through a file the value of right operand, then condition becomes
true.
In [48]: for jjk in open('[Link]'): <= If the value of left operand is less than or equal to the (a <= b) is true.
print(jjk) value of right operand, then condition becomes true.
The above statement checks if 1 was less than 2 and if 2 was less than 3. We could have written this using
Out[2]: True
The and is used to make sure two checks have to be true in order for the total check to be true. Let's see
another example:
Out[3]: True
The above checks if 3 is larger than both of the other numbers, so you could use and to rewrite it as:
Out[4]: True
It's important to note that Python is checking both instances of the comparisons. We can also use or to write
comparisons in Python. For example:
Out[5]: True
Note how it was true; this is because with the or operator, we only need one or the other to be true. Let's see
one more example to drive this home:
Out[6]: True