PPFD_1
PPFD_1
(303105257)
Anand Jawdekar
Easy to use and Read - Python's syntax is clear and easy to read, making it an ideal
language for both beginners and experienced programmers. This simplicity can lead to
faster development and reduce the chances of errors.
Dynamically Typed - The data types of variables are determined during run-time. We
do not need to specify the data type of a variable during writing codes.
High-level - High-level language means human readable code.
Compiled and Interpreted - Python code first gets compiled into bytecode, and then
interpreted line by line. When we download the Python in our system form pyhton.org
we download the default implement of Python known as CPython. CPython is
considered to be Complied and Interpreted both.
Features
Garbage Collected - Memory allocation and de-allocation are automatically managed. Programmers
do not specifically need to manage the memory.
Purely Object-Oriented - It refers to everything as an object, including numbers and strings.
Cross-platform Compatibility - Python can be easily installed on Windows, macOS, and various Linux
distributions, allowing developers to create software that runs across different operating systems.
Rich Standard Library - Python comes with several standard libraries that provide ready-to-use
modules and functions for various tasks, ranging from web development and data
manipulation to machine learning and networking.
Open Source - Python is an open-source, cost-free programming language. It is utilized in several
sectors and disciplines as a result.
Python Applications
Python is known for its general-purpose nature that makes it applicable in almost every domain of
software development. Python makes its presence in every emerging field. It is the fastest-growing
programming language and can develop any application.
Multi-Line Comments
# it is a
# comment
# extending to multiple lines
Python If-else statements
Decision making is the most important aspect of almost all the programming
languages. As the name implies, decision making allows us to run a particular block
of code for a particular decision. Here, the decisions are made on the validity of the
particular conditions. Condition checking is the backbone of decision making.
In python, decision making is performed by the following statements.
Python If-else statements
Statement Description
1 Break statement This command terminates the loop's execution and transfers the
program's control to the statement next to the loop.
# Initiating a loop
for s in a string:
# giving a condition in if block
if s == "o":
print("If block")
# if condition is not satisfied then else block will be executed
else:
print(s)
Output:
P y t h If block n L If block If block p
The range() Function
With the help of the range() function, we may produce a series of numbers. range(10) will produce
values between 0 and 9. (10 numbers).
We can give specific start, stop, and step size values in the manner range(start, stop, step size). If the
step size is not specified, it defaults to 1.
Since it doesn't create every value it "contains" after we construct it, the range object can be
characterized as being "slow." It does provide in, len, and __getitem__ actions, but it is not an
iterator.
The example that follows will make this clear.
Example
# Python program to show the working of range() function
print(range(15))
print(list(range(15)))
print(list(range(4, 9)))
Output:
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
Python While Loops
The Python while loop iteration of a code block is executed as long as the given Condition, i.e.,
conditional_expression, is true.
If we don't know how many times we'll execute the iteration ahead of time, we can write an
indefinite loop.
Syntax of Python While Loop
Statement
while Condition:
Statement
The given condition, i.e., conditional_expression, is evaluated initially in the Python while loop. Then,
if the conditional expression gives a boolean value True, the while loop statements are executed. The
conditional expression is verified again when the complete code block is executed. This procedure
repeatedly occurs until the conditional expression returns the boolean value False.
The statements of the Python while loop are dictated by indentation.
The code block begins when a statement is indented & ends with the very first unindented
statement. Any non-zero number in Python is interpreted as boolean True. False is interpreted as
None and 0.
Example
Program code 1:
Now we give code examples of while loops in Python for printing numbers from 1 to 10. The code is
given below -
i=1
while i<=10:
print(i, end=' ')
i+=1
Now we compile the above code in python, and after successful compilation, we run it. Then the
output is given below -
1 2 3 4 5 6 7 8 9 10
Loop Control Statements
Continue Statement
It returns the control of the Python interpreter to the beginning of the loop.
Code
# Python program to show how to use continue loop control
Here, if we check the type of the variable str using a Python script
print(type(str)), then it will print a string (str).
In Python, strings are treated as the sequence of characters, which means that Python doesn't
support the character data-type; instead, a single character written as 'p' is treated as the string of
length 1.
Example
Creating String in Python
We can create a string by enclosing the characters in single-quotes or double- quotes. Python also
provides triple-quotes to represent the string, but it is generally used for multiline string
or docstrings.
#Using single quotes
str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[] It is known as slice operator. It is used to access the sub-strings of a particular string.
[:] It is known as range slice operator. It is used to access the characters from the specified range.
in It is known as membership operator. It returns if a particular sub-string is present in the specified string.
not in It is also a membership operator and does the exact reverse of in. It returns true if a particular substring
is not present in the specified string.
It is used to specify the raw string. Raw strings are used in the cases where we need to print the actual
r/R meaning of escape characters such as "C://python". To define any string as a raw string, the character r
or R is followed by the string.
It is used to perform string formatting. It makes use of the format specifiers used in C programming like
% %d or %f to map their values in python. We will discuss how formatting is done in python.
Example
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
O
ll False False C://python37 The string str : Hello
Python String functions
Method Description
capitalize() It capitalizes the first character of the String. This function is deprecated in python3
casefold() It returns a version of s suitable for case-less comparisons.
center(width ,fillchar) It returns a space padded string with the original string centred with equal number of left and
right spaces.
count(string,begin,end) It counts the number of occurrences of a substring in a String between begin and end index.
decode(encoding = 'UTF8', errors = 'strict') Decodes the string using codec registered for encoding.
encode() Encode S using the codec registered for encoding. Default encoding is 'utf-8'.
endswith(suffix ,begin=0,end=len(string)) It returns a Boolean value if the string terminates with given suffix between begin and end.
expandtabs(tabsize = 8) It defines tabs in string to multiple spaces. The default space value is 8.
find(substring ,beginIndex, endIndex) It returns the index value of the string where substring is found between begin index and end
index.
format(value) It returns a formatted version of S, using the passed value.
index(subsring, beginIndex, endIndex) It throws an exception if string is not found. It works same as find() method.
isalnum() It returns true if the characters in the string are alphanumeric i.e., alphabets or numbers and
there is at least 1 character. Otherwise, it returns false.
isalpha() It returns true if all the characters are alphabets and there is at least one character, otherwise
False.
isdecimal() It returns true if all the characters of the string are decimals.
isdigit() It returns true if all the characters are digits and there is at least one character, otherwise False.
isidentifier() It returns true if the string is the valid identifier.
islower() It returns true if the characters of a string are in lower case, otherwise false.
isnumeric() It returns true if the string contains only numeric characters.
Python List
In Python, the sequence of various data types is stored in a list. A list is a collection of different kinds
of values or items. Since Python lists are mutable, we can change their elements after forming. The
comma (,) and the square brackets [enclose the List's items] serve as separators.
Although six Python data types can hold sequences, the List is the most common and reliable form. A
list, a type of sequence data, is used to store the collection of data.
A list is a collection of items separated by commas and denoted by the symbol [].
Example
# a simple list
list1 = [1, 2, "Python", "Program", 15.9]
list2 = ["Amy", "Ryan", "Henry", "Emma"]
# printing the list
print(list1)
print(list2)
# printing the type of list
print(type(list1))
print(type(list2))
Output:
[1, 2, 'Python', 'Program', 15.9] ['Amy', 'Ryan', 'Henry', 'Emma'] < class ' list ' > < class ' list ' >
Characteristics of Lists
The characteristics of the List are as follows:
The lists are in order.
The list element can be accessed via the index.
The mutable type of List is
The rundowns are changeable sorts.
The number of various elements can be stored in a list.
List Indexing and Splitting
The indexing procedure is carried out similarly to string processing. The slice operator [] can be used
to get to the List's components. The index ranges from 0 to length -1. The 0th index is where the
List's first element is stored; the 1st index is where the second element is stored, and so on.
List Indexing and Splitting
We can get the sub-list of the list using the following syntax.
list_varible(start:stop:step)
The beginning indicates the beginning record position of the rundown.
The stop signifies the last record position of the rundown.
Within a start, the step is used to skip the nth element: stop.
The start parameter is the initial index, the step is the ending index, and the value of the end
parameter is the number of elements that are "stepped" through. The default value for the step is
one without a specific value. Inside the resultant Sub List, the same with record start would be
available, yet the one with the file finish will not. The first element in a list appears to have an index
of zero.
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as they were working with
the strings. The different operations of list are
Repetition
Concatenation
Length
Iteration
Membership
1. Repetition
The redundancy administrator empowers the rundown components to be rehashed on different
occasions.
Code
# repetition of list
# declaring the list
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
2. Concatenation
It concatenates the list mentioned on either side of the operator.
Code
# concatenation of two lists
# declaring the lists
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86]
# concatenation operator +
l = list1 + list2
print(l)
Output:
[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]
3. Length
It is used to get the length of the list
Code
# size of the list
# declaring the list
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
# finding length of the list
len(list1)
Output:
9
4. Iteration
The for loop is used to iterate over the list elements.
Code
# iteration of the list
# declaring the list
list1 = [12, 14, 16, 39, 40]
# iterating
for i in list1:
print(i)
Output:
12 14 16 39 40
5. Membership
It returns true if a particular item exists in a particular list otherwise false.
Code
# membership of the list
# declaring the list
list1 = [100, 200, 300, 400, 500]
# true will be printed if value exists
# and false if not
print(600 in list1)
print(700 in list1)
print(1040 in list1)
print(300 in list1)
print(100 in list1)
print(500 in list1)
Output:
False False False True True True
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings, which can be iterated
as follows.
Code
# iterating a list
list = ["John", "David", "James", "Jonathan"]
for i in list:
# The i variable will iterate over the elements of the List and contains each element in each iteration.
print(i)
Output:
John David James Jonathan
Adding Elements to the List
The append() function in Python can add a new item to the List. In any case, the annex() capability
can enhance the finish of the rundown.
Consider the accompanying model, where we take the components of the rundown from the client
and print the rundown on the control center.
Code
#Declaring the empty list
l =[]
#Number of elements will be entered by the user
n = int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the item
l.append(input("Enter the item:"))
print("printing the list items..")
# traversal loop to print the list items
for i in l:
print(i, end = " ")
Example
Enter the number of elements in the list:10
Enter the item:32
Enter the item:56
Enter the item:81
Enter the item:2
Enter the item:34
Enter the item:65
Enter the item:09
Enter the item:66
Enter the item:12
Enter the item:18
printing the list items..
32 56 81 2 34 65 09 66 12 18
Removing Elements from the List
The remove() function in Python can remove an element from the List. To comprehend this idea, look
at the example that follows.
Code
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
Output:
printing original list: 0 1 2 3 4 printing the list after the removal of first element... 0 1 3 4
Python List Built-in Functions
Python provides the following built-in functions, which can be used with the lists.
len()
max()
min()
len( )
It is used to calculate the length of the list.
Code
# size of the list
# declaring the list
list1 = [12, 16, 18, 20, 39, 40]
# finding length of the list
len(list1)
Output:
6
Python List Built-in Functions
Max( )
It returns the maximum element of the list
Code
# maximum of the list
list1 = [103, 675, 321, 782, 200]
# large element in the list
print(max(list1))
Output:
782
Python List Built-in Functions
Min( )
It returns the minimum element of the list
Code
# minimum of the list
list1 = [103, 675, 321, 782, 200]
# smallest element in the list
print(min(list1))
Output:
103
Python Tuples
A comma-separated group of items is called a Python triple. The ordering, settled items, and
reiterations of a tuple are to some degree like those of a rundown, but in contrast to a rundown, a
tuple is unchanging.
The main difference between the two is that we cannot alter the components of a tuple once they
have been assigned. On the other hand, we can edit the contents of a list.
Example
("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.
Features of Python Tuple
Tuples are an immutable data type, meaning their elements cannot be changed after they are
generated.
Each element in a tuple has a specific order that will never change because tuples are ordered
sequences.
All the objects-also known as "elements"-must be separated by a comma, enclosed in parenthesis ().
Although parentheses are not required, they are recommended.
Example
Code
# Python program to show how to create a tuple
# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)
Python provides the built-in function dict() method which is also used to create the dictionary.
Example
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(4, 'Rinku'), (2, Singh)])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output
Empty Dictionary: {} Create Dictionary by using dict(): {1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'} Dictionary with each item as a pair: {4:
'Rinku', 2: 'Singh'}
Accessing the dictionary values
To access data contained in lists and tuples, indexing has been studied. The keys of the dictionary can be used to
obtain the values because they are unique from one another. The following method can be used to access
dictionary values.
Code
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Output
ee["Company"]) Output <class 'dict'> printing Employee data .... Name : Dev Age : 20 Salary : 45000 Company :
WIPRO
Python provides us with an alternative to use the get() method to access the dictionary values. It would give the
same result as given by the indexing.
Adding Dictionary Values
The dictionary is a mutable data type, and utilising the right keys allows you to change its values. Dict[key] = value and the value can
both be modified. An existing value can also be updated using the update() method
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements to dictionary one at a time
Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)