SlideShare a Scribd company logo
1 of 54
Download to read offline
In [ ]:
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for:
In [ ]:
web development (server-side),
software development,
mathematics,
system scripting.
What can Python do?
In [ ]:
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software development.
Why Python?
In [ ]:
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some other program
ming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is written. T
his means that prototyping can be very quick.
Python can be treated in a procedural way, an object-orientated way or a functional way.
In [3]:
print("Hello World !")
In [ ]:
Hello World !
Let's Check the Rules in Naming a Variable
Rule 1: A Variable name must start with a letter or Underscore
Rule 2: A Variable name cannot start with a number
Rule 3: A Variable name can only contain alphanumeric characters and underscores
Rule 4: Variable names are Case Sensitive
In [9]:
_a = 5
String = 8
string = 88
#8x = 9
print(_a)
print(String)
print(string)
Creating Variables
Variables are containers solely used for storing data values.
Python has no command for declaring a variable, ie., there is no declaration of variables.
A variable is created the moment you first assign a value to it.
In [2]:
x = 10
y = 15.6
z = 'String'
Let's Print the Variables
In [3]:
print(x)
print(y)
print(z)
Let's Check the Datatype of the Variables
In [5]:
print(type(x))
print(type(y))
print(type(z))
Let's Assign Multiple Values to Multiple Variables at one time
5
8
88
10
15.6
String
<class 'int'>
<class 'float'>
<class 'str'>
Let's Assign Multiple Values to Multiple Variables at one time
In [10]:
x, y, z = 10, 15.6, 'String'
print(type(x))
print(type(y))
print(type(z))
Let's Check how to Output the Variables
In [18]:
# for Integer and Float we can use comma to output the variables
x = 1056.88
y = 89
print("The Value of x is : ", x)
print("The Value of y is : ", y)
In [20]:
# for Strings we can use both '+' and ',' to output the variables
x = "String"
print("The Value of x is : "+ x)
print("The Value of x is : ", x)
Concatenation of Variables in Python
In [25]:
# let's first check the string concatenation
x = 'Python'
y = 'is'
z = 'Love'
a = x+y+z
print(a)
b = x+" "+y+" "+z
print(b)
In [27]:
# now, let's check the integer and float concatenation
x = 10
y = 15
a = x + y
print(a) # here, the '+' symbol will act as an arithmetic operation for addition and not concatena
tion
<class 'int'>
<class 'float'>
<class 'str'>
The Value of x is : 1056.88
The Value of y is : 89
The Value of x is : String
The Value of x is : String
PythonisLove
Python is Love
In [33]:
# let's try to concatenate strings and Integer/floats
x = 'My Age is'
y = 8
#z = x+y
#print(z)
#Expected : Type Error, Cannot Concatenate String and Integer
In [1]:
# the above programs produces an error because we cannot concatenate a string and an Integer
# but using the format function we can concatenate them
x = 'My Age is {} and cgpa is {}'
print(x.format(8, 6))
Global Variables
Global Variables are Variables which are created Outside of the Function. But, They can accessed from anywhere.
In [36]:
x = 89.63
def function():
print(x)
function() # here, we are able to access variable from outside of the variable
In [38]:
x = 8956454.23
def function():
x = 78
print(x)
function() # here, we are able to access the local variable
The Global Keyword
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
To create a global variable inside a function, you can use the global keyword.
In [41]:
def function():
global x
x = "fantastic"
print(x)
function()
25
My Age is 8 and cgpa is 6
89.63
78
function()
fantastic
Built in Data Types
Python has the following data types built-in by default, in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
Getting the Data Type of the Variable
In [3]:
x = 156
print(type(x))
In [2]:
y = 8.96
print(type(y))
In [4]:
z = 'string'
print(type(z))
In [5]:
a = 1j
print(type(a))
In [6]:
b = ['apple','ball','cat']
print(type(b))
In [3]:
b = set(('apple', 'ball'))
print(type(b))
In [7]:
c = ('apple','ball','cat')
<class 'int'>
<class 'float'>
<class 'str'>
<class 'complex'>
<class 'list'>
<class 'set'>
c = ('apple','ball','cat')
print(type(c))
In [8]:
d = {'Name': 'John', 'Age': 56, 'Salary': 78896.8}
print(type(d))
In [9]:
e = {"Dog","Cat",'Parrot'}
print(type(e))
In [11]:
f = frozenset({"Dog","Cat","Parrot"})
print(type(f))
In [12]:
g = True
print(type(g))
In [13]:
h = b"Hello"
print(type(h))
In [14]:
i = bytearray(85)
print(type(i))
In [16]:
j = memoryview(bytes(5))
print(type(j))
Setting the Data Types Specifically
In [18]:
x = int(3)
print(type(x))
<class 'tuple'>
<class 'dict'>
<class 'set'>
<class 'frozenset'>
<class 'bool'>
<class 'bytes'>
<class 'bytearray'>
<class 'memoryview'>
<class 'int'>
In [20]:
x = float(4.9)
print(type(x))
In [24]:
x = str('fish')
print(type(x))
In [25]:
x = list((7, 8, 9, 5))
print(type(x))
In [26]:
x = tuple((4, 5, 6, 8))
print(type(x))
In [6]:
x = range(5, 20)
x
In [31]:
x = dict(name="John", age=36)
print(type(x))
In [33]:
x = set(("Apple","Ball","Cat"))
print(type(x))
In [34]:
x = frozenset(("Red","Blue","Green"))
print(type(x))
In [36]:
x = bool(4)
print(type(x))
<class 'float'>
<class 'str'>
<class 'list'>
<class 'tuple'>
Out[6]:
range(5, 20, 2)
<class 'dict'>
<class 'set'>
<class 'frozenset'>
In [37]:
x = bytes(5)
print(type(x))
Typecasting
In [ ]:
x = 4
x = x.astype('float')
In [21]:
x = float(4)
x
In [38]:
x = 4
x = float(x)
print(type(x))
In [23]:
x = int(8.56)
x
Random Numbers
In [10]:
import random
# printing a random number from a specified range
print(random.randrange(1, 10))
In [11]:
# printing a random number in default range i.e., 0 to 1
print(random.random())
In [13]:
<class 'bool'>
<class 'bytes'>
Out[21]:
4.0
<class 'float'>
Out[23]:
8
8
0.9128538599745194
In [13]:
# printing a random integer number
print(random.randint(2, 10))
In [56]:
# printing specific number of random nuumbers
print(random.randn())
In [ ]:
9
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-56-97184c9f9038> in <module>
1 # printing specific number of random nuumbers
2
----> 3 print(random.randn())
AttributeError: module 'random' has no attribute 'randn'
Operators are used to perform operations on variables and
values.
Python Operators are divided into the following groups
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic Operators
'+' for Addition
'-' for Subtraction
'*' for Multiplication
'' for Divison
'' for floor divison
'%' for modulus
'**' for exponents
In [4]:
# addition of two numbers
x = 8
y = 9
z = x+y
print(z)
In [5]:
# subtraction of two numbers
x = 15
y = 10
z = x-y
print(z)
In [6]:
# multilpication of two numbers
x = 3
y = 9
z = x*y
print(z)
In [7]:
# division of two numbers
x = 27
y = 3
z = x/y
print(z)
17
5
27
print(z)
In [8]:
# floor division of two numbers
x = 34
y = 5
z = x//y
print(z)
In [1]:
# modulus of two numbers
x = 8
y = 3
z = x%y
print(z)
In [2]:
# exponent of a number
x = 8
y = 2
z = x**y
print(z)
Assignment Operators
'=' for assignment
'+=' for additive assignment
'-=' for subtractive assignment
'*=' for multiplicative assignment
'/=' for divisive assignment
'//=' for floor divisive assignment
'%=' for modulus assignment
'**=' for exponentiation assignment
'&=' for bitwise and assignment
'|=' for bitwise or assignment
'^=' for bitwise negation assignment
'>>=' for right shift assignment
'<<=' for left shift assignment
In [4]:
# assignment operator
x = 5
print(x)
In [10]:
# additive assignment
x = 50
9.0
6
2
64
5
x = 50
x += 5 # similar to x = x+5
print(x)
In [11]:
# subtractive assignment
x = 50
x -= 5
print(x)
In [13]:
# multiplicative assignment
x = 50
x *= 5
print(x)
In [15]:
# divisive assignement
x = 50
x /= 5
print(x)
In [18]:
# floor division assignment
x = 50
x //= 9
print(x)
In [19]:
## modulus assignment
x = 50
x %= 5
print(x)
In [30]:
# bitwise and assignment
x = 5
x &= 3
print(x)
55
45
250
10.0
5
0
1
In [29]:
# bitwise or assignment
x = 50
x |= 2
print(x)
In [49]:
# bitwise not assignment
x = 50
x ^= 2
print(x)
In [24]:
## left shift assignment
x = 8
x <<= 2
print(x)
In [25]:
# right shift assignment
x = 8
x >>= 2
print(x)
Comparison Operators
'==' for equal comparison
'!=' for not equal comparison
'>' for Greater than comparison
'<' for lesser than comparison
'>=' for Greater than equal to comparison
'<=' for Lesser than equal to comparison
In [50]:
# equal to comparison
x = 5
y = 9
print(x == y)
In [51]:
# not equal to comparison
x = 8
y = 9
50
48
32
2
False
y = 9
print(x!=y)
In [52]:
# greater than comparison
x = 5
y = 3
print(x>y)
In [53]:
# lesser than comparison
x = 5
y = 3
print(x<y)
In [54]:
# greater than equal to comparison
x = 5
y = 5
print(x>=y)
In [55]:
# lesser than equal to comparison
x = 5
y = 9
print(x<=y)
Logical Operators
'AND' Retuens true, If both the statements are True
'OR' returns true, If One of the Statements are True
'NOT' returns true, It will Reverse the Result.
In [56]:
# AND Operation
x = 10
y = 8
x > y and x > 5
In [57]:
True
True
False
True
True
Out[56]:
True
In [57]:
# OR Operation
x = 10
y = 5
x > 5 or y >8
In [60]:
# NOT Operation
x = 10
y = 5
not(x >= 10 and y == 5)
Identity Operators
is, Returns true, if both the objects are same
is not, Returns true, if both the objects are not the same
In [62]:
m = 5
n = 5
print(m is n)
In [63]:
m = ['apple','cat','ball']
n = ['apple','cat','ball']
print( m is n)
In [64]:
print(m == n)
In [65]:
print( m is not n)
Membership Operators
in, Returns True if a sequence with the specified value is present in the object
not in, Returns True if a sequence with the specified value is not present in the object
Out[57]:
True
Out[60]:
False
True
False
True
True
In [69]:
x = [2, 3, 4, 5, 6, 7]
y = [5]
z = [3, 4, 5]
a = 3
print(y in x)
print(z in x)
print(a in x)
Bitwise Operator
&, AND Operation
|, OR Operation
^, XOR Operation
~, NOT Operation
>>, Right Shift Operation
<<, Left Shift Operation
False
False
True
In [1]:
# Printing Strings into Python
print("Hello")
print('Hello')
In [1]:
x = "Chocolate"
x[-5:-2]
In [2]:
# Assigning Values to the String
a = "Hello"
print(a)
In [3]:
# Strings as Arrays
a = "Hello, World!"
print(a[1])
In [4]:
# Slicing
b = "Hello, World!"
print(b[2:5])
In [5]:
# Negative Indexing
b = "Hello, World!"
print(b[-5:-2])
In [6]:
# String Length
a = "Hello, World! 
kmlmlml"
b = '''kkmkmkm
nkjnkjnkjnkj
kjjn
Hello
Hello
Out[1]:
'ola'
Hello
e
llo
orl
kjjn
'''
print(len(a))
In [7]:
# Stripping a string
a = " Hello, World! "
print(a.strip())
In [8]:
# converting into lowercase
a = "Hello, World!"
print(a.lower())
In [9]:
# converting into uppercase
a = "Hello, World!"
print(a.upper())
In [10]:
# using replace function
a = "Hello, World!"
print(a.replace("H", "J"))
In [11]:
# Splitting a string
a = "Hello, World!"
print(a.split(","))
In [15]:
# String Formatting
age = 36
txt = "My name is John, I am {}"
print(txt.format(age))
Other Important Functions
capitalize() Converts the first character to upper case
13
Hello, World!
hello, world!
HELLO, WORLD!
Jello, World!
['Hello', ' World!']
My name is John, I am 36
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
In [ ]:
If Else
Conditional Statements
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
In [2]:
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In [3]:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In [4]:
# shorthand ifelse
if a > b: print("a is greater than b")
In [5]:
a = 2
b = 330
print("A") if a > b else print("B")
In [6]:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
In [7]:
a and b are equal
a is greater than b
a is greater than b
B
=
# and operation
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
In [8]:
# or operation
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
In [9]:
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
In [2]:
# if statements cannot be empty, but if you for some reason have an if statement
# with no content, put in the pass statement to avoid getting an error.
a = 33
b = 200
if b > a:
pass
While
With the while loop we can execute a set of statements as long as a condition is true.
In [12]:
i = 1
while i < 6:
print(i)
i += 1
With the break statement we can stop the loop even if the while condition is true:
Both conditions are True
At least one of the conditions is True
Above ten,
and also above 20!
1
2
3
4
5
In [13]:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
With the continue statement we can stop the current iteration, and continue with the next:
In [14]:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
With the else statement we can run a block of code once when the condition no longer is true:
In [16]:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
For
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like
the for keyword in other programming languages, and works more like an iterator method as found in other object-
orientated programming languages. With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc
In [17]:
# looping through a list
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
1
2
3
1
2
4
5
6
1
2
3
4
5
i is no longer less than 6
apple
banana
cherry
In [18]:
# looping through a string
for x in "banana":
print(x)
In [19]:
# using the break statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
In [20]:
# using the continue statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
In [21]:
# using th range() function
for x in range(7):
print(x)
In [22]:
# using the start parameter
for x in range(2, 6):
print(x)
cherry
b
a
n
a
n
a
apple
banana
apple
cherry
0
1
2
3
4
5
2
3
4
5
In [23]:
# incrementing the sequence
for x in range(2, 30, 3):
print(x)
In [24]:
# for and else
for x in range(6):
print(x)
else:
print("Finally finished!")
In [1]:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
2
5
8
11
14
17
20
23
26
29
0
1
2
3
4
5
Finally finished!
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
In [61]:
# Making a list
list = ["apple", "banana", "cherry"]
print(list)
In [62]:
# accessing the list
list = ["apple", "banana", "cherry"]
print(list[1])
In [63]:
# negative indexing
print(list[-1])
In [1]:
# accessing a range of lists
list = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(list[2:5])
In [65]:
print(list[-5:-2])
In [66]:
# reassigning the items in the list
list[1] = 'icecream'
print(list)
In [67]:
# reversing the list
print(list[::-1])
In [68]:
# concatinating two lists
list2 = ['potato', 'tomato']
list3 = list + list2
print(list3)
['apple', 'banana', 'cherry']
banana
cherry
['cherry', 'orange', 'kiwi']
['cherry', 'orange', 'kiwi']
['apple', 'icecream', 'cherry', 'orange', 'kiwi', 'melon', 'mango']
['mango', 'melon', 'kiwi', 'orange', 'cherry', 'icecream', 'apple']
print(list3)
In [69]:
# appending items to the list
list.append('cauliflower')
print(list)
In [70]:
# inserting items to the list
list.insert(0, 'brinjal')
print(list)
In [71]:
# removing items from the list
list.remove('brinjal')
print(list)
In [5]:
# extending items to the list
list.extend(['flower', 'app'])
print(list)
In [73]:
# sorting the list
list.sort()
print(list)
In [74]:
# applying pop operation
list.pop()
print(list)
In [75]:
# applying the remove operation
list.remove('l')
list.remove('f')
['apple', 'icecream', 'cherry', 'orange', 'kiwi', 'melon', 'mango', 'potato', 'tomato']
['apple', 'icecream', 'cherry', 'orange', 'kiwi', 'melon', 'mango', 'cauliflower']
['brinjal', 'apple', 'icecream', 'cherry', 'orange', 'kiwi', 'melon', 'mango', 'cauliflower']
['apple', 'icecream', 'cherry', 'orange', 'kiwi', 'melon', 'mango', 'cauliflower']
['apple', 'banana', 'cherry', 'orange', 'kiwi', 'melon', 'mango', 'flower', 'app']
['apple', 'cauliflower', 'cherry', 'e', 'f', 'icecream', 'kiwi', 'l', 'mango', 'melon', 'o', 'oran
ge', 'r', 'w']
['apple', 'cauliflower', 'cherry', 'e', 'f', 'icecream', 'kiwi', 'l', 'mango', 'melon', 'o', 'oran
ge', 'r']
list.remove('f')
list.remove('o')
print(list)
In [76]:
# copying the list
listcopy = list.copy()
print(listcopy)
In [77]:
# reversing the list using reverse function
list.reverse()
print(list)
In [78]:
# counting the elements in the list
x = list.count('orange')
print(x)
In [79]:
# using lists as stack (fifo)
stack = [2, 3, 4, 5, 6]
stack.append(7)
stack.append(8)
stack.append(9)
In [80]:
print(stack)
In [81]:
stack.pop()
stack.pop()
stack.pop()
print(stack)
In [82]:
# using lists as queue (lifo)
from collections import deque
queue = deque(['Ram', 'Shyam', 'Sita', 'Gita'])
print(queue)
['apple', 'cauliflower', 'cherry', 'e', 'icecream', 'kiwi', 'mango', 'melon', 'orange', 'r']
['apple', 'cauliflower', 'cherry', 'e', 'icecream', 'kiwi', 'mango', 'melon', 'orange', 'r']
['r', 'orange', 'melon', 'mango', 'kiwi', 'icecream', 'e', 'cherry', 'cauliflower', 'apple']
1
[2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6]
deque(['Ram', 'Shyam', 'Sita', 'Gita'])
In [83]:
queue.append('Rohan')
queue.append('Gopal')
print(queue)
In [84]:
queue.popleft()
print(queue)
In [39]:
# clearing the list
list.clear()
print(list)
In [1]:
# printing the items of a list
list = ["apple", "banana", "cherry"]
for x in list:
print(x)
In [3]:
# checking if the item exists or not
list = ["apple", "banana", "cherry"]
if "apple" in list:
print("Yes, 'apple' is in the fruits list")
In [1]:
x = [1, 3, 4]
y = [4, 5, 6]
In [ ]:
deque(['Ram', 'Shyam', 'Sita', 'Gita'])
deque(['Ram', 'Shyam', 'Sita', 'Gita', 'Rohan', 'Gopal'])
deque(['Shyam', 'Sita', 'Gita', 'Rohan', 'Gopal'])
[]
apple
banana
cherry
Yes, 'apple' is in the fruits list
Out[1]:
[1, 3, 4, 4, 5, 6]
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries
are written with curly brackets, and they have keys and values.
In [24]:
# creating a dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
In [31]:
thisdict["brand"] = 'Maruti'
thisdict['brand']
In [4]:
# accessing values
x = thisdict["model"]
x
In [6]:
# using the get() function
x = thisdict.get("model")
x
In [8]:
# updating the values
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
thisdict
In [9]:
# accessing the keys
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Out[31]:
'Maruti'
Out[4]:
'Mustang'
Out[6]:
'Mustang'
Out[8]:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
# accessing the keys
for x in thisdict:
print(x)
In [10]:
# accessing the values
for x in thisdict:
print(thisdict[x])
In [11]:
# using the values() to access the values in a dict
for x in thisdict.values():
print(x)
In [12]:
# accessing both the key and values
for x, y in thisdict.items():
print(x, y)
In [13]:
# checking if that particular string exists or not
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
In [33]:
# adding items to the list
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
thisdict["color"] = "blue"
thisdict["colors"] = "red"
print(thisdict)
brand
model
year
Ford
Mustang
2018
Ford
Mustang
2018
brand Ford
model Mustang
year 2018
Yes, 'model' is one of the keys in the thisdict dictionary
print(thisdict)
In [36]:
# removing the items from the dict
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("year")
print(thisdict)
In [38]:
# removing the last item from the dict
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
In [17]:
# using del keyword to remove the elements
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
In [40]:
# deleting the dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
In [19]:
# emptieing the dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'blue', 'colors': 'red'}
{'brand': 'Ford', 'model': 'Mustang'}
{'brand': 'Ford', 'model': 'Mustang'}
{'brand': 'Ford', 'year': 1964}
{}
In [43]:
# nested dictionary
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
child4 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
myfamily2 = {
"child4":child4,
}
family = {
"myfamily":myfamily,
"myfamily2":myfamily2,
}
family
In [23]:
# one dictionary containing multiple dictionaries
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
myfamily
In [25]:
{}
Out[43]:
{'myfamily': {'child1': {'name': 'Emil', 'year': 2004},
'child2': {'name': 'Tobias', 'year': 2007},
'child3': {'name': 'Linus', 'year': 2011}},
'myfamily2': {'child4': {'name': 'Linus', 'year': 2011}}}
Out[23]:
{'child1': {'name': 'Emil', 'year': 2004},
'child2': {'name': 'Tobias', 'year': 2007},
'child3': {'name': 'Linus', 'year': 2011}}
In [25]:
# creating a dictionary using the dict keyword
thisdict = dict(brand="Ford", model="Mustang", year=1964)
print(thisdict)
Dictionary Methods
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and values
get() Returns the value of the specified key
items() Returns a list containing the a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
In [10]:
## Q9. Take a Number and check whether a number is Prime or not
def primenumber(x):
if x>1:
for i in range(2,x//2):
if(x%i==0):
print("number is not prime")
break
else:
print("number is prime no")
else:
print('ff')
primenumber(7)
In [11]:
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
number is prime no
How many terms? 5
Fibonacci sequence:
0
In [17]:
string = "$ 50 M"
x = string.split()
int(x[1])
In [19]:
string = "$ 50 M"
string.split(' ')
In [ ]:
0
1
1
2
3
Out[17]:
50
Out[19]:
['$', '50', 'M']
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
In [7]:
# creating a class with a property named x
class MyClass:
x = 5
y = 6
In [8]:
# creating an object
p1 = MyClass()
print(p1.x)
print(p1.y)
The Init Function
The examples above are classes and objects in their simplest form, and are not really useful in real life applications.
To understand the meaning of classes we have to understand the built-in init() function.
All classes have a function called init(), which is always executed when the class is being initiated.
Use the init() function to assign values to object properties, or other operations that are necessary to do when the object is being
created:
In [10]:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 45)
print(p1.name)
print(p1.age)
Object Methods
In [5]:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
5
6
John
45
p1.myfunc()
The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the
class:
In [6]:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
In [8]:
# modifying the object properties
p1.age = 40
print(p1.age)
In [9]:
# deleting the object properties
del p1.age
print(p1.age)
In [31]:
class Cal:
def __init__(self, x, y, z, t, r):
self.x = x
self.y = y
self.z = z
self.t = t
self.r = r
def add(self):
print("Addition :", self.x+self.y)
def sub(self):
print("Subtraction :", self.x-self.y)
def mul(self):
print("Multiplication :", self.x*self.r)
def div(self):
print("Divison :", self.x/self.y)
def floor(self):
Hello my name is John
Hello my name is John
40
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-9-fdb3f776cdce> in <module>
3 del p1.age
4
----> 5 print(p1.age)
AttributeError: 'Person' object has no attribute 'age'
print("Floor Divison :", self.x//self.y)
def exp(self):
print("Exponentiation :", self.z**self.y)
a = Cal(3, 5, 5, 7, 4)
a.add()
a.sub()
a.mul()
a.div()
a.floor()
a.exp()
In [19]:
import pandas as p
In [21]:
help(p.read_csv)
Addition : 8
Subtraction : -2
Multiplication : 12
Divison : 0.6
Floor Divison : 0
Exponentiation : 3125
Help on function read_csv in module pandas.io.parsers:
read_csv(filepath_or_buffer:Union[str, pathlib.Path, IO[~AnyStr]], sep=',', delimiter=None,
header='infer', names=None, index_col=None, usecols=None, squeeze=False, prefix=None,
mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None,
false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None,
na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True,
parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None,
dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression='infer',
thousands=None, decimal=b'.', lineterminator=None, quotechar='"', quoting=0, doublequote=True,
escapechar=None, comment=None, encoding=None, dialect=None, error_bad_lines=True,
warn_bad_lines=True, delim_whitespace=False, low_memory=True, memory_map=False,
float_precision=None)
Read a comma-separated values (csv) file into DataFrame.
Also supports optionally iterating or breaking of the file
into chunks.
Additional help can be found in the online docs for
`IO Tools <http://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_.
Parameters
----------
filepath_or_buffer : str, path object or file-like object
Any valid string path is acceptable. The string could be a URL. Valid
URL schemes include http, ftp, s3, and file. For file URLs, a host is
expected. A local file could be: file://localhost/path/to/table.csv.
If you want to pass in a path object, pandas accepts any ``os.PathLike``.
By file-like object, we refer to objects with a ``read()`` method, such as
a file handler (e.g. via builtin ``open`` function) or ``StringIO``.
sep : str, default ','
Delimiter to use. If sep is None, the C engine cannot automatically detect
the separator, but the Python parsing engine can, meaning the latter will
be used and automatically detect the separator by Python's builtin sniffer
tool, ``csv.Sniffer``. In addition, separators longer than 1 character and
different from ``'s+'`` will be interpreted as regular expressions and
will also force the use of the Python parsing engine. Note that regex
delimiters are prone to ignoring quoted data. Regex example: ``'rt'``.
delimiter : str, default ``None``
Alias for sep.
header : int, list of int, default 'infer'
Row number(s) to use as the column names, and the start of the
data. Default behavior is to infer the column names: if no names
are passed the behavior is identical to ``header=0`` and column
names are inferred from the first line of the file, if column
names are inferred from the first line of the file, if column
names are passed explicitly then the behavior is identical to
``header=None``. Explicitly pass ``header=0`` to be able to
replace existing names. The header can be a list of integers that
specify row locations for a multi-index on the columns
e.g. [0,1,3]. Intervening rows that are not specified will be
skipped (e.g. 2 in this example is skipped). Note that this
parameter ignores commented lines and empty lines if
``skip_blank_lines=True``, so ``header=0`` denotes the first line of
data rather than the first line of the file.
names : array-like, optional
List of column names to use. If file contains no header row, then you
should explicitly pass ``header=None``. Duplicates in this list are not
allowed.
index_col : int, str, sequence of int / str, or False, default ``None``
Column(s) to use as the row labels of the ``DataFrame``, either given as
string name or column index. If a sequence of int / str is given, a
MultiIndex is used.
Note: ``index_col=False`` can be used to force pandas to *not* use the first
column as the index, e.g. when you have a malformed file with delimiters at
the end of each line.
usecols : list-like or callable, optional
Return a subset of the columns. If list-like, all elements must either
be positional (i.e. integer indices into the document columns) or strings
that correspond to column names provided either by the user in `names` or
inferred from the document header row(s). For example, a valid list-like
`usecols` parameter would be ``[0, 1, 2]`` or ``['foo', 'bar', 'baz']``.
Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``.
To instantiate a DataFrame from ``data`` with element order preserved use
``pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]`` for columns
in ``['foo', 'bar']`` order or
``pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]``
for ``['bar', 'foo']`` order.
If callable, the callable function will be evaluated against the column
names, returning names where the callable function evaluates to True. An
example of a valid callable argument would be ``lambda x: x.upper() in
['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster
parsing time and lower memory usage.
squeeze : bool, default False
If the parsed data only contains one column then return a Series.
prefix : str, optional
Prefix to add to column numbers when no header, e.g. 'X' for X0, X1, ...
mangle_dupe_cols : bool, default True
Duplicate columns will be specified as 'X', 'X.1', ...'X.N', rather than
'X'...'X'. Passing in False will cause data to be overwritten if there
are duplicate names in the columns.
dtype : Type name or dict of column -> type, optional
Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32,
'c': 'Int64'}
Use `str` or `object` together with suitable `na_values` settings
to preserve and not interpret dtype.
If converters are specified, they will be applied INSTEAD
of dtype conversion.
engine : {'c', 'python'}, optional
Parser engine to use. The C engine is faster while the python engine is
currently more feature-complete.
converters : dict, optional
Dict of functions for converting values in certain columns. Keys can either
be integers or column labels.
true_values : list, optional
Values to consider as True.
false_values : list, optional
Values to consider as False.
skipinitialspace : bool, default False
Skip spaces after delimiter.
skiprows : list-like, int or callable, optional
Line numbers to skip (0-indexed) or number of lines to skip (int)
at the start of the file.
If callable, the callable function will be evaluated against the row
indices, returning True if the row should be skipped and False otherwise.
An example of a valid callable argument would be ``lambda x: x in [0, 2]``.
skipfooter : int, default 0
Number of lines at bottom of file to skip (Unsupported with engine='c').
nrows : int, optional
Number of rows of file to read. Useful for reading pieces of large files.
Number of rows of file to read. Useful for reading pieces of large files.
na_values : scalar, str, list-like, or dict, optional
Additional strings to recognize as NA/NaN. If dict passed, specific
per-column NA values. By default the following values are interpreted as
NaN: '', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan',
'1.#IND', '1.#QNAN', 'N/A', 'NA', 'NULL', 'NaN', 'n/a', 'nan',
'null'.
keep_default_na : bool, default True
Whether or not to include the default NaN values when parsing the data.
Depending on whether `na_values` is passed in, the behavior is as follows:
* If `keep_default_na` is True, and `na_values` are specified, `na_values`
is appended to the default NaN values used for parsing.
* If `keep_default_na` is True, and `na_values` are not specified, only
the default NaN values are used for parsing.
* If `keep_default_na` is False, and `na_values` are specified, only
the NaN values specified `na_values` are used for parsing.
* If `keep_default_na` is False, and `na_values` are not specified, no
strings will be parsed as NaN.
Note that if `na_filter` is passed in as False, the `keep_default_na` and
`na_values` parameters will be ignored.
na_filter : bool, default True
Detect missing value markers (empty strings and the value of na_values). In
data without any NAs, passing na_filter=False can improve the performance
of reading a large file.
verbose : bool, default False
Indicate number of NA values placed in non-numeric columns.
skip_blank_lines : bool, default True
If True, skip over blank lines rather than interpreting as NaN values.
parse_dates : bool or list of int or names or list of lists or dict, default False
The behavior is as follows:
* boolean. If True -> try parsing the index.
* list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3
each as a separate date column.
* list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as
a single date column.
* dict, e.g. {'foo' : [1, 3]} -> parse columns 1, 3 as date and call
result 'foo'
If a column or index cannot be represented as an array of datetimes,
say because of an unparseable value or a mixture of timezones, the column
or index will be returned unaltered as an object data type. For
non-standard datetime parsing, use ``pd.to_datetime`` after
``pd.read_csv``. To parse an index or column with a mixture of timezones,
specify ``date_parser`` to be a partially-applied
:func:`pandas.to_datetime` with ``utc=True``. See
:ref:`io.csv.mixed_timezones` for more.
Note: A fast-path exists for iso8601-formatted dates.
infer_datetime_format : bool, default False
If True and `parse_dates` is enabled, pandas will attempt to infer the
format of the datetime strings in the columns, and if it can be inferred,
switch to a faster method of parsing them. In some cases this can increase
the parsing speed by 5-10x.
keep_date_col : bool, default False
If True and `parse_dates` specifies combining multiple columns then
keep the original columns.
date_parser : function, optional
Function to use for converting a sequence of string columns to an array of
datetime instances. The default uses ``dateutil.parser.parser`` to do the
conversion. Pandas will try to call `date_parser` in three different ways,
advancing to the next if an exception occurs: 1) Pass one or more arrays
(as defined by `parse_dates`) as arguments; 2) concatenate (row-wise) the
string values from the columns defined by `parse_dates` into a single array
and pass that; and 3) call `date_parser` once for each row using one or
more strings (corresponding to the columns defined by `parse_dates`) as
arguments.
dayfirst : bool, default False
DD/MM format dates, international and European format.
cache_dates : boolean, default True
If True, use a cache of unique, converted dates to apply the datetime
conversion. May produce significant speed-up when parsing duplicate
date strings, especially ones with timezone offsets.
.. versionadded:: 0.25.0
iterator : bool, default False
iterator : bool, default False
Return TextFileReader object for iteration or getting chunks with
``get_chunk()``.
chunksize : int, optional
Return TextFileReader object for iteration.
See the `IO Tools docs
<http://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_
for more information on ``iterator`` and ``chunksize``.
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'
For on-the-fly decompression of on-disk data. If 'infer' and
`filepath_or_buffer` is path-like, then detect compression from the
following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no
decompression). If using 'zip', the ZIP file must contain only one data
file to be read in. Set to None for no decompression.
.. versionadded:: 0.18.1 support for 'zip' and 'xz' compression.
thousands : str, optional
Thousands separator.
decimal : str, default '.'
Character to recognize as decimal point (e.g. use ',' for European data).
lineterminator : str (length 1), optional
Character to break file into lines. Only valid with C parser.
quotechar : str (length 1), optional
The character used to denote the start and end of a quoted item. Quoted
items can include the delimiter and it will be ignored.
quoting : int or csv.QUOTE_* instance, default 0
Control field quoting behavior per ``csv.QUOTE_*`` constants. Use one of
QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3).
doublequote : bool, default ``True``
When quotechar is specified and quoting is not ``QUOTE_NONE``, indicate
whether or not to interpret two consecutive quotechar elements INSIDE a
field as a single ``quotechar`` element.
escapechar : str (length 1), optional
One-character string used to escape other characters.
comment : str, optional
Indicates remainder of line should not be parsed. If found at the beginning
of a line, the line will be ignored altogether. This parameter must be a
single character. Like empty lines (as long as ``skip_blank_lines=True``),
fully commented lines are ignored by the parameter `header` but not by
`skiprows`. For example, if ``comment='#'``, parsing
``#emptyna,b,cn1,2,3`` with ``header=0`` will result in 'a,b,c' being
treated as the header.
encoding : str, optional
Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python
standard encodings
<https://docs.python.org/3/library/codecs.html#standard-encodings>`_ .
dialect : str or csv.Dialect, optional
If provided, this parameter will override values (default or not) for the
following parameters: `delimiter`, `doublequote`, `escapechar`,
`skipinitialspace`, `quotechar`, and `quoting`. If it is necessary to
override values, a ParserWarning will be issued. See csv.Dialect
documentation for more details.
error_bad_lines : bool, default True
Lines with too many fields (e.g. a csv line with too many commas) will by
default cause an exception to be raised, and no DataFrame will be returned.
If False, then these "bad lines" will dropped from the DataFrame that is
returned.
warn_bad_lines : bool, default True
If error_bad_lines is False, and warn_bad_lines is True, a warning for each
"bad line" will be output.
delim_whitespace : bool, default False
Specifies whether or not whitespace (e.g. ``' '`` or ``' '``) will be
used as the sep. Equivalent to setting ``sep='s+'``. If this option
is set to True, nothing should be passed in for the ``delimiter``
parameter.
.. versionadded:: 0.18.1 support for the Python parser.
low_memory : bool, default True
Internally process the file in chunks, resulting in lower memory use
while parsing, but possibly mixed type inference. To ensure no mixed
types either set False, or specify the type with the `dtype` parameter.
Note that the entire file is read into a single DataFrame regardless,
use the `chunksize` or `iterator` parameter to return the data in chunks.
(Only valid with C parser).
memory_map : bool, default False
If a filepath is provided for `filepath_or_buffer`, map the file object
In [ ]:
def fun(x, y)
In [26]:
class Cal:
def __init__(self, x, y):
self.x = x
self.y = y
def add(self):
print("Addition :", self.x + self.y)
def sub(self):
print("Subtraction :", self.x -self.y)
a = Cal(3, 4)
a.add()
a.sub()
In [ ]:
If a filepath is provided for `filepath_or_buffer`, map the file object
directly onto memory and access the data directly from there. Using this
option can improve performance because there is no longer any I/O overhead.
float_precision : str, optional
Specifies which converter the C engine should use for floating-point
values. The options are `None` for the ordinary converter,
`high` for the high-precision converter, and `round_trip` for the
round-trip converter.
Returns
-------
DataFrame or TextParser
A comma-separated values (csv) file is returned as two-dimensional
data structure with labeled axes.
See Also
--------
to_csv : Write DataFrame to a comma-separated values (csv) file.
read_csv : Read a comma-separated values (csv) file into DataFrame.
read_fwf : Read a table of fixed-width formatted lines into DataFrame.
Examples
--------
>>> pd.read_csv('data.csv') # doctest: +SKIP
Addition : 7
Subtraction : -1
A date in Python is not a data type of its own, but we can import a module named datetime to
work with dates as date objects.
In [2]:
# printing the current date and time
import datetime
x = datetime.datetime.now()
print(x)
In [4]:
# returning the specific things
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.month)
print(x.day)
print(x.strftime("%A"))
print(x.strftime("%d"))
In [3]:
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
Other Date Formats
%a Weekday, short version Wed
%A Weekday, full version Wednesday
%w Weekday as a number 0-6, 0 is Sunday 3
%d Day of month 01-31 31
%b Month name, short version Dec
%B Month name, full version December
%m Month as a number 01-12 12
%y Year, short version, without century 18
%Y Year, full version 2018
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%f Microsecond 000000-999999 548513
%z UTC offset +0100
%Z Timezone CST
%j Day number of year 001-366 365
2020-02-25 19:05:00.483050
2020
2
Tuesday
25
June
%j Day number of year 001-366 365
%U Week number of year, Sunday as the first day of week, 00-53 52
%W Week number of year, Monday as the first day of week, 00-53 52
%c Local version of date and time Mon Dec 31 17:41:00 2018
%x Local version of date 12/31/18
%X Local version of time 17:41:00
%% A % character %
A RegEx, or Regular Expression, is a sequence of characters that forms a
search pattern.
RegEx can be used to check if a string contains the specified search
pattern.
In [5]:
# Search the string to see if it starts with "The" and ends with "Spain":
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain", txt)
print(x)
Meta Characters
[] A set of characters "[a-m]"
 Signals a special sequence (can also be used to escape special characters) "d"
