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

Python

Python is a versatile programming language created in 1991, widely used for web development, software development, mathematics, and system scripting. It features a simple syntax, supports multiple programming styles, and allows for dynamic typing and easy variable management. The document also covers Python's features like lists, tuples, and variable handling, including comments, data types, and methods for manipulating data structures.

Uploaded by

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

Python

Python is a versatile programming language created in 1991, widely used for web development, software development, mathematics, and system scripting. It features a simple syntax, supports multiple programming styles, and allows for dynamic typing and easy variable management. The document also covers Python's features like lists, tuples, and variable handling, including comments, data types, and methods for manipulating data structures.

Uploaded by

Rohan Pareek
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Introduction to Python

at is Python?

hon is a popular programming language created by Guido van Rossum in 1991. It is used in many fields l
Web development (building websites & web apps)
oftware development (creating programs & tools)
Mathematics (solving equations, graphs, AI, etc.)
ystem scripting (automating tasks on a computer)

at Can Python Do?

hon is a powerful and versatile language that can:


reate web applications (used in websites like YouTube, Instagram)
e used with software to automate tasks
onnect to databases and manage data
andle big data and complex math operations
e used for rapid prototyping and building real-world applications
Why Python?

ython is easy to use and very flexible because:


✔ It works on Windows, Mac, Linux, Raspberry Pi, etc.
✔ The syntax is simple, like writing in English
✔ You can write fewer lines of code compared to other languages
✔ It runs immediately without needing a separate compilation step
✔ It supports multiple styles of programming (procedural, object-oriented, functional)
Python Comments:

• Comments starts with a #, and Python will ignore them.

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

Visual presentation:
📝 ➝ # This is a comment. (Ignored by Python)
➝ "Hello, World!" (Displayed on screen)

• 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.

Explanation:
The print("Hello, World!") command displays "Hello, World!" on the screen.
# This is a comment. is written after the statement. Python ignores everything after #.
Multiline Comments:

Python does not really have a syntax for multiline comments. To add a multiline comment, you
could insert a # for each line.
Python Variables:

Variables are containers for storing data values. Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Variables do not need to be declared with any type, and can even change type after they
have been set.
Casting of variables:

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

Example:
x = str(3)
y = int(3)
z = float(3)

print(x)
print(y)
print(z)

Output:
3
3
3.0
Get the type:

You can get the data type of a variable with the type() function.
Single or Double quotes?

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

Example:
x = "John"
print(x)
#double quotes are the same as single quotes:
x = 'John'
print(x)

Output:
John
John
Case – Sensitive:

Variable names are case-sensitive.


Python Variables 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)
• A variable name cannot be any of the Python keywords.
Multi Words Variable Names:

Variable names with more than one word can be difficult to read. There are several techniques
you can use to make them more readable.

1. Camel case:
Each word, except the first, starts with a capital letter

Example: myVariableName = "John”

2. Pascal case:
Each word starts with a capital letter.

Example: MyVariableName = "John”

3. Snake case:
Each word is separated by an underscore character.

Example: my_variable_name = "John"


Assign Multiple Values:

Python allows you to assign values to multiple variables in one line.


One Value to multiple variables:

And you can assign the same value to multiple variables in one line:
Unpack a collection:
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.
Python Output Variables:

• The Python print() function is often used to output variables.

Example:
x = "🐍 Python is 😍 awesome"
print(x)

Output:
🐍 Python is 😍 awesome

• In the print() function, you output multiple variables, separated by a comma.

Example:
x = "🐍 Python"
y = "💡 is"
z = "😍 awesome"

print(x, y, z)

Output:
🐍 Python 💡 is 😍 awesome
• You can also use the + operator to output multiple variables.

Example:
x = "🐍 Python"
y = "💡 is"
z = "😍 awesome"

print(x+y+z)

Output:
🐍 Python 💡 is 😍 awesome

• For numbers, the + character works as a mathematical operator.

Example:
x=5
y = 10
print(x + y)

Output:
15
Python Global Variable:

Variables that are created outside of a function (as in all of the examples in the previous pages)
are known as global variables. Global variables can be used by everyone, both inside of functions
and outside.

Example:
Create a variable outside of a function and use it inside the function.

x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

Output:
Python is awesome
If you create a variable with the same name inside a function, this variable will be local, and
can only be used inside the function. The global variable with the same name will remain as
it was, global and with the original value.

Example:
Create a variable inside a function, with the same name as the global variable.

x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()

print("Python is " + x)

Output:
Python is fantastic
Python is awesome
Lists in Python:

The data type list is an ordered sequence that is mutable and made up of one or more elements.
A list can have elements of different data types, such as integer, string, tuple or even another list.
List is very useful to group together elements of mixed data types.
Elements of lists are enclosed in squared brackets and are separated by coma.
List indices also starts from 0.

