0% found this document useful (0 votes)
3 views

Python Books

Uploaded by

shivamsingh17917
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Books

Uploaded by

shivamsingh17917
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

1

Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
❖ What is Python?

Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.

It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

❖ What can Python do?


 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?
 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 programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional way.

❖ Careers with Python

If you know Python nicely, then you have a great career ahead. Here are just a few of the
career options where Python is a key skill:

 Game developer
 Web designer
 Python developer
 Full-stack developer
 Machine learning engineer
 Data scientist
 Data analyst
 Data engineer
 DevOps engineer
 Software engineer
 Many more other roles

❖ Python Syntax compared to other programming languages


 Python was designed for readability, and has some similarities to the English language
with influence from mathematics.

2
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
 Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets for
this purpose.

❖ Execute Python Syntax


 As we learned in the previous page, Python syntax can be executed by writing directly
in the Command Line:

>>> print("Hello, World!")


Hello, World!

❖ Python Indentation

Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.

Python uses indentation to indicate a block of code.

Example:-

if 5 > 2:
print("Five is greater than two!")

❖ Python Comments

Comments can be used to explain Python code.

Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

Comments starts with a #, and Python will ignore them:

Example:-

#This is a comment
print("Hello, World!")

Comments can be placed at the end of a line, and Python will ignore the rest of the line:

Example:-

print("Hello, World!") #This is a comment

3
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Python will ignore string literals that are not assigned to a variable, you can add a multiline
string (triple quotes) in your code, and place your comment inside it:

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

As long as the string is not assigned to a variable, Python will read the code, but then ignore
it, and you have made a multiline comment.

❖ Python Variables

Creating Variables

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

Example:-

x=5
y = "John"
print(x)
print(y)

Casting

If you want to specify the data type of a variable, this can be done with casting.

x = str(3) # x will be '3'


y = int(3) # y will be 3
z = float(3) # z will be 3.0

Get the Type

You can get the data type of a variable with the type() function.

x=5
y = "John"
print(type(x))
print(type(y))

Single or Double Quotes?

String variables can be declared either by using single or double quotes:

4
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
x = "John"
# is the same as
x = 'John'

Variable Names

A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)

Example:-

Illegal variable names:

2myvar = "John"
my-var = "John"
my var = "John"

❖ Built-in Data Types

In programming, data type is an important concept.

Variables can store data of different types, and different types can do different things.

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

5
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Binary Types: bytes, bytearray, memoryview

None Type: NoneType

❖ Specify a Variable Type

There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.

Casting in python is therefore done using constructor functions:

 int() - constructs an integer number from an integer literal, a float literal (by removing
all decimals), or a string literal (providing the string represents a whole number)
 float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
 str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals

❖ Multiline Strings
 You can assign a multiline string to a variable by using three quotes:

Example:-

 You can use three double quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""

print(a)
Or three single quotes:
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''

print(a)

Note: in the result, the line breaks are inserted at the same position as in the code.

❖ Strings are Arrays

6
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.

However, Python does not have a character data type, a single character is simply a string
with a length of 1.

Square brackets can be used to access elements of the string.

Example:-

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])
output:-
e

❖ Looping Through a String

Since strings are arrays, we can loop through the characters in a string, with a for loop.

for x in "banana":
print(x)
output :-
b
a
n
a
n
a

❖ String Length

To get the length of a string, use the len() function.

Example:-

a = "Hello, World!"
print(len(a))

❖ Check String

To check if a certain phrase or character is present in a string, we can use the keyword in.

txt = "The best things in life are free!"


print("free" in txt)
output:

7
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
true

Example:-

Print only if "free" is present:

txt = "The best things in life are free!"


if "free" in txt:
print("Yes, 'free' is present.")

Example:-

Check if "expensive" is NOT present in the following text:

txt = "The best things in life are free!"


print("expensive" not in txt)

❖ Slicing

You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the string.

Example:-

Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

❖ Slice From the Start

By leaving out the start index, the range will start at the first character:

Example:-

Get the characters from the start to position 5 (not included):

b = "Hello, World!"
print(b[:5])

