UNIT-01 PYTHON BASICS
UNIT-01 PYTHON BASICS
UNIT-01
What is Python?
Python is a very popular general-
purpose interpreted, interactive,
object-oriented, and high-level
programming language.
Python It was created by Guido van Rossum,
Introduction and released in 1991.
It is used for:
1. web development (server-side),
2. software development,
3. mathematics,
4. system scripting.
Python can be used on a server to
create web applications.
Python can be used alongside
software to create workflows.
What can Python can connect to database
Python do? 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 production-
ready software development.
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
Python when testing code.
Comments Creating a Comment
Comments starts with a #, and Python will ignore
them:
Example #This is a comment
print("Hello,
World!")
Example
#This is a comment
#written in
#more than just one
Multiline line
print("Hello, World!")
Comments Or, not quite as intended, you can use a multiline string.
Since 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!")
Variables are containers for storing data
values.
Creating Variables
Variables Python has no command for declaring a
variable.
OR A variable is created the moment you first
Names assign a value to it.
Examplex = 5
y = "John"
print(x)
print(y) OUTPUT :
5
John
Casting Get the Type
Variables do not
need to be You can get the
If you want to
declared with any data type of a
particular type, specify the data
variable with
and can even type of a variable,
the type() function.
change type after this can be done
with casting. EXAMPLE
they have been x=5
set.
x=4 # x is of type int
EXAMPLE y = "John"
x = "Sally" # x is now of x = str(3) print(type(x
type str y = int(3) OUTPU )) OUTPUT
print(x) z = float(3) T print(type(y <class
print(x) 3 )) 'int'>
print(y) 3 <class
print(z) 3.0 'str'>
Single or Double Case-Sensitive
Quotes?
String variables can
Variable names are
be declared either
by using single or case-sensitive.
double quotes: Example
VARIABLES x = "John"
print(x)
This will create two
variables:
#double quotes are a=4
the same as single A = "Sally"
quotes: #A will not overwrite
x = 'John' a
print(x) print(a)
print(A)
OUTPU
OUTPU
T John
T:
John
4
Sally
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
Variable underscore character
Names 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.
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John" OUTPUT
John
EXAMPLE myvar2 = "John"
John
print(myvar) John
print(my_var) John
print(_my_var) John
print(myVar) John
print(MYVAR)
print(myvar2)
Python allows you to assign values to multiple
variables in one line:
Python x, y, z = "Orange", "Banana",
Variables "Cherry" OUTPUT:
Orange
- Assign print(x)
print(y)
Banana
Multiple print(z)
Cherry
Values
And you can assign the same value to
multiple variables in one line:
x=y=z=
"Orange"
One Value OUTPUT:
Orange
to Multiple print(x)
print(y) Orange
Variables print(z) Orange
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
Unpack a fruits = ["apple", "banana",
Collection "cherry"]
OUTPUT:
x, y, z = fruits
apple
print(x) banana
print(y) cherry
print(z)
The Python print() function is often
used to output variables.
x = "Python"
y = "is"
Output z = "awesome"
print(x, y, z)
Variables O/P: Python is awesome
Global Variables
Variables that are created outside of a
function are known as global variables.
Global variables can be used by everyone,
both inside of functions and outside.
Global
Variables x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Output:
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2,
123, 'john')
Python range() is an in-built function in Python which returns a
sequence of numbers starting from 0 and increments to 1 until it
reaches a specified number.
Python We use range() function with for and while loop to generate a
sequence of numbers.
range(start, Following
stop, step) is the syntax of the function:
Ranges
Function
Here is the description of the parameters used:
1. start: Integer number to specify starting position, (Its optional,
Default: 0)
2. stop: An integer number specifying at which position to stop(Its
mandatory)
3. step: Integer number to specify increment, (Its optional, Default: 1)
for i in range(5): for i in range(1, 5):
print(i) print(i)
0 1
1 2
2 3
4
Examples 3
4
Python dictionaries are kind of hash table type.A dictionary
key can be almost any Python type, but are usually numbers
or strings.
Python dictionary is like associative arrays or hashes found in
Python Perl and consist of key:value pairs.
The pairs are separated by comma and put inside curly
Dictionary brackets {}. To establish mapping between key and value,
Data Type the semicolon':' symbol is put between the two.
Dictionaries are enclosed by curly braces ({ }) and values
dict = {}
can be assigned and accessed using square braces ([]). For
dict['one'] = "This is one"
example −
dict[2] = "This is two"
Python
Arithmetic
Operators
These operators compare the values on either sides
of them and decide the relation among them. They
are also called Relational operators.
Assume variable a holds 10 and variable b holds 20,
then
Python
Comparison
Operators
Assignment operators are used to assign values to
variables. Following is a table which shows all Python
assignment operators.
Python
Assignment
Operators
Bitwise operator works on bits and performs bit by bit
operation. These operators are used to compare
binary numbers.
Python
Bitwise
Operators
Python logical operators are used to combile two or
more conditions and check the final result.
Python
Logical
Operators
Python's membership operators test for membership
in a sequence, such as strings, lists, or tuples. −
Python
Membership
Operators
Identity operators compare the memory locations of
two objects.
Python
Identity
Operators
Sr.N Operator & Description
o.
1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus (method names for the last two
are +@ and -@)
3 * / % //
Python 4
Multiply, divide, modulo and floor division
+-
Addition and subtraction
Operators 5 >> <<
Right and left bitwise shift
Precedence 6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
8 <= < > >=
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators
# Program for Fahrenheit to Celsius Conversion
in Python
def fahrenheit_to_celsius(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
Program for return celsius
Hello Samay
Hello
Pratima
Hello Steven
Python also accepts function recursion, which means
a defined function can call itself.
Recursion is a common mathematical and
programming concept. It means that a function calls
itself. This has the benefit of meaning that you can
loop through data to reach a result.
# Recursive function
def recursive_fibonacci(n):
if n <= 1: Fibonacci
return n series:
else: 0
Example for return(recursive_fibonacci(n-1) +
recursive_fibonacci(n-2))
1
1
Recursion 2
3
n_terms = 10
5
# check if the number of terms is valid 8
if n_terms <= 0: 13
print("Invalid input ! Please input a positive value") 21
else: 34
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))
A function is a block of organized, reusable code that is
used to perform a single, related action. Functions provide
better modularity for your application and a high degree of
code reusing.
The concept of module in Python further enhances the
modularity. You can define more than one related functions
Python - together and load required functions.
Modules A module is a file containing definition of functions,
classes, variables, constants or any other Python object.
Contents of this file can be made available to any other
program. Python has the import keyword for this purpose.
import math
print ("Square root of 100:",
math.sqrt(100))
Sr.N Name & Brief Description
o.
1 os
This module provides a unified interface to a number of operating system
functions.
2 string
This module contains a number of functions for string processing
3 re
This module provides a set of powerful regular expression facilities. Regular
expression (RegEx), allows powerful string search and matching for a pattern in a
Built in 4
string
math
Modules This module implements a number of mathematical operations for floating point
numbers. These functions are generally thin wrappers around the platform C
library functions.
5 cmath
This module contains a number of mathematical operations for complex numbers.
6 datetime
This module provides functions to deal with dates and the time within a day. It
wraps the C runtime library.
7 gc
This module provides an interface to the built-in garbage collector.
8 asyncio
This module defines functionality required for asynchronous processing
9 Collections
This module provides advanced Container datatypes.
10 Functools
11 operator
Functions corresponding to the standard operators.
12 pickle
Convert Python objects to streams of bytes and back.
13 socket
Low-level networking interface.
14 sqlite3
A DB-API 2.0 implementation using SQLite 3.x.
15 statistics
Mathematical statistics functions
16 typing
Support for type hints
17 venv
Creation of virtual environments.
18 json
Encode and decode the JSON format.
19 wsgiref
WSGI Utilities and Reference Implementation.
20 unittest
Unit testing framework for Python.
21 random
Generate pseudo-random numbers
Any text file with .py extension and containing Python
code is basically a module.
It can contain definitions of one or more functions,
variables, constants as well as classes.
User Any Python object from a module can be made
available to interpreter session or another Python
Defined script by import statement. A module can also include
runnable code.
Modules
Creating a module is nothing but saving a Python
code with the help of any editor. Let us save the
following code as mymodule.py
def SayHello(name):
print ("Hi {}! How are
you?".format(name))
Create a return
The import Let us save the following code having three functions
as mymodule.py.
Statement def sum(x,y):
return x+y The import
mymodule statement loads
def all the functions in this
average(x,y): module in the current
return namespace. Each function in
(x+y)/2 the imported module is an
attribute of this module
def object.
power(x,y):
return x**y
Dot notation is a syntax used in programming
languages like Python to access an object’s attributes
and methods, making it easier to search complex
data structures.
When we use dot notation in Python, we usually write
[object we want to access][dot][attribute or method].
: Colon
Must
if first condition:
first body
elif second condition:
second body
elif third condition:
third body
else:
fourth body
CONDITIONAL CONSTRUCT – if else
STATEMENT
FLOW CHART
False
Condition ? Statement 1 Statement 2
Main True
Body
Statement 1
else
Statement 2 body
CONDITIONAL CONSTRUCT – if else
STATEMENT
else is
missing, it
is an
optional
statement
OUT
PUT
CONDITIONAL CONSTRUCT
: Colon
Must
else is
used
OUT
PUT
EXAMPLES – if elif STATEMENT
READ AS
18 is less
than age
and
18 is less
than 60
OUTPU
T
3. ITERATION OR LOOPING
while loop
for loop
while loop
FLOW
CHART
while
loop
while loop - programs
# Natural Numbers generation
OUTPUT
while loop - programs
# Calculating Sum of Natural
Numbers
OUTPUT
for LOOP
OUTPU
T
for LOOP
range KEYWORD
for LOOP - range
KEYWORD
The range() function returns
a sequence of numbers, starting
from 0 by default, and
increments by 1 (by default),
and ends at a specified number.
OUTPU
T
for LOOP - range KEYWORD
OUTPU
T
for LOOP - range KEYWORD
# print string character by
character
OUTP
UT
else statement in loop
2. continue STATEMENT
4. BRANCHING OR JUMPING
STATEMENTS
1. break STATEMENT
Loop
Condition ? break
causes
jump
True
Statement 1
break
1. break STATEMENT
OUT
PUT
2. continue STATEMENT
Loop False
Condition ?
True
Statement 1
Statements
ignored or continue
skipped
continue
Statement n
causes
jump
2. continue STATEMENT
pass in loop
pass in has no
loop output
BREAK CONTINUE
It terminates the It terminates only the
execution of current iteration of
remaining iteration the loop.
Differen of the loop.
ce 'break' resumes the 'continue' resumes
control of the the control of the
Between program to the end program to the next
break of loop enclosing iteration of that loop
and that 'break'. enclosing 'continue'.
It causes early It causes early
continue termination of loop. execution of the next
iteration.
'break' stops the 'continue' do not
continuation of stops the continuation
What is namespace:
A namespace is a system that has a unique name for each
and every object in Python.
An object might be a variable or a method. Python itself
Namespac maintains a namespace in the form of a Python dictionary.
Let’s go through an example, a directory-file system
es and structure in computers. Needless to say, that one can
have multiple directories having a file with the same
Scope in name inside every directory.
Python But one can get directed to the file, one wishes, just by
specifying the absolute path to the file.
Real-time example, the role of a namespace is like a
surname. One might not find a single “Alice” in the class
there might be multiple “Alice” but when you particularly
ask for “Alice Lee” or “Alice Clark” (with a surname), there
will be only one (time being don’t think of both first name
and surname are same for multiple students).
When Python interpreter runs solely without any user-
defined modules, methods, classes, etc. Some functions
like print(), id() are always present, these are built-in
namespaces.
When a user creates a module, a global namespace gets
created, later the creation of local functions creates the
local namespace.
The built-innamespace encompasses the global
namespace and the global namespace encompasses
the local namespace.
Types of
# var1 is in the global
namespaces : namespace
var1 = 5
def some_func():
# var2 is in the local namespace
var2 = 6
def some_inner_func():
# var3 is in the nested local
# namespace
var3 = 7
Raise an exception
As a Python developer you can choose to throw an
exception if a condition occurs.