ample:
List1 of mixed data types.

t1 = [20,0.5, “python”]
nt(List1)

tput: [20, 0.5, “python”]

List2 is an example of nested list

t2 = [[“Varun”, 1998], [“Shyam”, 2001], [“Amrit”, 1998]]


nt(List2)

tput: [[“Varun”, 1998], [“Shyam”, 2001], [“Amrit”, 1998]]


• Allows duplicates:
Since lists are indexed, lists can have items with the same value.
Example:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)

Output: ["apple", "banana", "cherry", "apple", "cherry"]

• List length:
To determine how many items a list has, use the len() function.
Example:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))

Output: 3

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

Output: <class 'list'>


List() constructor:
s also possible to use the list() constructor when creating a new list.
ample:
slist = list(("apple", "banana", "cherry"))
nt(thislist)

tput: ['apple', 'banana', 'cherry’]

Access items:
t items are indexed, and you can access them by referring to the index number.
ample:
slist = ["apple", "banana", "cherry"]
nt(thislist[1])

tput: banana

Negative indexing.
gative indexing means start from the end. -1 refers to the last item, -2 refers to the second last item etc.
ample:
slist = ["apple", "banana", "cherry"]
nt(thislist[-1])

tput: cherry
nge of indexes:
an specify a range of indexes by specifying where to start and where to end the range. When specifying a ra
turn value will be a new list with the specified items.
ple:
t = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
thislist[2:5])

t: ['cherry', 'orange', 'kiwi’]

nge of negative indexes:


y negative indexes if you want to start the search from the end of the list.
ple:
t = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
thislist[-4:-1])

t: ['orange', 'kiwi', 'melon’]

ecking if item exist:


ermine if a specified item is present in a list use the in keyword.
ple:
t = ["apple", "banana", "cherry"]
ple" in thislist:
("Yes, 'apple' is in the fruits list")
hange item in the list:
hange the value of a specific item, refer to the index number.
mple:
ist = ["apple", "banana", "cherry"]
ist[1] = "blackcurrant"
t(thislist)

put: ['apple', 'blackcurrant', 'cherry’]

hange a range of item values.


hange the value of items within a specific range, define a list with the new values, and refer to the range of
x numbers where you want to insert the new values.
mple:
ist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
ist[1:3] = ["blackcurrant", "watermelon"]
t(thislist)

put: ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']


Insert items:
o insert a new list item, without replacing any of the existing values, we can use the insert() method.
he insert() method inserts an item at the specified index.
xample:
hislist = ["apple", "banana", "cherry"]
hislist.insert(2, "watermelon")
rint(thislist)

utput: ['apple', 'banana', 'watermelon', 'cherry’]

Append item:
o add an item to the end of the list, use the append() method.
xample:
hislist = ["apple", "banana", "cherry"]
hislist.append("orange")
rint(thislist)

utput: ['apple', 'banana', 'cherry', 'orange']


Extend list:
append elements from another list to the current list, use the extend() method.
mple:
list = ["apple", "banana", "cherry"]
pical = ["mango", "pineapple", "papaya"]
list.extend(tropical)
nt(thislist)

put: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya’]

Remove specified item:


remove() method removes the specified item.
mple:
list = ["apple", "banana", "cherry"]
list.remove("banana")
nt(thislist)

put: ['apple', 'cherry’]

here are more than one item with the specified value, the remove() method removes the first occurrence.
• Remove specified index:
The pop() method removes the specified index.
Example:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)

Output: ['apple', 'cherry’]

The del keyword also removes the specified index.


Example:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

Output: ['banana', 'cherry’]

• Clear the list.


The clear() method empties the list. The list still remains, but it has no content.
Example:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Output: []
• Sort the list:
List objects have a sort() method that will sort the list alphanumerically, ascending, by default.

Example:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)

Output:
['banana', 'kiwi', 'mango', 'orange', 'pineapple’]

Example: sorting list numerically.


thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)

Output:
[23, 50, 65, 82, 100]
Sort list in descending order:
sort descending, use the keyword argument reverse = True.

ample:
slist = ["orange", "mango", "kiwi", "pineapple", "banana"]
slist.sort(reverse = True)
nt(thislist)

tput:
ineapple', 'orange', 'mango', 'kiwi', 'banana’]

Case sensitive sort:


default, the sort() method is case sensitive, resulting in all capital letters being sorted before lower case le

ample:
slist = ["banana", "Orange", "Kiwi", "cherry"]
slist.sort()
nt(thislist)

tput:
iwi', 'Orange', 'banana', 'cherry']
an use built-in functions as key functions when sorting a list. So, if you want a case-insensitive sort function
tr.lower as a key function.

ple:
t = ["banana", "Orange", "Kiwi", "cherry"]
t.sort(key = str.lower)
thislist)

ut:
ana', 'cherry', 'Kiwi', 'Orange’]