❖ Slice To the End

By leaving out the end index, the range will go to the end:

b = "Hello, World!"
print(b[2:])

❖ Negative Indexing
8
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Use negative indexes to start the slice from the end of the string:

Example:-

Get the characters:

From: "o" in "World!" (position -5)


To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])

Example :-

The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())

The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

To concatenate, or combine, two strings you can use the + operator.

a = "Hello"
b = "World"
c=a+b
print(c)

To add a space between them, add a " ":

a = "Hello"
b = "World"
c=a+""+b
print(c)

As we learned in the Python Variables chapter, we cannot combine strings and numbers like
this:

age = 36
txt = "My name is John, I am " + age
print(txt)

9
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places them in the
string where the placeholders {} are:

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

The format() method takes unlimited number of arguments, and are placed into the
respective placeholders:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

You can use index numbers {0} to be sure the arguments are placed in the correct
placeholders:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

The escape character allows you to use double quotes when you normally would not be
allowed:

txt = "We are the so-called \"Vikings\" from the north."

❖ Escape Characters

Other escape characters used in Python:

Code Result

\' Single Quote

\\ Backslash

\n New Line

10
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
\r Carriage Return

\t Tab

\b Backspace

\f Form Feed

\ooo Octal value

\xhh Hex value

The capitalize() method returns a string where the first character is upper case, and the rest
is lower case.

txt = "hello, and welcome to my world."

x = txt.capitalize()

print (x)

The casefold() method returns a string where all the characters are lower case.

txt = "Hello, And Welcome To My World!"

x = txt.casefold()

print(x)

The center() method will center align the string, using a specified character (space is
default) as the fill character.

txt = "GLOBAL COMPUTER EDUCATION"

x = txt.center(20)

print(x)

Using the letter "O" as the padding character:

11
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
txt = "banana"

x = txt.center(20, "O")

print(x)
Output:-
OOOOOOObananaOOOOOOO

The count() method returns the number of times a specified value appears in the string.

txt = "I love apples, apple are my favorite fruit"

x = txt.count("apple")

print(x)

The join() method takes all items in an iterable and joins them into one string.

myTuple = ("John", "Peter", "Vicky")

x = "#".join(myTuple)

print(x)
output:-
John#Peter#Vicky
Example :-
myDict = {"name": "John", "country": "Norway"}
mySeparator = "TEST"

x = mySeparator.join(myDict)

print(x)
Output:-
nameTESTcountry

The translate() method returns a string where some specified characters are replaced with
the character described in a dictionary, or in a mapping table.

#use a dictionary with ascii codes to replace 83 (S) with 80 (P):


mydict = {83: 80}
txt = "Hello Sam!"
print(txt.translate(mydict))
Output:-

12
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Hello Pam!
Example :-
txt = "Hello Sam!"
mytable = str.maketrans("S", "P")
print(txt.translate(mytable))
Output:-
Hello Pam!

The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified
length.

If the value of the len parameter is less than the length of the string, no filling is done.

txt = "50"

x = txt.zfill(10)

print(x)
Output :-
0000000050
Example :-
a = "hello"
b = "welcome to the jungle"
c = "10.000"

print(a.zfill(10))
print(b.zfill(10))
print(c.zfill(10))
output:-
00000hello
welcome to the jungle
000010.000

13
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
❖ Python Operators

Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators
❖ Arithmetic Operators

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

❖ Assignment Operators

Operator Example Same As

14
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

15
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

❖ Comparison Operators

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

❖ Logical Operators

Operator Description Example

and Returns True if both statements x < 5 and x < 10


are true

16
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Or Returns True if one of the x < 5 or x < 4
statements is true

Not Reverse the result, returns False not(x < 5 and x < 10)
if the result is true

❖ Identity Operators

Operator Description Example

is Returns True if both variables are the x is y


same object

is not Returns True if both variables are not x is not y


the same object

❖ Membership Operators

Operator Description Example

in Returns True if a sequence with the specified x in y


value is present in the object

not in Returns True if a sequence with the specified x not in y