. Any character (except newline character)
^ Starts with "^hello"
"dollar sign" Ends with
'star sign' Zero or more occurrences "aix*"
'+' One or more occurrences "aix+"
{} Exactly the specified number of occurrences "al{2}"
| Either or "falls|stays"
() Capture and group
In [ ]:
Built-in Function
findall Returns a list containing all matches
search Returns a Match object if there is a match anywhere in the string
split Returns a list where the string has been split at each match
sub Replaces one or many matches with a string
Special Characters
A Returns a match if the specified characters are at the beginning of the string "AThe"
b Returns a match where the specified characters are at the beginning or at the end of a word r"bain"r"ainb"
B Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word r"Bain"
r"ainB"
d Returns a match where the string contains digits (numbers from 0-9) "d"
D Returns a match where the string DOES NOT contain digits "D"
s Returns a match where the string contains a white space character "s"
S Returns a match where the string DOES NOT contain a white space character "S"
w Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _
character) "w"
W Returns a match where the string DOES NOT contain any word characters "W"
Z Returns a match if the specified characters are at the end of the string "SpainZ"
<_sre.SRE_Match object; span=(0, 17), match='The rain in Spain'>
sets
[arn] Returns a match where one of the specified characters (a, r, or n) are present
[a-n] Returns a match for any lower case character, alphabetically between a and n
[^arn] Returns a match for any character EXCEPT a, r, and n
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present
[0-9] Returns a match for any digit between 0 and 9
[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59
[a-zA-Z] Returns a match for any character alphabetically between a and z, lower case OR upper case
[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for any + character in the stri
In [5]:
# using the findall function
import re
str = "The rain in Spain"
x = re.findall("ai", str)
print(x)
In [6]:
# using the search function
str = "The rain in Spain"
x = re.search("s", str)
print("The first white-space character is located in position:", x.start())
In [7]:
# using the split function
import re
str = "The rain in Spain"
x = re.split("s", str)
print(x)
In [9]:
# using the sub function(used to replace string)
import re
str = "The rain in Spain"
x = re.sub("s", "9", str)
print(x)
In [10]:
# using the span function to search for occurences
import re
str = "The rain in Spain"
x = re.search(r"bSw+", str)
['ai', 'ai']
The first white-space character is located in position: 3
['The', 'rain', 'in', 'Spain']
The9rain9in9Spain
x = re.search(r"bSw+", str)
print(x.span())
In [11]:
# printing the group where
import re
str = "The rain in Spain"
x = re.search(r"bSw+", str)
print(x.group())
In [4]:
xx = "guru99,education is fun"
r1 = re.findall(r"^w",xx)
print(r1)
In [3]:
xx = "guru99,education is fun"
r1 = re.findall(r"^w+",xx)
print(r1)
In [ ]:
regex = '^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$'
def check(email):
# pass the regualar expression
# and the string in search() method
if(re.search(regex,email)):
print("Valid Email")
else:
print("Invalid Email")
(12, 17)
Spain
['g']
['guru99']
functional Programming
In [6]:
def function(x):
y = x+2
return y
In [7]:
def function2(y):
z = y*2
return z
In [8]:
def function3(z):
a = z**2
return a
In [9]:
def function4(a):
b = a/4
return b
In [10]:
# creating a bigger function where we will include all the other functions
def all(x):
y = function(x)
z = function2(y)
a = function3(z)
b = function4(a)
return b
In [11]:
all(4)
In [12]:
all(95)
In [13]:
all(85)
Out[11]:
36.0
Out[12]:
9409.0
Out[13]:
7569.0
Q1. Write a Python program which accepts the radius of a circle from the user and compute the
area
In [ ]:
Q2. Write a Python program which accepts a sequence of comma-separated numbers from user
and generate a list and a tuple with those numbers
In [ ]:
Q3. Write a Python program to display the first and last colors from the following list.
In [ ]:
Q4. Write a Python program that accepts an integer (n) and computes the value of
n+nn+nnn
In [ ]:
Q5. Write a Python program to get the volume of a sphere with radius 6.
In [ ]:
Q6. Write a Python program to test whether a number is within 100 of 1000 or 2000.
In [ ]:
Q7. Write a Python program to count the number 4 in a given list.
In [ ]:
Q8.Write a Python program to test whether a passed letter is a vowel or not.
In [ ]:
Q9. Write a Python program to concatenate all elements in a list into a string and return it.
In [ ]:
color_list_1 = set(["White", "Black", "Red"]) color_list_2 = set(["Red", "Green"])
In [ ]:
Q10. Write a Python program to print out a set containing all the colors from color_list_1 which
are not present in color_list_2
In [ ]:
Q11. Write a Python program that will accept the base and height of a triangle and compute the
area.
In [ ]:
Q12. Write a Python program to compute the greatest common divisor (GCD) of two positive
integers.
In [ ]:
Q13. Write a Python program to get the least common multiple (LCM) of two positive
integers
In [ ]:
Q14. Write a Python program to solve (x + y) * (x + y).
In [ ]:
Q15. Write a Python program to compute the distance between the points (x1, y1) and (x2,
y2).
In [ ]:
Q16. Write a python program to find the sum of the first n positive integers.
In [ ]:
Q17. Reverse a String
In [ ]:
Q18. Swap two Numbers
In [ ]:
Q19. Write a command to get the documentation of numpy module.
In [ ]:
Q20. Write a Python program to find the available built-in modules.
In [ ]:
Hint: Input-> 2 Output-> 0 1 2
Hint: Input->5 Output->1+2+3+4+5 = 15
Hint: Input->5 Output-> 1*2*3*4*5 = 120
Hint: Input->5 Output->1/5
Hint: Input-> Roshan Output-> Hi Roshan!, Hope your Day is good.
Hint: Input-> String: '$ 50 M' Output-> Number: 50
Hint: Input1-> Amar Input2-> Singh Input3-> Chouhan Output-> Amar Singh Chouhan
Hint: Input-> [2, 5, 8, 8, 9, 7, 4] Output-> Sum: 43 Average: 43/7 Standard Deviation: ? Median: 7 Max: 9 Min: 2
Hint: Input->9 Output-> Not Prime Input->11 Output->Prime
Hint: Input->2 Output-> 2, 4, 6, 8, 10, 12, 14, 16, 18, 20
Q1. Take a User Input and Print the Fibonacci Series until that number
Q2. Take a User Input and find the Cumulative sum until that number
Q3. Take a User Input and find the factorial of that number
Q4. Take a User Input and rerurn the Inverse of that number
Q5. Take User's Name as Input and Greet that User
Q6. Clean the String: $ 50 M to 50
Q7. Take First Name, Middle Name and Last Name from the User and Return
the Full Name
Q8. Take a List and Compute the Sum, Average, Standard deviation, median,
maximum and minimum values
Q9. Take a Number and check whether a number is Prime or not
Q10. Take a Number and Return the Table of that Number
In [ ]:
Input : {a: 98, b: 89, c: 78} Output: a, b, c
Sample Dictionary : {0: 10, 1: 20} Expected Result : {0: 10, 1: 20, 2: 30}
Sample Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
Input: {a:89, b:90, c:98} check for c
Input: {a:20, b:70, c:90} Output: 180
Lists
Write a Python program to sum all the items in a list.
In [3]:
def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))
Write a Python program to multiplies all the items in a list.
In [ ]:
Write a Python program to remove duplicates from a list
In [ ]:
Write a Python program to generate all permutations of a list in Python
In [ ]:
import itertools
print(list(itertools.permutations([1,2,3])))
Dictionary
Write a Python script to sort (ascending and descending) a dictionary by value.
Write a Python script to add a key to a dictionary.
Write a Python script to concatenate following dictionaries to create a new one.
Write a Python script to check whether a given key already exists in a dictionary.
Write a Python program to iterate over dictionaries using for loops and add the values
Write a Python script to generate and print a dictionary that contains a number (between 1 and
-5
Sample Dictionary ( n = 5) : Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Write a Python script to generate and print a dictionary that contains a number (between 1 and
n) in the form (x, x*x)

More Related Content

What's hot

Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & ImportMohd Sajjad
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 
Python programing
Python programingPython programing
Python programinghamzagame
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc csKALAISELVI P
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in pythonSarfaraz Ghanta
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Twoamiable_indian
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Pedro Rodrigues
 
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEFUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEVenugopalavarma Raja
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1Abdul Haseeb
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for KidsAimee Maree Forsstrom
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonMarian Marinov
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasserySHAMJITH KM
 

What's hot (20)

Python Basics
Python BasicsPython Basics
Python Basics
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Python programing
Python programingPython programing
Python programing
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
 
Python
PythonPython
Python
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
 
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEFUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
 
Python ppt
Python pptPython ppt
Python ppt
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
 
python.ppt
python.pptpython.ppt
python.ppt
 
Day2
Day2Day2
Day2
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - Kalamassery
 

Similar to Python for data science by www.dmdiploma.com

USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONvikram mahendra
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In RubyRoss Lawley
 
Poetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePoetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePeter Solymos
 
R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)Christopher Roach
 
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxINFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxcarliotwaycave
 