verse order:
if you want to reverse the order of a list, regardless of the alphabet? The reverse() method reverses the cu
g order of the elements.

ple:
t = ["banana", "Orange", "Kiwi", "cherry"]
t.reverse()
thislist)

ut:
ry', 'Kiwi', 'Orange', 'banana']
opy a list:
cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes
e in list1 will automatically also be made in list2.

can use the built-in List method copy() to copy a list.

mple:
st = ["apple", "banana", "cherry"]
st = thislist.copy()
(mylist)

ut:
ple', 'banana', 'cherry’]

st() method:
her way to make a copy is to use the built-in method list().

mple:
st = ["apple", "banana", "cherry"]
st = list(thislist)
(mylist)

ut:
ple', 'banana', 'cherry']
Tuples in Python.

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


ple 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.
uple is a collection which is ordered and unchangeable.
ples are written with round brackets.

ple: create a tuple.


uple = ("apple", "banana", "cherry")
thistuple)

ut:
le', 'banana', 'cherry’)

ple items:
items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed, the first item has in
econd item has index [1] etc.

dered:
n we say that tuples are ordered, it means that the items have a defined order, and that order will not chan
Unchangeable:
les are unchangeable, meaning that we cannot change, add or remove items after the tuple has been creat

llows duplicates:
ce tuples are indexed, they can have items with the same value.

mple:
tuple = ("apple", "banana", "cherry", "apple", "cherry")
t(thistuple)

put:
ple', 'banana', 'cherry', 'apple', 'cherry’)

uple length.
determine how many items a tuple has, use the len() function.

mple:
tuple = tuple(("apple", "banana", "cherry"))
t(len(thistuple))

put:
eate tuple with one item:
eate a tuple with only one item, you must add a comma after the item, otherwise Python will not recognize
ple.

mple:
uple = ("apple",)
(type(thistuple))

T a tuple
uple = ("apple")
(type(thistuple))

put:
ss 'tuple'>
ss 'str’>
(tuple3)
• Tuple data type:
Tuple items can be of any data type.

Example:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
print(tuple1)
print(tuple2)
print(tuple3)

Output:
('apple', 'banana', 'cherry’)
(1, 5, 7, 9, 3)
(True, False, False)

A tuple can contain different data types.

Example:
tuple1 = ("abc", 34, True, 40, "male")
print(tuple1)

Output:
('abc', 34, True, 40, 'male')
• Tuple type():
From Python's perspective, tuples are defined as objects with the data type 'tuple’.

Example:
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))

Output:
<class 'tuple’>

• The tuple() constructor:


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

Example:
thistuple = tuple(("apple", "banana", "cherry"))
print(thistuple)

Output:
('apple', 'banana', 'cherry')
• Access tuple items:
You can access tuple items by referring to the index number, inside square brackets.

Example:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

Output:
banana

• Negative indexing:
Negative indexing means start from the end. -1 refers to the last item, -2 refers to the second last item et

Example:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])

Output:
cherry
ange of index:
can specify a range of indexes by specifying where to start and where to end the range. When specifying a
ge, the return value will be a new tuple with the specified items.

mple:
tuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
t(thistuple[2:5])

put:
erry', 'orange', 'kiwi’)

eaving out the start value, the range will start at the first item:

mple:
tuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
t(thistuple[:4])

put:
ple', 'banana', 'cherry', 'orange’)
By leaving out the end value, the range will go on to the end of the tuple:
Example:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango")
print(thistuple[2:])