value is not present in the object

❖ Bitwise Operators

Operator Name Description Example

& AND Sets each bit to 1 if both bits are 1 x&y

17
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
| OR Sets each bit to 1 if one of two bits is 1 x|y

^ XOR Sets each bit to 1 if only one of two bits is 1 x^y

~ NOT Inverts all the bits ~x

<< Zero fill Shift left by pushing zeros in from the right x << 2
left shift and let the leftmost bits fall off

>> Signed Shift right by pushing copies of the leftmost x >> 2


right bit in from the left, and let the rightmost bits
shift fall off

18
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
19
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
20
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
21
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
22
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
23
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
24
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
25
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
26
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
27
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
❖ Python Collections (Arrays)

There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.


 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.
 Dictionary is a collection which is ordered** and changeable. No duplicate members.

 List

Lists are used to store multiple items in a single variable.

List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.

28
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
 Ordered

When we say that lists are ordered, it means that the items have a defined order, and that
order will not change.

If you add new items to a list, the new items will be placed at the end of the list.

 Changeable

The list is changeable, meaning that we can change, add, and remove items in a list after it
has been created.

 Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example :-
list = ["apple", "banana", "cherry", "apple", "cherry"]
print(list)

 List Length
To determine how many items a list has, use the len() function:

 List Items - Data Types


Example :-
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

List items can be of any data type:


A list can contain different data types:
Example :-
list1 = ["abc", 34, True, 40, "male"]

Python's perspective, lists are defined as objects with the data type 'list':
mylist = ["apple", "banana", "cherry"]
print(type(mylist))

 Access Items
List items are indexed and you can access them by referring to the index number:
Example :-
thislist = ["apple", "banana", "cherry"]
print(thislist[1])

Negative indexing means start from the end

29
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
-1 refers to the last item, -2 refers to the second last item etc.
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])

 Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
a = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(a[2:5])

This example returns the items from the beginning to, but NOT including, "kiwi":
a = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(a[:4])

This example returns the items from "cherry" to the end:


a = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(a[2:])

 Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the list:
example returns the items from "orange" (-4) to, but NOT including "mango" (-1):
a = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(a[-4:-1])

 Check if Item Exists


To determine if a specified item is present in a list use the in keyword:
a = ["apple", "banana", "cherry"]
if "apple" in a:
print("Yes, 'apple' is in the fruits list")

 Change Item Value


To change the value of a specific item, refer to the index number:
a = ["apple", "banana", "cherry"]
a[1] = "blackcurrant"
print(a)
Output:-
['apple', 'blackcurrant', 'cherry']

Change the second and third value by replacing it with one value:
a = ["apple", "banana", "cherry"]
a[1:3] = ["watermelon"]
print(a)

30
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Output:-
['apple', 'watermelon']

The insert() method inserts an item at the specified index:


a = ["apple", "banana", "cherry"]
a.insert(2, "watermelon")
print(a)
Output:-
['apple', 'banana', 'watermelon', 'cherry']

To add an item to the end of the list, use the append() method:
a = ["apple", "banana", "cherry"]
a.append("orange")
print(a)
Output:-
['apple', 'banana', 'cherry', 'orange']

To append elements from another list to the current list, use the extend() method.
a = ["apple", "banana", "cherry"]
b = ["mango", "pineapple", "papaya"]
a.extend(b)
print(a)
Output:-
['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']

The remove() method removes the specified item.


b = ["apple", "banana", "cherry"]
b.remove("banana")
print(b)

If there are more than one item with the specified value, the remove() method removes the
first occurance:
a = ["apple", "banana", "cherry", "banana", "kiwi"]
a.remove("banana")
print(a)
['apple', 'cherry', 'banana', 'kiwi']

 Remove Specified Index


The pop() method removes the specified index.
a = ["apple", "banana", "cherry"]
a.pop(1)
print(a)
Note :-If you do not specify the index, the pop() method removes the last item.

31
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)

The del keyword also removes the specified index:


b = ["apple", "banana", "cherry"]
del b[0]
print(b)

The del keyword can also delete the list completely.