Introduction to python programming 1
Introduction to python programming   1Introduction to python programming   1
Introduction to python programming 1Giovanni Della Lunga
 
Detecting Bugs in Binaries Using Decompilation and Data Flow Analysis
Detecting Bugs in Binaries Using Decompilation and Data Flow AnalysisDetecting Bugs in Binaries Using Decompilation and Data Flow Analysis
Detecting Bugs in Binaries Using Decompilation and Data Flow AnalysisSilvio Cesare
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevJavaDayUA
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programmingAlberto Labarga
 
Python-CH01L04-Presentation.pptx
Python-CH01L04-Presentation.pptxPython-CH01L04-Presentation.pptx
Python-CH01L04-Presentation.pptxElijahSantos4
 
Ejercicios de estilo en la programación
Ejercicios de estilo en la programaciónEjercicios de estilo en la programación
Ejercicios de estilo en la programaciónSoftware Guru
 
NumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxNumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxJohnWilliam111370
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Languagevsssuresh
 

Similar to Python for data science by www.dmdiploma.com (20)

Introduction to r
Introduction to rIntroduction to r
Introduction to r
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In Ruby
 
Poetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePoetry with R -- Dissecting the code
Poetry with R -- Dissecting the code
 
R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)
 
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxINFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Introduction to python programming 1
Introduction to python programming   1Introduction to python programming   1
Introduction to python programming 1
 
