Python-Basic-Elements
Python-Basic-Elements
A. Y. : 2024-25
Python Programming
• Started as a hobby project by Guido Van Rossum and was first
released in 1991.
• An object-oriented programming construct language
• An open-source language
• A high-level language
• Uses an interpreter and hence called an interpreted language
• Supports minimalism and modularity to increase readability and
minimize time and space complexity
• Comes with a vast collection of libraries
• Python doesn’t convert its code into machine code
• Python converts the source code into a series of byte codes which is
stored with a .pyc or .pyo format.
• this byte code can’t be identified by CPU
• need for a mediator to do this task (Interpreter), In most PCs, Python
interpreter is installed at /usr/local/bin/python3.8.
• The python virtual machine To execute Bytecodes
Real World Applications
• Web Development- Django, Pyramid, Flask, and Bottle for developing web
frameworks
• Game Development- PySoy (a 3D game engine that supports Python 3)
and PyGame are two Python-based libraries used widely for game
development.
• Scientific and Numeric Applications-
• SciPy (scientific numeric library)
• Pandas (data analytics library)
• IPython (command shell)
• Numeric Python (fundamental numeric package)
• Natural Language Toolkit (Mathematical And text analysis)
• Artificial Intelligence and Machine Learning
• Language Development-many new programming languages such as Boo,
Swift, CoffeeScript, Cobra, and OCaml.
Real World Applications
• Desktop GUI- PyQt, PyGtk, Kivy, Tkinter, WxPython, PyGUI, and PySide are
some of the best Python-based GUI frameworks that allow developers to
create highly functional Graphical User Interfaces (GUIs)
• Software Development
• Enterprise-level/Business Applications
• Education programs and training courses
• Operating Systems
• Web Scraping Applications- BeautifulSoup, MechanicalSoup, Scrapy, LXML,
Python Requests, Selenium, and Urllib are some of the best Python-based
web scraping tools.
• Image Processing and Graphic Design Applications- Python is used in
several 3D animation packages such as Blender, Houdini, 3ds Max, Maya,
Cinema 4D, and Lightwave, to name a few.
Understanding code
Indentation matters to meaning the code
Block structure indicated by indentation
The first assignment to a variable creates it
Dynamic typing: no declarations, names don’t have types, objects
do
Assignment uses = and comparison uses ==
For numbers + - * / % are as expected.
Use of + for string concatenation.
Use of % for string formatting (like printf in C)
Logical operators are words (and,or,not) not symbols
The basic printing command is print
Whitespace
Whitespace is meaningful in Python, especially
indentation and placement of newlines
Use a newline to end a line of code
Use \n when must go to next line prematurely
No braces {} to mark blocks of code, use consistent
indentation instead
• First line with less indentation is outside of the block
• First line with more indentation starts a nested block
Colons start of a new block in many constructs, e.g.
function definitions, then clauses
Comments
Start comments with #, rest of line is ignored
Can include a “documentation string” as the first line of
a new function or class you define
Development environments, debugger, and other tools
use it: it’s good style to include one
def fact(n):
“““fact(n) assumes n is a positive
integer and returns facorial of n.”””
assert(n>0)
return 1 if n==1 else n*fact(n-1)
Naming Rules
Names are case sensitive and cannot start with a
number. They can contain letters, numbers, and
underscores.
bob Bob _bob _2_bob_ bob_2 BoB
Keywords
and, assert, break, class, continue,
def, del, elif, else, except, exec,
finally, for, from, global, if, import,
in, is, lambda, not, or, pass, print,
raise, return, try, while
Data types
Literals
• In the following example, the parameter values passed to the print
function are all technically called literals
• More precisely, “Hello” and “Programming is fun!” are called textual literals,
while 3 and 2.3 are called numeric literals
>>> print("Hello")
Hello
>>> print("Programming is fun!")
Programming is fun!
>>> print(3)
3
>>> print(2.3)
2.3
Simple Assignment Statements
• A literal is used to indicate a specific value, which can be assigned to
a variable
>>> x = 2
x is a variable and 2 is its value >>> print(x)
2
>>> x = 2.3
>>> print(x)
2.3
Simple Assignment Statements
• A literal is used to indicate a specific value, which can be assigned to
a variable
>>> x = 2
x is a variable and 2 is its value >>> print(x)
2
x can be assigned different values; >>> x = 2.3
hence, it is called a variable >>> print(x)
2.3
Simple Assignment Statements: Box View
• A simple way to view the effect of an assignment is to assume that
when a variable changes, its old value is replaced
>>> x = 2 x = 2.3
Before After
>>> print(x)
2 x 2 x 2.3
>>> x = 2.3
>>> print(x)
2.3
Simple Assignment Statements: Actual View
• Python assignment statements are actually slightly different from the
“variable as a box” model
• In Python, values may end up anywhere in memory, and variables are used to
refer to them
x = 2.3
>>> x = 2
Before After
>>> print(x) What will
2 2 happen to
x 2 x
>>> x = 2.3 value 2?
>>> print(x)
2.3
2.3
Garbage Collection
• Interestingly, as a Python programmer you do not have to worry about
computer memory getting filled up with old values when new values
are assigned to variables
After
Memory location
• Python will automatically clear old
values out of memory in a process x 2 X will be automatically
reclaimed by the
known as garbage collection garbage collector
2.3
Assigning Input
• So far, we have been using values specified by programmers and printed
or assigned to variables
• How can we let users (not programmers) input values?
• This form of assignment might seem strange at first, but it can prove
remarkably useful (e.g., for swapping values)
Simultaneous Assignment
• Suppose you have two variables x and y, and you want to swap their
values (i.e., you want the value stored in x to be in y and vice versa)
>>> x = 2
>>> y = 3
>>> x = y
>>> y = x
>>> x X CANNOT be done with
two simple assignments
3
>>> y
3
Simultaneous Assignment
• Suppose you have two variables x and y, and you want to swap their
values (i.e., you want the value stored in x to be in y and vice versa)
>>> x = 2
Thus far, we have been using >>> y = 3
different names for >>> temp = x CAN be done with
variables. These names
are technically called
identifiers
>>> x = y
>>> y = temp three simple assignments,
but more efficiently with
simultaneous assignment
>>> x
3
>>> y
2
>>>
Identifiers
• Python has some rules about how identifiers can be formed
• Every identifier must begin with a letter or underscore, which may be
followed by any sequence of letters, digits, or underscores
>>> x1 = 10
>>> x2 = 20
>>> y_effect = 1.5
>>> celsius = 32
>>> 2celsius
File "<stdin>", line 1
2celsius
^
SyntaxError: invalid syntax
Identifiers
• Python has some rules about how identifiers can be formed
• Identifiers are case-sensitive
>>> x = 10
>>> X = 5.7
>>> print(x)
10
>>> print(X)
5.7
Identifiers
• Python has some rules about how identifiers can be formed
• Some identifiers are part of Python itself (they are called reserved words or
keywords) and cannot be used by programmers as ordinary identifiers
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Python Keywords
Identifiers
• Python has some rules about how identifiers can be formed
• Some identifiers are part of Python itself (they are called reserved words or
keywords) and cannot be used by programmers as ordinary identifiers
>>> for = 4
File "<stdin>", line 1
An example… for = 4
^
SyntaxError: invalid syntax
Expressions
• You can produce new data (numeric or text) values in your program
using expressions
>>> x = 2 + 3
This is an expression that uses the >>> print(x)
addition operator 5
>>> print(5 * 7)
35
>>> print("5" + "7")
57
Expressions
• You can produce new data (numeric or text) values in your program
using expressions
>>> x = 2 + 3
This is an expression that uses the >>> print(x)
addition operator 5
>>> print(5 * 7)
This is another expression that uses the 35
multiplication operator >>> print("5" + "7")
57
Expressions
• You can produce new data (numeric or text) values in your program
using expressions
>>> x = 2 + 3
This is an expression that uses the >>> print(x)
addition operator 5
>>> print(5 * 7)
This is another expression that uses the 35
multiplication operator >>> print("5" + "7")
57
This is yet another expression that uses the
addition operator but to concatenate (or glue)
strings together
Expressions
• You can produce new data (numeric or text) values in your program
using expressions
• A Python module file is just a text file with a .py extension, which can
be created using any program for editing text (e.g., notepad or vim)
Programming Environments and IDLE
• A special type of software known as a programming environment
simplifies the process of creating modules/programs
• Operators are used to form and combine expressions into more complex
expressions (e.g., the expression x + 3 * y combines two expressions
together using the + and * operators)
Summary
• In Python, assignment of a value to a variable is done using the equal
sign (i.e., =)
• Using assignments, programs can get inputs from users and manipulate
them internally
if Boolean expression:
block of code
else:
block of code
Example:
if x%2 == 0:
print(“Even”)
else:
print(“Odd”)
Print(“Done with conditional”)
a=5
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
• Python Program to Add Two Numbers
• Python Program to Calculate the Area of a Triangle
• Python Program to Swap Two Variables
• Python Program to Convert Kilometers to Meters
• Python Program to Check if a Number is Positive, Negative or 0
• Python Program to Check Leap Year
• Python Program to Check Prime Number
Lists:
• List items are:
• Ordered
• Changeable
• allow duplicate values
• Indexed
• List items can contain different data types.
Python List
• an ordered sequence of items
• All the items in a list do not need to be of the same type.
• Items separated by commas are enclosed within brackets [ ].
• Example:
a = [1, 2.2, 'python']
• The index starts from 0 in Python.
• Lists are mutable, meaning, the value of elements of a list can be
altered.
Slicing Operator ‘[ ]’
• to extract an item or a range of items from a list.
• Example:
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])
# a[5:] = [30, 35, 40]
print("a[5:] = ", a[5:])
List Length
• len() function: To determine how many items a list has.
• Example:
if "apple" in fruits:
print("Yes, 'apple' is in the fruits list")
insert() method
• The insert() method inserts an item at the specified index
• Syntax: list.insert(pos, elmnt)
• Example:
# Demonstration of list insert() method
odd = [1, 9]
odd.insert(1,3)
print(odd)
append() method
• To add an item to the end of the list
• Example:
# Appending and Extending lists in Python
odd = [1, 3, 5]
odd.append(7)
print(odd)
extend() method
• To append elements from another list to the current list
• We can add one item to a list using the append() method or add several
items using extend() method.
• Example:
# Appending and Extending lists in Python
odd = [1, 3, 5]
odd.append(7)
print(odd)
odd.append([7,6])
print(odd)
• We can also use + operator to combine two lists. This is also called
concatenation.
• The * operator repeats a list for the given number of times.
• Example:
# Concatenating and repeating lists
odd = [1, 3, 5]
print(odd + [9, 7, 5])
print(["re"] * 3)
remove() method
• removes the specified item.
• Example:
• print(list(range(10)))
• print(list(range(2, 8)))
• Example 2:
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)): #i will take values:
print(fruits[i])
Test Your skills:
• Print First 10 natural numbers using for loop
• Python program to find the factorial of a number provided by the user.
• Print the following pattern:
1
12
123
1234
12345
• Program to print squares of all numbers present in a list
• Reverse the following list using for loop (Hint: Just print it in reverse order)
[1, 2, 3, 4, 5]
while loop:
• used to iterate over a block of code as long
as the test expression (condition) is true.
• Syntax:
while test_expression:
Body of while
• Example 1:
n = int(input("Enter n: "))
sum = 0 # initialize sum and counter
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
print("The sum is", sum) # print the sum
• Example 2: (while loop with else)
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
break statement
• The break statement terminates
the loop containing it.
• If the break statement is inside a
nested loop (loop inside another
loop), the break statement will
terminate the innermost loop.
• Syntax: break
• Example:
for val in "string":
if val == "i":
break
print(val)
print("The end")
continue statement
• The continue statement is used to skip the
rest of the code inside a loop for the
current iteration only.
• Loop does not terminate but continues on
with the next iteration.
• Example:
for val in "string":
if val == "i":
continue
print(val)
print("The end")
Using a While Loop with list
• Example:
fruits = ["apple", "banana", "cherry"]
i=0
while i < len(fruits):
print(fruits[i])
i=i+1
sort() method
• sort the list alphanumerically, ascending, by default
• Example:
t = [100, 50, 65, 82, 23]
t.sort()
print(t)
• To sort descending, use the keyword argument reverse = True
• Example:
t = [100, 50, 65, 82, 23]
t.sort(reverse = True)
print(t)
reverse() Method
• method reverses the sorting order of the elements.
• Example:
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
Try yourself
• Copy a list from one to another.
• Make change in the first list.
• Example:
thislist = ["apple", "banana", "cherry"]
mylist = thislist
thislist[2]="bit"
print(mylist)
print(thislist)
• Example:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
thislist[2]="bit"
print(mylist)
print(thislist)
Copy method
• Make a copy of a list with the copy() method:
• Example:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
thislist[2]="bit"
print(mylist)
print(thislist)
Try yourself
• Join two Lists
• Append()
• Extend()
• + operator
• Example:
l1 = ["a", "b" , "c"]
l2 = [1, 2, 3]
for x in l2:
l1.append(x)
print(l1)
List Methods
Python Tuples
• Tuples are used to store multiple items in a single variable.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
• Example:
fruits = ("apple", "banana", “apple")
print(fruits)
print(type(fruits))
Tuple Items
• Ordered - it means that the items have a defined order, and that
order will not change.
• Unchangeable - we cannot change, add or remove items after the
tuple has been created.
• allow duplicate values
• A tuple can contain different data types
• Example:
tuple1 = ("abc", 34, True, 40, "male")
• Example:
Fruits_tuple = ("apple", "banana", "cherry")
print(Fruit_tuple[1])
Access Tuple Elements
Indexing
Example 1:
Fruits_tuple = ("apple", "banana", "cherry")
print(Fruit_tuple[1])
Example 2:
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4
• Negative Indexing: print(Fruit_tuple[-2])
• Slicing: print(Fruit_tuple[-2:-1])
• Check if Item Exists (using in keyword)
• Example 1:
t = ("apple", "banana", "cherry")
if "apple" in t:
print("Yes, 'apple' is in the fruits tuple")
Update Tuples
• You cannot add items to a tuple
• You can convert the tuple into a list, change the list/ add an item, and convert the
list back into a tuple.
• Example 1:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
x = ("apple", "banana", "cherry")
print("x:",id(x))
y = list(x)
y[1] = "kiwi"
print("y:",id(y))
x = tuple(y)
print("x:",id(x))
print("y:",id(y))
• Example 2:
# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])
my_tuple[1] = 9