a = ["apple", "banana", "cherry"]
del a

The clear() method empties the list.


The list still remains, but it has no content.
b = ["apple", "banana", "cherry"]
b.clear()
print(b)

 Loop Through a List


You can loop through the list items by using a for loop:
a = ["apple", "banana", "cherry"]
for x in a:
print(x)
Output:-
apple
banana
cherry

 the Index Numbers


You can also loop through the list items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
Output:-
apple
banana
cherry

 While Loop
You can loop through the list items by using a while loop.

32
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Use the len() function to determine the length of the list, then start at 0 and loop your way
through the list items by referring to their indexes.
Remember to increase the index by 1 after each iteration.
thislist = ["apple", "banana", "cherry"]
i=0
while i < len(thislist):
print(thislist[i])
i=i+1

 Looping Using List Comprehension


List Comprehension offers the shortest syntax for looping through lists:
a = ["apple", "banana", "cherry"]
[print(x) for x in a]

 List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in
the name.
Without list comprehension you will have to write a for statement with a conditional test
inside:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
if "a" in x:
newlist.append(x)

print(newlist)
output:-
['apple', 'banana', 'mango']

With list comprehension you can do all that with only one line of code:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)
output:-
['apple', 'banana', 'mango']

33
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
 Iterable
The iterable can be any iterable object, like a list, tuple, set etc.
newlist = [x for x in range(10)]
output:-
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Accept only numbers lower than 5:


newlist = [x for x in range(10) if x < 5]
output:-
[0, 1, 2, 3, 4, 5]
Set the values in the new list to upper case:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x.upper() for x in fruits]
print(newlist)
OUTPUT:-
['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO']

 Sort List Alphanumerically


List objects have a sort() method that will sort the list alphanumerically, ascending, by
default:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
output:-
['banana', 'kiwi', 'mango', 'orange', 'pineapple']

 Sort Descending
To sort descending, use the keyword argument reverse = True:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)

 Case Insensitive Sort


By default the sort() method is case sensitive, resulting in all capital letters being sorted
before lower case letters:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort()
print(thislist)
output:-

34
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
['Kiwi', 'Orange', 'banana', 'cherry']

we can use built-in functions as key functions when sorting a list.


So if you want a case-insensitive sort function, use str.lower as a key function:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)
output:-=
['banana', 'Cherry', 'Kiwi', 'Orange']

 Reverse Order
What if you want to reverse the order of a list, regardless of the alphabet?
The reverse() method reverses the current sorting order of the elements.
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)
output:-
['cherry', 'Kiwi', 'Orange', 'banana']

 Join Two Lists


There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)
output:-
['a', 'b', 'c', 1, 2, 3]

Another way to join two lists is by appending all the items from list2 into list1, one by one:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
output:-
['a', 'b', 'c', 1, 2, 3]

Make a copy of a list with the copy() method:

35
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Output:-
['apple', 'banana', 'cherry']

 Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Example:-
a = ("apple", "banana", "cherry")
print(a)

Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered

When we say that tuples are ordered, it means that the items have a defined order, and that
order will not change.

Unchangeable

Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.

Allow Duplicates

Since tuples are indexed, they can have items with the same value:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Output:-
('apple', 'banana', 'cherry', 'apple', 'cherry')

Check if Item Exists

36
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
output:-
Yes, 'apple' is in the fruits tuple

Loop Through a Tuple

You can loop through the tuple items by using a for loop.
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])
output:-
apple
banana
cherry

 Set
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is unordered, unchangeable*, and unindexed.
Note: Set items are unchangeable, but you can remove items and add new items.
Example:-
thisset = {"apple", "banana", "cherry"}
print(thisset)
output:-
{'banana', 'apple', 'cherry'}

Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to
by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been
created.
37
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Duplicates Not Allowed
Sets cannot have two items with the same value.
a = {"apple", "banana", "cherry", "apple"}

print(a)
output:-
{'banana', 'cherry', 'apple'}

Access Items
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a specified value is present
in a set, by using the in keyword.
thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)
output:
True

To add one item to a set use the add() method.


thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)
output:-
{'cherry', 'banana', 'orange', 'apple'}
To add items from another set into the current set, use the update() method.
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya","banana"}
thisset.update(tropical)
print(thisset)
Output:-
{'banana', 'cherry', 'papaya', 'pineapple', 'mango', 'apple'}

 Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
thisdict = {

38
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
output:-
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Dictionary Items

Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
output:
Ford

Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
output:-
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

39
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
To determine how many items a dictionary has, use the len() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(len(thisdict))
Output:-
3

Dictionary Items - Data Types

The values in dictionary items can be of any data type:


{'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}

The dict() Constructor

It is also possible to use the dict() constructor to make a dictionary.


thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)
output:-
{'name': 'John', 'age': 36, 'country': 'Norway'}

There is also a method called get() that will give you the same result:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.get("model")
print(x)
output:-
Mustang

The keys() method will return a list of all the keys in the dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",

40
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
"year": 1964
}
x = thisdict.keys()
print(x)
output:-
dict_keys(['brand', 'model', 'year'])

The values() method will return a list of all the values in the dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.values()
print(x)
output:-
dict_values(['Ford', 'Mustang', 1964])

Add a new item to the original dictionary, and see that the values list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
output:-
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 1964, 'red'])

The items() method will return each item in a dictionary, as tuples in a list.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964

41
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
}
x = thisdict.items()
print(x)
Output:-
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

Check if Key Exists

To determine if a specified key is present in a dictionary use the in keyword:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
output:-
Yes, 'model' is one of the keys in the thisdict dictionary

Loop Through a Dictionary

You can loop through a dictionary by using a for loop.


When looping through a dictionary, the return value are the keys of the dictionary, but there
are methods to return the values as well.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
Output:-
brand
model
year
Print all values in the dictionary, one by one:
thisdict = {

42
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(thisdict[x])
output:-
Ford
Mustang
1964
You can also use the values() method to return values of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.values():
print(x)
for x in thisdict.keys():
print(x)
Loop through both keys and values, by using the items() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x, y in thisdict.items():
print(x, y)
output:-
brand Ford
model Mustang
year 1964

Nested Dictionaries

A dictionary can contain dictionaries, this is called nested dictionaries.


43
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)
output:
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name':
'Linus', 'year': 2011}}

44
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
❖ Functions

A function is a block of code which only runs when it is called.


You can pass data, known as parameters, into a function.
A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:


Example:
def my_function():
print("Hello from a function")
my_function()
output:-
Hello from a function

Arguments

Information can be passed into functions as arguments.


Arguments are specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full name:
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Output:
Emil Refsnes
Tobias Refsnes
Linus Refsnes

Number of Arguments

By default, a function must be called with the correct number of arguments. Meaning that if
your function expects 2 arguments, you have to call the function with 2 arguments, not
more, and not less.
def my_function(fname, lname):

45
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
print(fname + " " + lname)
my_function("Emil", "Refsnes")
output:
Emil Refsnes

46
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
❖ Classes/Objects

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.
To create a class, use the keyword class:
Example:-
class MyClass:
x=5
p1 = MyClass()
print(p1.x)

❖ 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:
Example:-
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Note: The __init__() function is called automatically every time the class is being used to
create a new object.

❖ The __str__() Function

The __str__() function controls what should be returned when the class object is represented
as a string.
If the __str__() function is not set, the string representation of the object is returned:
Example:-

47
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)

❖ The self Parameter

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:
Example:-
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()

❖ The pass Statement

class definitions cannot be empty, but if you for some reason have a class definition with no
content, put in the pass statement to avoid getting an error.

Example:-
class Person:
pass
# having an empty class definition like this, would raise an error without the pass statement

❖ Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from
another class.

48
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.

❖ Parent Class

Any class can be a parent class, so the syntax is the same as creating any other class:
Example:-
Create a class named Person, with firstname and lastname properties, and
a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()

49
Add:- FF-8,9 Rudraksh Complex, Beside Osia Mall, Gotri Road, Vadodara -390021
Email-ID:- [email protected]

You might also like