Detecting Bugs in Binaries Using Decompilation and Data Flow Analysis
Detecting Bugs in Binaries Using Decompilation and Data Flow AnalysisDetecting Bugs in Binaries Using Decompilation and Data Flow Analysis
Detecting Bugs in Binaries Using Decompilation and Data Flow Analysis
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy Dyagilev
 
Python
PythonPython
Python
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programming
 
Python-CH01L04-Presentation.pptx
Python-CH01L04-Presentation.pptxPython-CH01L04-Presentation.pptx
Python-CH01L04-Presentation.pptx
 
Ejercicios de estilo en la programación
Ejercicios de estilo en la programaciónEjercicios de estilo en la programación
Ejercicios de estilo en la programación
 
NumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxNumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptx
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Language
 

Recently uploaded

Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 

Recently uploaded (20)

Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 

Python for data science by www.dmdiploma.com

  • 1. In [ ]: Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. It is used for: In [ ]: web development (server-side), software development, mathematics, system scripting. What can Python do? In [ ]: Python can be used on a server to create web applications. Python can be used alongside software to create workflows. Python can connect to database systems. It can also read and modify files. Python can be used to handle big data and perform complex mathematics. Python can be used for rapid prototyping, or for production-ready software development. Why Python? In [ ]: Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). Python has a simple syntax similar to the English language. Python has syntax that allows developers to write programs with fewer lines than some other program ming languages. Python runs on an interpreter system, meaning that code can be executed as soon as it is written. T his means that prototyping can be very quick. Python can be treated in a procedural way, an object-orientated way or a functional way. In [3]: print("Hello World !") In [ ]: Hello World !
  • 2. Let's Check the Rules in Naming a Variable Rule 1: A Variable name must start with a letter or Underscore Rule 2: A Variable name cannot start with a number Rule 3: A Variable name can only contain alphanumeric characters and underscores Rule 4: Variable names are Case Sensitive In [9]: _a = 5 String = 8 string = 88 #8x = 9 print(_a) print(String) print(string) Creating Variables Variables are containers solely used for storing data values. Python has no command for declaring a variable, ie., there is no declaration of variables. A variable is created the moment you first assign a value to it. In [2]: x = 10 y = 15.6 z = 'String' Let's Print the Variables In [3]: print(x) print(y) print(z) Let's Check the Datatype of the Variables In [5]: print(type(x)) print(type(y)) print(type(z)) Let's Assign Multiple Values to Multiple Variables at one time 5 8 88 10 15.6 String <class 'int'> <class 'float'> <class 'str'>
  • 3. Let's Assign Multiple Values to Multiple Variables at one time In [10]: x, y, z = 10, 15.6, 'String' print(type(x)) print(type(y)) print(type(z)) Let's Check how to Output the Variables In [18]: # for Integer and Float we can use comma to output the variables x = 1056.88 y = 89 print("The Value of x is : ", x) print("The Value of y is : ", y) In [20]: # for Strings we can use both '+' and ',' to output the variables x = "String" print("The Value of x is : "+ x) print("The Value of x is : ", x) Concatenation of Variables in Python In [25]: # let's first check the string concatenation x = 'Python' y = 'is' z = 'Love' a = x+y+z print(a) b = x+" "+y+" "+z print(b) In [27]: # now, let's check the integer and float concatenation x = 10 y = 15 a = x + y print(a) # here, the '+' symbol will act as an arithmetic operation for addition and not concatena tion <class 'int'> <class 'float'> <class 'str'> The Value of x is : 1056.88 The Value of y is : 89 The Value of x is : String The Value of x is : String PythonisLove Python is Love
  • 4. In [33]: # let's try to concatenate strings and Integer/floats x = 'My Age is' y = 8 #z = x+y #print(z) #Expected : Type Error, Cannot Concatenate String and Integer In [1]: # the above programs produces an error because we cannot concatenate a string and an Integer # but using the format function we can concatenate them x = 'My Age is {} and cgpa is {}' print(x.format(8, 6)) Global Variables Global Variables are Variables which are created Outside of the Function. But, They can accessed from anywhere. In [36]: x = 89.63 def function(): print(x) function() # here, we are able to access variable from outside of the variable In [38]: x = 8956454.23 def function(): x = 78 print(x) function() # here, we are able to access the local variable The Global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword. In [41]: def function(): global x x = "fantastic" print(x) function() 25 My Age is 8 and cgpa is 6 89.63 78
  • 6. Built in Data Types Python has the following data types built-in by default, in these categories: Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview Getting the Data Type of the Variable In [3]: x = 156 print(type(x)) In [2]: y = 8.96 print(type(y)) In [4]: z = 'string' print(type(z)) In [5]: a = 1j print(type(a)) In [6]: b = ['apple','ball','cat'] print(type(b)) In [3]: b = set(('apple', 'ball')) print(type(b)) In [7]: c = ('apple','ball','cat') <class 'int'> <class 'float'> <class 'str'> <class 'complex'> <class 'list'> <class 'set'>
  • 7. c = ('apple','ball','cat') print(type(c)) In [8]: d = {'Name': 'John', 'Age': 56, 'Salary': 78896.8} print(type(d)) In [9]: e = {"Dog","Cat",'Parrot'} print(type(e)) In [11]: f = frozenset({"Dog","Cat","Parrot"}) print(type(f)) In [12]: g = True print(type(g)) In [13]: h = b"Hello" print(type(h)) In [14]: i = bytearray(85) print(type(i)) In [16]: j = memoryview(bytes(5)) print(type(j)) Setting the Data Types Specifically In [18]: x = int(3) print(type(x)) <class 'tuple'> <class 'dict'> <class 'set'> <class 'frozenset'> <class 'bool'> <class 'bytes'> <class 'bytearray'> <class 'memoryview'> <class 'int'>
  • 8. In [20]: x = float(4.9) print(type(x)) In [24]: x = str('fish') print(type(x)) In [25]: x = list((7, 8, 9, 5)) print(type(x)) In [26]: x = tuple((4, 5, 6, 8)) print(type(x)) In [6]: x = range(5, 20) x In [31]: x = dict(name="John", age=36) print(type(x)) In [33]: x = set(("Apple","Ball","Cat")) print(type(x)) In [34]: x = frozenset(("Red","Blue","Green")) print(type(x)) In [36]: x = bool(4) print(type(x)) <class 'float'> <class 'str'> <class 'list'> <class 'tuple'> Out[6]: range(5, 20, 2) <class 'dict'> <class 'set'> <class 'frozenset'>
  • 9. In [37]: x = bytes(5) print(type(x)) Typecasting In [ ]: x = 4 x = x.astype('float') In [21]: x = float(4) x In [38]: x = 4 x = float(x) print(type(x)) In [23]: x = int(8.56) x Random Numbers In [10]: import random # printing a random number from a specified range print(random.randrange(1, 10)) In [11]: # printing a random number in default range i.e., 0 to 1 print(random.random()) In [13]: <class 'bool'> <class 'bytes'> Out[21]: 4.0 <class 'float'> Out[23]: 8 8 0.9128538599745194
  • 10. In [13]: # printing a random integer number print(random.randint(2, 10)) In [56]: # printing specific number of random nuumbers print(random.randn()) In [ ]: 9 --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-56-97184c9f9038> in <module> 1 # printing specific number of random nuumbers 2 ----> 3 print(random.randn()) AttributeError: module 'random' has no attribute 'randn'
  • 11. Operators are used to perform operations on variables and values. Python Operators are divided into the following groups Arithmetic operators Assignment operators Comparison operators Logical operators Identity operators Membership operators Bitwise operators Arithmetic Operators '+' for Addition '-' for Subtraction '*' for Multiplication '' for Divison '' for floor divison '%' for modulus '**' for exponents In [4]: # addition of two numbers x = 8 y = 9 z = x+y print(z) In [5]: # subtraction of two numbers x = 15 y = 10 z = x-y print(z) In [6]: # multilpication of two numbers x = 3 y = 9 z = x*y print(z) In [7]: # division of two numbers x = 27 y = 3 z = x/y print(z) 17 5 27
  • 12. print(z) In [8]: # floor division of two numbers x = 34 y = 5 z = x//y print(z) In [1]: # modulus of two numbers x = 8 y = 3 z = x%y print(z) In [2]: # exponent of a number x = 8 y = 2 z = x**y print(z) Assignment Operators '=' for assignment '+=' for additive assignment '-=' for subtractive assignment '*=' for multiplicative assignment '/=' for divisive assignment '//=' for floor divisive assignment '%=' for modulus assignment '**=' for exponentiation assignment '&=' for bitwise and assignment '|=' for bitwise or assignment '^=' for bitwise negation assignment '>>=' for right shift assignment '<<=' for left shift assignment In [4]: # assignment operator x = 5 print(x) In [10]: # additive assignment x = 50 9.0 6 2 64 5
  • 13. x = 50 x += 5 # similar to x = x+5 print(x) In [11]: # subtractive assignment x = 50 x -= 5 print(x) In [13]: # multiplicative assignment x = 50 x *= 5 print(x) In [15]: # divisive assignement x = 50 x /= 5 print(x) In [18]: # floor division assignment x = 50 x //= 9 print(x) In [19]: ## modulus assignment x = 50 x %= 5 print(x) In [30]: # bitwise and assignment x = 5 x &= 3 print(x) 55 45 250 10.0 5 0 1
  • 14. In [29]: # bitwise or assignment x = 50 x |= 2 print(x) In [49]: # bitwise not assignment x = 50 x ^= 2 print(x) In [24]: ## left shift assignment x = 8 x <<= 2 print(x) In [25]: # right shift assignment x = 8 x >>= 2 print(x) Comparison Operators '==' for equal comparison '!=' for not equal comparison '>' for Greater than comparison '<' for lesser than comparison '>=' for Greater than equal to comparison '<=' for Lesser than equal to comparison In [50]: # equal to comparison x = 5 y = 9 print(x == y) In [51]: # not equal to comparison x = 8 y = 9 50 48 32 2 False
  • 15. y = 9 print(x!=y) In [52]: # greater than comparison x = 5 y = 3 print(x>y) In [53]: # lesser than comparison x = 5 y = 3 print(x<y) In [54]: # greater than equal to comparison x = 5 y = 5 print(x>=y) In [55]: # lesser than equal to comparison x = 5 y = 9 print(x<=y) Logical Operators 'AND' Retuens true, If both the statements are True 'OR' returns true, If One of the Statements are True 'NOT' returns true, It will Reverse the Result. In [56]: # AND Operation x = 10 y = 8 x > y and x > 5 In [57]: True True False True True Out[56]: True
  • 16. In [57]: # OR Operation x = 10 y = 5 x > 5 or y >8 In [60]: # NOT Operation x = 10 y = 5 not(x >= 10 and y == 5) Identity Operators is, Returns true, if both the objects are same is not, Returns true, if both the objects are not the same In [62]: m = 5 n = 5 print(m is n) In [63]: m = ['apple','cat','ball'] n = ['apple','cat','ball'] print( m is n) In [64]: print(m == n) In [65]: print( m is not n) Membership Operators in, Returns True if a sequence with the specified value is present in the object not in, Returns True if a sequence with the specified value is not present in the object Out[57]: True Out[60]: False True False True True
  • 17. In [69]: x = [2, 3, 4, 5, 6, 7] y = [5] z = [3, 4, 5] a = 3 print(y in x) print(z in x) print(a in x) Bitwise Operator &, AND Operation |, OR Operation ^, XOR Operation ~, NOT Operation >>, Right Shift Operation <<, Left Shift Operation False False True
  • 18. In [1]: # Printing Strings into Python print("Hello") print('Hello') In [1]: x = "Chocolate" x[-5:-2] In [2]: # Assigning Values to the String a = "Hello" print(a) In [3]: # Strings as Arrays a = "Hello, World!" print(a[1]) In [4]: # Slicing b = "Hello, World!" print(b[2:5]) In [5]: # Negative Indexing b = "Hello, World!" print(b[-5:-2]) In [6]: # String Length a = "Hello, World! kmlmlml" b = '''kkmkmkm nkjnkjnkjnkj kjjn Hello Hello Out[1]: 'ola' Hello e llo orl
  • 19. kjjn ''' print(len(a)) In [7]: # Stripping a string a = " Hello, World! " print(a.strip()) In [8]: # converting into lowercase a = "Hello, World!" print(a.lower()) In [9]: # converting into uppercase a = "Hello, World!" print(a.upper()) In [10]: # using replace function a = "Hello, World!" print(a.replace("H", "J")) In [11]: # Splitting a string a = "Hello, World!" print(a.split(",")) In [15]: # String Formatting age = 36 txt = "My name is John, I am {}" print(txt.format(age)) Other Important Functions capitalize() Converts the first character to upper case 13 Hello, World! hello, world! HELLO, WORLD! Jello, World! ['Hello', ' World!'] My name is John, I am 36
  • 20. capitalize() Converts the first character to upper case casefold() Converts string into lower case center() Returns a centered string count() Returns the number of times a specified value occurs in a string encode() Returns an encoded version of the string endswith() Returns true if the string ends with the specified value expandtabs() Sets the tab size of the string find() Searches the string for a specified value and returns the position of where it was found format() Formats specified values in a string format_map() Formats specified values in a string index() Searches the string for a specified value and returns the position of where it was found isalnum() Returns True if all characters in the string are alphanumeric isalpha() Returns True if all characters in the string are in the alphabet isdecimal() Returns True if all characters in the string are decimals isdigit() Returns True if all characters in the string are digits isidentifier() Returns True if the string is an identifier islower() Returns True if all characters in the string are lower case isnumeric() Returns True if all characters in the string are numeric isprintable() Returns True if all characters in the string are printable isspace() Returns True if all characters in the string are whitespaces istitle() Returns True if the string follows the rules of a title isupper() Returns True if all characters in the string are upper case join() Joins the elements of an iterable to the end of the string ljust() Returns a left justified version of the string lower() Converts a string into lower case lstrip() Returns a left trim version of the string maketrans() Returns a translation table to be used in translations partition() Returns a tuple where the string is parted into three parts replace() Returns a string where a specified value is replaced with a specified value rfind() Searches the string for a specified value and returns the last position of where it was found rindex() Searches the string for a specified value and returns the last position of where it was found rjust() Returns a right justified version of the string rpartition() Returns a tuple where the string is parted into three parts rsplit() Splits the string at the specified separator, and returns a list rstrip() Returns a right trim version of the string split() Splits the string at the specified separator, and returns a list splitlines() Splits the string at line breaks and returns a list startswith() Returns true if the string starts with the specified value strip() Returns a trimmed version of the string swapcase() Swaps cases, lower case becomes upper case and vice versa title() Converts the first character of each word to upper case translate() Returns a translated string upper() Converts a string into upper case zfill() Fills the string with a specified number of 0 values at the beginning In [ ]:
  • 21. If Else Conditional Statements Equals: a == b Not Equals: a != b Less than: a < b Less than or equal to: a <= b Greater than: a > b Greater than or equal to: a >= b In [2]: a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") In [3]: a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") In [4]: # shorthand ifelse if a > b: print("a is greater than b") In [5]: a = 2 b = 330 print("A") if a > b else print("B") In [6]: a = 330 b = 330 print("A") if a > b else print("=") if a == b else print("B") In [7]: a and b are equal a is greater than b a is greater than b B =
  • 22. # and operation a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True") In [8]: # or operation a = 200 b = 33 c = 500 if a > b or a > c: print("At least one of the conditions is True") In [9]: x = 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.") In [2]: # if statements cannot be empty, but if you for some reason have an if statement # with no content, put in the pass statement to avoid getting an error. a = 33 b = 200 if b > a: pass While With the while loop we can execute a set of statements as long as a condition is true. In [12]: i = 1 while i < 6: print(i) i += 1 With the break statement we can stop the loop even if the while condition is true: Both conditions are True At least one of the conditions is True Above ten, and also above 20! 1 2 3 4 5
  • 23. In [13]: i = 1 while i < 6: print(i) if i == 3: break i += 1 With the continue statement we can stop the current iteration, and continue with the next: In [14]: i = 0 while i < 6: i += 1 if i == 3: continue print(i) With the else statement we can run a block of code once when the condition no longer is true: In [16]: i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6") For A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object- orientated programming languages. With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc In [17]: # looping through a list fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) 1 2 3 1 2 4 5 6 1 2 3 4 5 i is no longer less than 6 apple banana cherry
  • 24. In [18]: # looping through a string for x in "banana": print(x) In [19]: # using the break statement fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break In [20]: # using the continue statement fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) In [21]: # using th range() function for x in range(7): print(x) In [22]: # using the start parameter for x in range(2, 6): print(x) cherry b a n a n a apple banana apple cherry 0 1 2 3 4 5 2 3 4 5
  • 25. In [23]: # incrementing the sequence for x in range(2, 30, 3): print(x) In [24]: # for and else for x in range(6): print(x) else: print("Finally finished!") In [1]: adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y) 2 5 8 11 14 17 20 23 26 29 0 1 2 3 4 5 Finally finished! red apple red banana red cherry big apple big banana big cherry tasty apple tasty banana tasty cherry
  • 26. In [61]: # Making a list list = ["apple", "banana", "cherry"] print(list) In [62]: # accessing the list list = ["apple", "banana", "cherry"] print(list[1]) In [63]: # negative indexing print(list[-1]) In [1]: # accessing a range of lists list = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(list[2:5]) In [65]: print(list[-5:-2]) In [66]: # reassigning the items in the list list[1] = 'icecream' print(list) In [67]: # reversing the list print(list[::-1]) In [68]: # concatinating two lists list2 = ['potato', 'tomato'] list3 = list + list2 print(list3) ['apple', 'banana', 'cherry'] banana cherry ['cherry', 'orange', 'kiwi'] ['cherry', 'orange', 'kiwi'] ['apple', 'icecream', 'cherry', 'orange', 'kiwi', 'melon', 'mango'] ['mango', 'melon', 'kiwi', 'orange', 'cherry', 'icecream', 'apple']
  • 27. print(list3) In [69]: # appending items to the list list.append('cauliflower') print(list) In [70]: # inserting items to the list list.insert(0, 'brinjal') print(list) In [71]: # removing items from the list list.remove('brinjal') print(list) In [5]: # extending items to the list list.extend(['flower', 'app']) print(list) In [73]: # sorting the list list.sort() print(list) In [74]: # applying pop operation list.pop() print(list) In [75]: # applying the remove operation list.remove('l') list.remove('f') ['apple', 'icecream', 'cherry', 'orange', 'kiwi', 'melon', 'mango', 'potato', 'tomato'] ['apple', 'icecream', 'cherry', 'orange', 'kiwi', 'melon', 'mango', 'cauliflower'] ['brinjal', 'apple', 'icecream', 'cherry', 'orange', 'kiwi', 'melon', 'mango', 'cauliflower'] ['apple', 'icecream', 'cherry', 'orange', 'kiwi', 'melon', 'mango', 'cauliflower'] ['apple', 'banana', 'cherry', 'orange', 'kiwi', 'melon', 'mango', 'flower', 'app'] ['apple', 'cauliflower', 'cherry', 'e', 'f', 'icecream', 'kiwi', 'l', 'mango', 'melon', 'o', 'oran ge', 'r', 'w'] ['apple', 'cauliflower', 'cherry', 'e', 'f', 'icecream', 'kiwi', 'l', 'mango', 'melon', 'o', 'oran ge', 'r']
  • 28. list.remove('f') list.remove('o') print(list) In [76]: # copying the list listcopy = list.copy() print(listcopy) In [77]: # reversing the list using reverse function list.reverse() print(list) In [78]: # counting the elements in the list x = list.count('orange') print(x) In [79]: # using lists as stack (fifo) stack = [2, 3, 4, 5, 6] stack.append(7) stack.append(8) stack.append(9) In [80]: print(stack) In [81]: stack.pop() stack.pop() stack.pop() print(stack) In [82]: # using lists as queue (lifo) from collections import deque queue = deque(['Ram', 'Shyam', 'Sita', 'Gita']) print(queue) ['apple', 'cauliflower', 'cherry', 'e', 'icecream', 'kiwi', 'mango', 'melon', 'orange', 'r'] ['apple', 'cauliflower', 'cherry', 'e', 'icecream', 'kiwi', 'mango', 'melon', 'orange', 'r'] ['r', 'orange', 'melon', 'mango', 'kiwi', 'icecream', 'e', 'cherry', 'cauliflower', 'apple'] 1 [2, 3, 4, 5, 6, 7, 8, 9] [2, 3, 4, 5, 6] deque(['Ram', 'Shyam', 'Sita', 'Gita'])
  • 29. In [83]: queue.append('Rohan') queue.append('Gopal') print(queue) In [84]: queue.popleft() print(queue) In [39]: # clearing the list list.clear() print(list) In [1]: # printing the items of a list list = ["apple", "banana", "cherry"] for x in list: print(x) In [3]: # checking if the item exists or not list = ["apple", "banana", "cherry"] if "apple" in list: print("Yes, 'apple' is in the fruits list") In [1]: x = [1, 3, 4] y = [4, 5, 6] In [ ]: deque(['Ram', 'Shyam', 'Sita', 'Gita']) deque(['Ram', 'Shyam', 'Sita', 'Gita', 'Rohan', 'Gopal']) deque(['Shyam', 'Sita', 'Gita', 'Rohan', 'Gopal']) [] apple banana cherry Yes, 'apple' is in the fruits list Out[1]: [1, 3, 4, 4, 5, 6]
  • 30. A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. In [24]: # creating a dictionary thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) In [31]: thisdict["brand"] = 'Maruti' thisdict['brand'] In [4]: # accessing values x = thisdict["model"] x In [6]: # using the get() function x = thisdict.get("model") x In [8]: # updating the values thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["year"] = 2018 thisdict In [9]: # accessing the keys {'brand': 'Ford', 'model': 'Mustang', 'year': 1964} Out[31]: 'Maruti' Out[4]: 'Mustang' Out[6]: 'Mustang' Out[8]: {'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
  • 31. # accessing the keys for x in thisdict: print(x) In [10]: # accessing the values for x in thisdict: print(thisdict[x]) In [11]: # using the values() to access the values in a dict for x in thisdict.values(): print(x) In [12]: # accessing both the key and values for x, y in thisdict.items(): print(x, y) In [13]: # checking if that particular string exists or not thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } if "model" in thisdict: print("Yes, 'model' is one of the keys in the thisdict dictionary") In [33]: # adding items to the list thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["color"] = "red" thisdict["color"] = "blue" thisdict["colors"] = "red" print(thisdict) brand model year Ford Mustang 2018 Ford Mustang 2018 brand Ford model Mustang year 2018 Yes, 'model' is one of the keys in the thisdict dictionary
  • 32. print(thisdict) In [36]: # removing the items from the dict thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.pop("year") print(thisdict) In [38]: # removing the last item from the dict thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.popitem() print(thisdict) In [17]: # using del keyword to remove the elements thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } del thisdict["model"] print(thisdict) In [40]: # deleting the dictionary thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } del thisdict In [19]: # emptieing the dictionary thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.clear() print(thisdict) {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'blue', 'colors': 'red'} {'brand': 'Ford', 'model': 'Mustang'} {'brand': 'Ford', 'model': 'Mustang'} {'brand': 'Ford', 'year': 1964} {}
  • 33. In [43]: # nested dictionary child1 = { "name" : "Emil", "year" : 2004 } child2 = { "name" : "Tobias", "year" : 2007 } child3 = { "name" : "Linus", "year" : 2011 } child4 = { "name" : "Linus", "year" : 2011 } myfamily = { "child1" : child1, "child2" : child2, "child3" : child3 } myfamily2 = { "child4":child4, } family = { "myfamily":myfamily, "myfamily2":myfamily2, } family In [23]: # one dictionary containing multiple dictionaries myfamily = { "child1" : { "name" : "Emil", "year" : 2004 }, "child2" : { "name" : "Tobias", "year" : 2007 }, "child3" : { "name" : "Linus", "year" : 2011 } } myfamily In [25]: {} Out[43]: {'myfamily': {'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}, 'myfamily2': {'child4': {'name': 'Linus', 'year': 2011}}} Out[23]: {'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
  • 34. In [25]: # creating a dictionary using the dict keyword thisdict = dict(brand="Ford", model="Mustang", year=1964) print(thisdict) Dictionary Methods clear() Removes all the elements from the dictionary copy() Returns a copy of the dictionary fromkeys() Returns a dictionary with the specified keys and values get() Returns the value of the specified key items() Returns a list containing the a tuple for each key value pair keys() Returns a list containing the dictionary's keys pop() Removes the element with the specified key popitem() Removes the last inserted key-value pair setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value update() Updates the dictionary with the specified key-value pairs values() Returns a list of all the values in the dictionary In [10]: ## Q9. Take a Number and check whether a number is Prime or not def primenumber(x): if x>1: for i in range(2,x//2): if(x%i==0): print("number is not prime") break else: print("number is prime no") else: print('ff') primenumber(7) In [11]: # Program to display the Fibonacci sequence up to n-th term nterms = int(input("How many terms? ")) # first two terms n1, n2 = 0, 1 count = 0 # check if the number of terms is valid if nterms <= 0: print("Please enter a positive integer") elif nterms == 1: print("Fibonacci sequence upto",nterms,":") print(n1) else: print("Fibonacci sequence:") while count < nterms: print(n1) nth = n1 + n2 # update values n1 = n2 n2 = nth count += 1 {'brand': 'Ford', 'model': 'Mustang', 'year': 1964} number is prime no How many terms? 5 Fibonacci sequence: 0
  • 35. In [17]: string = "$ 50 M" x = string.split() int(x[1]) In [19]: string = "$ 50 M" string.split(' ') In [ ]: 0 1 1 2 3 Out[17]: 50 Out[19]: ['$', '50', 'M']
  • 36. Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. In [7]: # creating a class with a property named x class MyClass: x = 5 y = 6 In [8]: # creating an object p1 = MyClass() print(p1.x) print(p1.y) The Init Function The examples above are classes and objects in their simplest form, and are not really useful in real life applications. To understand the meaning of classes we have to understand the built-in init() function. All classes have a function called init(), which is always executed when the class is being initiated. Use the init() function to assign values to object properties, or other operations that are necessary to do when the object is being created: In [10]: class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 45) print(p1.name) print(p1.age) Object Methods In [5]: class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) p1.myfunc() 5 6 John 45
  • 37. p1.myfunc() The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class. It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class: In [6]: class Person: def __init__(mysillyobject, name, age): mysillyobject.name = name mysillyobject.age = age def myfunc(abc): print("Hello my name is " + abc.name) p1 = Person("John", 36) p1.myfunc() In [8]: # modifying the object properties p1.age = 40 print(p1.age) In [9]: # deleting the object properties del p1.age print(p1.age) In [31]: class Cal: def __init__(self, x, y, z, t, r): self.x = x self.y = y self.z = z self.t = t self.r = r def add(self): print("Addition :", self.x+self.y) def sub(self): print("Subtraction :", self.x-self.y) def mul(self): print("Multiplication :", self.x*self.r) def div(self): print("Divison :", self.x/self.y) def floor(self): Hello my name is John Hello my name is John 40 --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-9-fdb3f776cdce> in <module> 3 del p1.age 4 ----> 5 print(p1.age) AttributeError: 'Person' object has no attribute 'age'
  • 38. print("Floor Divison :", self.x//self.y) def exp(self): print("Exponentiation :", self.z**self.y) a = Cal(3, 5, 5, 7, 4) a.add() a.sub() a.mul() a.div() a.floor() a.exp() In [19]: import pandas as p In [21]: help(p.read_csv) Addition : 8 Subtraction : -2 Multiplication : 12 Divison : 0.6 Floor Divison : 0 Exponentiation : 3125 Help on function read_csv in module pandas.io.parsers: read_csv(filepath_or_buffer:Union[str, pathlib.Path, IO[~AnyStr]], sep=',', delimiter=None, header='infer', names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression='infer', thousands=None, decimal=b'.', lineterminator=None, quotechar='"', quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, error_bad_lines=True, warn_bad_lines=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None) Read a comma-separated values (csv) file into DataFrame. Also supports optionally iterating or breaking of the file into chunks. Additional help can be found in the online docs for `IO Tools <http://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_. Parameters ---------- filepath_or_buffer : str, path object or file-like object Any valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.csv. If you want to pass in a path object, pandas accepts any ``os.PathLike``. By file-like object, we refer to objects with a ``read()`` method, such as a file handler (e.g. via builtin ``open`` function) or ``StringIO``. sep : str, default ',' Delimiter to use. If sep is None, the C engine cannot automatically detect the separator, but the Python parsing engine can, meaning the latter will be used and automatically detect the separator by Python's builtin sniffer tool, ``csv.Sniffer``. In addition, separators longer than 1 character and different from ``'s+'`` will be interpreted as regular expressions and will also force the use of the Python parsing engine. Note that regex delimiters are prone to ignoring quoted data. Regex example: ``'rt'``. delimiter : str, default ``None`` Alias for sep. header : int, list of int, default 'infer' Row number(s) to use as the column names, and the start of the data. Default behavior is to infer the column names: if no names are passed the behavior is identical to ``header=0`` and column names are inferred from the first line of the file, if column
  • 39. names are inferred from the first line of the file, if column names are passed explicitly then the behavior is identical to ``header=None``. Explicitly pass ``header=0`` to be able to replace existing names. The header can be a list of integers that specify row locations for a multi-index on the columns e.g. [0,1,3]. Intervening rows that are not specified will be skipped (e.g. 2 in this example is skipped). Note that this parameter ignores commented lines and empty lines if ``skip_blank_lines=True``, so ``header=0`` denotes the first line of data rather than the first line of the file. names : array-like, optional List of column names to use. If file contains no header row, then you should explicitly pass ``header=None``. Duplicates in this list are not allowed. index_col : int, str, sequence of int / str, or False, default ``None`` Column(s) to use as the row labels of the ``DataFrame``, either given as string name or column index. If a sequence of int / str is given, a MultiIndex is used. Note: ``index_col=False`` can be used to force pandas to *not* use the first column as the index, e.g. when you have a malformed file with delimiters at the end of each line. usecols : list-like or callable, optional Return a subset of the columns. If list-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in `names` or inferred from the document header row(s). For example, a valid list-like `usecols` parameter would be ``[0, 1, 2]`` or ``['foo', 'bar', 'baz']``. Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``. To instantiate a DataFrame from ``data`` with element order preserved use ``pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]`` for columns in ``['foo', 'bar']`` order or ``pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]`` for ``['bar', 'foo']`` order. If callable, the callable function will be evaluated against the column names, returning names where the callable function evaluates to True. An example of a valid callable argument would be ``lambda x: x.upper() in ['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster parsing time and lower memory usage. squeeze : bool, default False If the parsed data only contains one column then return a Series. prefix : str, optional Prefix to add to column numbers when no header, e.g. 'X' for X0, X1, ... mangle_dupe_cols : bool, default True Duplicate columns will be specified as 'X', 'X.1', ...'X.N', rather than 'X'...'X'. Passing in False will cause data to be overwritten if there are duplicate names in the columns. dtype : Type name or dict of column -> type, optional Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32, 'c': 'Int64'} Use `str` or `object` together with suitable `na_values` settings to preserve and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion. engine : {'c', 'python'}, optional Parser engine to use. The C engine is faster while the python engine is currently more feature-complete. converters : dict, optional Dict of functions for converting values in certain columns. Keys can either be integers or column labels. true_values : list, optional Values to consider as True. false_values : list, optional Values to consider as False. skipinitialspace : bool, default False Skip spaces after delimiter. skiprows : list-like, int or callable, optional Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file. If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be ``lambda x: x in [0, 2]``. skipfooter : int, default 0 Number of lines at bottom of file to skip (Unsupported with engine='c'). nrows : int, optional Number of rows of file to read. Useful for reading pieces of large files.
  • 40. Number of rows of file to read. Useful for reading pieces of large files. na_values : scalar, str, list-like, or dict, optional Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. By default the following values are interpreted as NaN: '', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan', '1.#IND', '1.#QNAN', 'N/A', 'NA', 'NULL', 'NaN', 'n/a', 'nan', 'null'. keep_default_na : bool, default True Whether or not to include the default NaN values when parsing the data. Depending on whether `na_values` is passed in, the behavior is as follows: * If `keep_default_na` is True, and `na_values` are specified, `na_values` is appended to the default NaN values used for parsing. * If `keep_default_na` is True, and `na_values` are not specified, only the default NaN values are used for parsing. * If `keep_default_na` is False, and `na_values` are specified, only the NaN values specified `na_values` are used for parsing. * If `keep_default_na` is False, and `na_values` are not specified, no strings will be parsed as NaN. Note that if `na_filter` is passed in as False, the `keep_default_na` and `na_values` parameters will be ignored. na_filter : bool, default True Detect missing value markers (empty strings and the value of na_values). In data without any NAs, passing na_filter=False can improve the performance of reading a large file. verbose : bool, default False Indicate number of NA values placed in non-numeric columns. skip_blank_lines : bool, default True If True, skip over blank lines rather than interpreting as NaN values. parse_dates : bool or list of int or names or list of lists or dict, default False The behavior is as follows: * boolean. If True -> try parsing the index. * list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column. * list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column. * dict, e.g. {'foo' : [1, 3]} -> parse columns 1, 3 as date and call result 'foo' If a column or index cannot be represented as an array of datetimes, say because of an unparseable value or a mixture of timezones, the column or index will be returned unaltered as an object data type. For non-standard datetime parsing, use ``pd.to_datetime`` after ``pd.read_csv``. To parse an index or column with a mixture of timezones, specify ``date_parser`` to be a partially-applied :func:`pandas.to_datetime` with ``utc=True``. See :ref:`io.csv.mixed_timezones` for more. Note: A fast-path exists for iso8601-formatted dates. infer_datetime_format : bool, default False If True and `parse_dates` is enabled, pandas will attempt to infer the format of the datetime strings in the columns, and if it can be inferred, switch to a faster method of parsing them. In some cases this can increase the parsing speed by 5-10x. keep_date_col : bool, default False If True and `parse_dates` specifies combining multiple columns then keep the original columns. date_parser : function, optional Function to use for converting a sequence of string columns to an array of datetime instances. The default uses ``dateutil.parser.parser`` to do the conversion. Pandas will try to call `date_parser` in three different ways, advancing to the next if an exception occurs: 1) Pass one or more arrays (as defined by `parse_dates`) as arguments; 2) concatenate (row-wise) the string values from the columns defined by `parse_dates` into a single array and pass that; and 3) call `date_parser` once for each row using one or more strings (corresponding to the columns defined by `parse_dates`) as arguments. dayfirst : bool, default False DD/MM format dates, international and European format. cache_dates : boolean, default True If True, use a cache of unique, converted dates to apply the datetime conversion. May produce significant speed-up when parsing duplicate date strings, especially ones with timezone offsets. .. versionadded:: 0.25.0 iterator : bool, default False
  • 41. iterator : bool, default False Return TextFileReader object for iteration or getting chunks with ``get_chunk()``. chunksize : int, optional Return TextFileReader object for iteration. See the `IO Tools docs <http://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_ for more information on ``iterator`` and ``chunksize``. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer' For on-the-fly decompression of on-disk data. If 'infer' and `filepath_or_buffer` is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no decompression). If using 'zip', the ZIP file must contain only one data file to be read in. Set to None for no decompression. .. versionadded:: 0.18.1 support for 'zip' and 'xz' compression. thousands : str, optional Thousands separator. decimal : str, default '.' Character to recognize as decimal point (e.g. use ',' for European data). lineterminator : str (length 1), optional Character to break file into lines. Only valid with C parser. quotechar : str (length 1), optional The character used to denote the start and end of a quoted item. Quoted items can include the delimiter and it will be ignored. quoting : int or csv.QUOTE_* instance, default 0 Control field quoting behavior per ``csv.QUOTE_*`` constants. Use one of QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3). doublequote : bool, default ``True`` When quotechar is specified and quoting is not ``QUOTE_NONE``, indicate whether or not to interpret two consecutive quotechar elements INSIDE a field as a single ``quotechar`` element. escapechar : str (length 1), optional One-character string used to escape other characters. comment : str, optional Indicates remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. Like empty lines (as long as ``skip_blank_lines=True``), fully commented lines are ignored by the parameter `header` but not by `skiprows`. For example, if ``comment='#'``, parsing ``#emptyna,b,cn1,2,3`` with ``header=0`` will result in 'a,b,c' being treated as the header. encoding : str, optional Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python standard encodings <https://docs.python.org/3/library/codecs.html#standard-encodings>`_ . dialect : str or csv.Dialect, optional If provided, this parameter will override values (default or not) for the following parameters: `delimiter`, `doublequote`, `escapechar`, `skipinitialspace`, `quotechar`, and `quoting`. If it is necessary to override values, a ParserWarning will be issued. See csv.Dialect documentation for more details. error_bad_lines : bool, default True Lines with too many fields (e.g. a csv line with too many commas) will by default cause an exception to be raised, and no DataFrame will be returned. If False, then these "bad lines" will dropped from the DataFrame that is returned. warn_bad_lines : bool, default True If error_bad_lines is False, and warn_bad_lines is True, a warning for each "bad line" will be output. delim_whitespace : bool, default False Specifies whether or not whitespace (e.g. ``' '`` or ``' '``) will be used as the sep. Equivalent to setting ``sep='s+'``. If this option is set to True, nothing should be passed in for the ``delimiter`` parameter. .. versionadded:: 0.18.1 support for the Python parser. low_memory : bool, default True Internally process the file in chunks, resulting in lower memory use while parsing, but possibly mixed type inference. To ensure no mixed types either set False, or specify the type with the `dtype` parameter. Note that the entire file is read into a single DataFrame regardless, use the `chunksize` or `iterator` parameter to return the data in chunks. (Only valid with C parser). memory_map : bool, default False If a filepath is provided for `filepath_or_buffer`, map the file object
  • 42. In [ ]: def fun(x, y) In [26]: class Cal: def __init__(self, x, y): self.x = x self.y = y def add(self): print("Addition :", self.x + self.y) def sub(self): print("Subtraction :", self.x -self.y) a = Cal(3, 4) a.add() a.sub() In [ ]: If a filepath is provided for `filepath_or_buffer`, map the file object directly onto memory and access the data directly from there. Using this option can improve performance because there is no longer any I/O overhead. float_precision : str, optional Specifies which converter the C engine should use for floating-point values. The options are `None` for the ordinary converter, `high` for the high-precision converter, and `round_trip` for the round-trip converter. Returns ------- DataFrame or TextParser A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes. See Also -------- to_csv : Write DataFrame to a comma-separated values (csv) file. read_csv : Read a comma-separated values (csv) file into DataFrame. read_fwf : Read a table of fixed-width formatted lines into DataFrame. Examples -------- >>> pd.read_csv('data.csv') # doctest: +SKIP Addition : 7 Subtraction : -1
  • 43. A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects. In [2]: # printing the current date and time import datetime x = datetime.datetime.now() print(x) In [4]: # returning the specific things import datetime x = datetime.datetime.now() print(x.year) print(x.month) print(x.day) print(x.strftime("%A")) print(x.strftime("%d")) In [3]: import datetime x = datetime.datetime(2018, 6, 1) print(x.strftime("%B")) Other Date Formats %a Weekday, short version Wed %A Weekday, full version Wednesday %w Weekday as a number 0-6, 0 is Sunday 3 %d Day of month 01-31 31 %b Month name, short version Dec %B Month name, full version December %m Month as a number 01-12 12 %y Year, short version, without century 18 %Y Year, full version 2018 %H Hour 00-23 17 %I Hour 00-12 05 %p AM/PM PM %M Minute 00-59 41 %S Second 00-59 08 %f Microsecond 000000-999999 548513 %z UTC offset +0100 %Z Timezone CST %j Day number of year 001-366 365 2020-02-25 19:05:00.483050 2020 2 Tuesday 25 June
  • 44. %j Day number of year 001-366 365 %U Week number of year, Sunday as the first day of week, 00-53 52 %W Week number of year, Monday as the first day of week, 00-53 52 %c Local version of date and time Mon Dec 31 17:41:00 2018 %x Local version of date 12/31/18 %X Local version of time 17:41:00 %% A % character %
  • 45. A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. RegEx can be used to check if a string contains the specified search pattern. In [5]: # Search the string to see if it starts with "The" and ends with "Spain": import re txt = "The rain in Spain" x = re.search("^The.*Spain", txt) print(x) Meta Characters [] A set of characters "[a-m]" Signals a special sequence (can also be used to escape special characters) "d" . Any character (except newline character) ^ Starts with "^hello" "dollar sign" Ends with 'star sign' Zero or more occurrences "aix*" '+' One or more occurrences "aix+" {} Exactly the specified number of occurrences "al{2}" | Either or "falls|stays" () Capture and group In [ ]: Built-in Function findall Returns a list containing all matches search Returns a Match object if there is a match anywhere in the string split Returns a list where the string has been split at each match sub Replaces one or many matches with a string Special Characters A Returns a match if the specified characters are at the beginning of the string "AThe" b Returns a match where the specified characters are at the beginning or at the end of a word r"bain"r"ainb" B Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word r"Bain" r"ainB" d Returns a match where the string contains digits (numbers from 0-9) "d" D Returns a match where the string DOES NOT contain digits "D" s Returns a match where the string contains a white space character "s" S Returns a match where the string DOES NOT contain a white space character "S" w Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) "w" W Returns a match where the string DOES NOT contain any word characters "W" Z Returns a match if the specified characters are at the end of the string "SpainZ" <_sre.SRE_Match object; span=(0, 17), match='The rain in Spain'>
  • 46. sets [arn] Returns a match where one of the specified characters (a, r, or n) are present [a-n] Returns a match for any lower case character, alphabetically between a and n [^arn] Returns a match for any character EXCEPT a, r, and n [0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present [0-9] Returns a match for any digit between 0 and 9 [0-5][0-9] Returns a match for any two-digit numbers from 00 and 59 [a-zA-Z] Returns a match for any character alphabetically between a and z, lower case OR upper case [+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for any + character in the stri In [5]: # using the findall function import re str = "The rain in Spain" x = re.findall("ai", str) print(x) In [6]: # using the search function str = "The rain in Spain" x = re.search("s", str) print("The first white-space character is located in position:", x.start()) In [7]: # using the split function import re str = "The rain in Spain" x = re.split("s", str) print(x) In [9]: # using the sub function(used to replace string) import re str = "The rain in Spain" x = re.sub("s", "9", str) print(x) In [10]: # using the span function to search for occurences import re str = "The rain in Spain" x = re.search(r"bSw+", str) ['ai', 'ai'] The first white-space character is located in position: 3 ['The', 'rain', 'in', 'Spain'] The9rain9in9Spain
  • 47. x = re.search(r"bSw+", str) print(x.span()) In [11]: # printing the group where import re str = "The rain in Spain" x = re.search(r"bSw+", str) print(x.group()) In [4]: xx = "guru99,education is fun" r1 = re.findall(r"^w",xx) print(r1) In [3]: xx = "guru99,education is fun" r1 = re.findall(r"^w+",xx) print(r1) In [ ]: regex = '^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$' def check(email): # pass the regualar expression # and the string in search() method if(re.search(regex,email)): print("Valid Email") else: print("Invalid Email") (12, 17) Spain ['g'] ['guru99']
  • 48. functional Programming In [6]: def function(x): y = x+2 return y In [7]: def function2(y): z = y*2 return z In [8]: def function3(z): a = z**2 return a In [9]: def function4(a): b = a/4 return b In [10]: # creating a bigger function where we will include all the other functions def all(x): y = function(x) z = function2(y) a = function3(z) b = function4(a) return b In [11]: all(4) In [12]: all(95) In [13]: all(85) Out[11]: 36.0 Out[12]: 9409.0 Out[13]: 7569.0
  • 49. Q1. Write a Python program which accepts the radius of a circle from the user and compute the area In [ ]: Q2. Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers In [ ]: Q3. Write a Python program to display the first and last colors from the following list. In [ ]: Q4. Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn In [ ]: Q5. Write a Python program to get the volume of a sphere with radius 6. In [ ]: Q6. Write a Python program to test whether a number is within 100 of 1000 or 2000. In [ ]: Q7. Write a Python program to count the number 4 in a given list. In [ ]: Q8.Write a Python program to test whether a passed letter is a vowel or not. In [ ]: Q9. Write a Python program to concatenate all elements in a list into a string and return it. In [ ]:
  • 50. color_list_1 = set(["White", "Black", "Red"]) color_list_2 = set(["Red", "Green"]) In [ ]: Q10. Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2 In [ ]: Q11. Write a Python program that will accept the base and height of a triangle and compute the area. In [ ]: Q12. Write a Python program to compute the greatest common divisor (GCD) of two positive integers. In [ ]: Q13. Write a Python program to get the least common multiple (LCM) of two positive integers In [ ]: Q14. Write a Python program to solve (x + y) * (x + y). In [ ]: Q15. Write a Python program to compute the distance between the points (x1, y1) and (x2, y2). In [ ]: Q16. Write a python program to find the sum of the first n positive integers. In [ ]: Q17. Reverse a String In [ ]:
  • 51. Q18. Swap two Numbers In [ ]: Q19. Write a command to get the documentation of numpy module. In [ ]: Q20. Write a Python program to find the available built-in modules. In [ ]:
  • 52. Hint: Input-> 2 Output-> 0 1 2 Hint: Input->5 Output->1+2+3+4+5 = 15 Hint: Input->5 Output-> 1*2*3*4*5 = 120 Hint: Input->5 Output->1/5 Hint: Input-> Roshan Output-> Hi Roshan!, Hope your Day is good. Hint: Input-> String: '$ 50 M' Output-> Number: 50 Hint: Input1-> Amar Input2-> Singh Input3-> Chouhan Output-> Amar Singh Chouhan Hint: Input-> [2, 5, 8, 8, 9, 7, 4] Output-> Sum: 43 Average: 43/7 Standard Deviation: ? Median: 7 Max: 9 Min: 2 Hint: Input->9 Output-> Not Prime Input->11 Output->Prime Hint: Input->2 Output-> 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 Q1. Take a User Input and Print the Fibonacci Series until that number Q2. Take a User Input and find the Cumulative sum until that number Q3. Take a User Input and find the factorial of that number Q4. Take a User Input and rerurn the Inverse of that number Q5. Take User's Name as Input and Greet that User Q6. Clean the String: $ 50 M to 50 Q7. Take First Name, Middle Name and Last Name from the User and Return the Full Name Q8. Take a List and Compute the Sum, Average, Standard deviation, median, maximum and minimum values Q9. Take a Number and check whether a number is Prime or not Q10. Take a Number and Return the Table of that Number In [ ]:
  • 53. Input : {a: 98, b: 89, c: 78} Output: a, b, c Sample Dictionary : {0: 10, 1: 20} Expected Result : {0: 10, 1: 20, 2: 30} Sample Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} Input: {a:89, b:90, c:98} check for c Input: {a:20, b:70, c:90} Output: 180 Lists Write a Python program to sum all the items in a list. In [3]: def sum_list(items): sum_numbers = 0 for x in items: sum_numbers += x return sum_numbers print(sum_list([1,2,-8])) Write a Python program to multiplies all the items in a list. In [ ]: Write a Python program to remove duplicates from a list In [ ]: Write a Python program to generate all permutations of a list in Python In [ ]: import itertools print(list(itertools.permutations([1,2,3]))) Dictionary Write a Python script to sort (ascending and descending) a dictionary by value. Write a Python script to add a key to a dictionary. Write a Python script to concatenate following dictionaries to create a new one. Write a Python script to check whether a given key already exists in a dictionary. Write a Python program to iterate over dictionaries using for loops and add the values Write a Python script to generate and print a dictionary that contains a number (between 1 and -5
  • 54. Sample Dictionary ( n = 5) : Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x)