Output:
('cherry', 'orange', 'kiwi', 'melon', 'mango’)

• Range of negative index:


Specify negative indexes if you want to start the search from the end of
the tuple.

Example:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango")
print(thistuple[-4:-1])

Output:
('orange', 'kiwi', 'melon’)

• Check if item exist:


To determine if a specified item is present in a tuple use the in keyword.
Example:
Python set:
• Sets are used to store multiple items in a single variable.
• A set is a collection which is unordered, unchangeable*, and unindexed.
• Set items are unchangeable, but you can remove items and add new items.
• Sets are written with curly brackets.

Example: Create a set.


thisset = {"apple", "banana", "cherry"}
print(thisset)

Output:
{'apple', 'cherry', 'banana’}

• Duplicates are not allowed.


Example:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)

Output:
{'banana', 'cherry', 'apple'}
• True and 1 is considered the same value.
Example:
thisset = {"apple", "banana", "cherry", True, 1, 2}
print(thisset)

Output:
{True, 2, 'banana', 'cherry', 'apple’}

•Get the Length of a Set:


To determine how many items a set has, use the len() function.

Example:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))

Output:
3
• Data type:
Set items can be of any data type.

Example:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
print(set1)
print(set2)
print(set3)

Output:
{'cherry', 'apple', 'banana’}
{1, 3, 5, 7, 9}
{False, True}

• A set can contain different data types.


Example:
set1 = {"abc", 34, True, 40, "male"}
print(set1)

Output:
{True, 34, 40, 'male', 'abc'}
• Type():
From Python's perspective, sets are defined as objects with the data type 'set’.

Example:
myset = {"apple", "banana", "cherry"}
print(type(myset))

Output:
<class 'set’>

• The set() Constructor:


t is also possible to use the set() constructor to make a set.

Example:
thisset = set(("apple", "banana", "cherry"))
print(thisset)

Output:
{'banana', 'cherry', 'apple'}
cess item:
annot access items in a set by referring to an index or a key. But you can loop through the set items using
or ask if a specified value is present in a set, by using the in keyword.

mple:
et = {"apple", "banana", "cherry"}
in thisset:
t(x)

ut:
y
na
e

mple: Check if "banana" is present in the set.


et = {"apple", "banana", "cherry"}
("banana" in thisset)

ut:
mple: Check if "banana" is NOT present in the set.
set = {"apple", "banana", "cherry"}
t("banana" not in thisset)

put:
e

hange item:
e a set is created, you cannot change its items, but you can add new items.

dd items:
e a set is created, you cannot change its items, but you can add new items. To add one item to a set use th
() method.

mple:
set = {"apple", "banana", "cherry"}
set.add("orange")
t(thisset)

put:
ange', 'banana', 'cherry', 'apple'}
set:
items from another set into the current set, use the update() method.

ple:
t = {"apple", "banana", "cherry"}
al = {"pineapple", "mango", "papaya"}
t.update(tropical)
hisset)

t:
e', 'mango', 'cherry', 'pineapple', 'banana', 'papaya’}

iterable:
bject in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionari

ple:
t = {"apple", "banana", "cherry"}
= ["kiwi", "orange"]
t.update(mylist)
hisset)

t:
ana', 'cherry', 'apple', 'orange', 'kiwi'}
Remove item:
To remove an item in a set, use the remove(), or the discard() method.
Example:
hisset = {"apple", "banana", "cherry"}
hisset.remove("banana")
print(thisset)

Output:
{'apple', 'cherry’}

If the item to remove does not exist, remove() will raise an error.
Example:
hisset = {"apple", "banana", "cherry"}
hisset.discard("banana")
print(thisset)

Output:
{'cherry', 'apple'}
can also use the pop() method to remove an item, but this method will remove a random item, so you cann
what item that gets removed. The return value of the pop() method is the removed item.

le:
= {"apple", "banana", "cherry"}
sset.pop()
) #removed item
hisset) #print the set

t:
a
ry', 'apple’}

clear() method empties the set.


le:
= {"apple", "banana", "cherry"}
.clear()
hisset)

t:
• The del keyword will delete the set completely.
Example:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)

• Loop items:
You can loop through the set items by using a for loop.
Example:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)

Output:
banana
apple
cherry
Python 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.
Dictionaries are written with curly brackets and have keys and values.

xample:
hisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964

rint(thisdict)

utput:
brand': 'Ford', 'model': 'Mustang', 'year': 1964}
ctionary items:
onary items are ordered, changeable, and do not allow duplicates. Dictionary items are presented in key:va
, and can be referred to by using the key name.

mple: Print “brand” value.


ct = {
and": "Ford",
del": "Mustang",
ar": 1964

thisdict["brand"])

ut:
Duplicates are not allowed:
ictionaries cannot have two items with the same key.
xample:
hisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020

rint(thisdict)

utput:
brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Length of dictionary:
o determine how many items a dictionary has, use the len() function.
xample:
hisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020

rint(len(thisdict))
Data types:
he values in dictionary items can be of any data type.
xample:
isdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]

int(thisdict)

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

Type():
ctionaries are defined as objects with the data type 'dict’.
xample:
isdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964

int(type(thisdict))
dist() Constructor:
t is also possible to use the dict() constructor to make a dictionary.
xample:
hisdict = dict(name = "John", age = 36, country = "Norway")
rint(thisdict)

Output:
'name': 'John', 'age': 36, 'country': 'Norway’}

Accessing item:
ou can access the items of a dictionary by referring to its key name, inside square brackets.
xample:
hisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964

= thisdict["model"]
rint(x)

Output:
Mustang

You might also like