UNIT 1 PythonNotes
UNIT 1 PythonNotes
1.Introduction to Python:
1.2 Features
Python provide lot of features for the programmers.
Object-Oriented and Functional
Python is an object-oriented language, from the ground up. It follow object and class
concept. Its class model supportsadvanced notions such as polymorphism, operator
overloading, and multiple inheritance; Like C++, Python supports procedure-oriented
programming as well as object-oriented programming.In addition to its original procedural
(statement-based) and object-oriented (classbased)paradigms, python borrows functional
programming concepts —a set that by most measures includes generators, comprehensions,
closures,maps, decorators, anonymous function lambdas, and first-class function objects.
Free and Open Source
Python is completely free to use and distribute. As with other open source software,such
as Tcl, Perl, Linux, and Apache, you can fetch the entire Python system’s sourcecode for free
on the Internet. There are no restrictions on copying it, embedding it inyour systems, or
shipping it with your products. This is called FLOSS(Free/Libre and Open Source Software).
Portable
The standard implementation of Python is written in portable ANSI C, and it compilesand
runs on virtually every major platform currently in use. For example, Python programsrun
today on everything from PDAs to supercomputers. Python can run equally on different
platforms such as Windows, Linux, Unix and Macintosh etc.
Relatively Easy to Use and Learn
Compared to alternative languages, python programming is extremely simple to learn.
It offers an easy to understand syntax, simple setup, and has many practical applications in
web development. To run a Python program, you simply type it and
run it. There are no intermediate compile and link steps, like there are for languagessuch as C
or C++. Python executes programs immediately, which makes for an interactive
programming experience and rapid turnaround after program changes
Interpreted
Python is an interpreted language i.e. interpreter executes the code line by line at a time.
When you use an interpreted language like Python, there is no separate compilation and
execution steps. You just run the program from the source code. This makesdebugging easy
and thus suitable for beginners. Internally, Python converts the source code into an
intermediate form called bytecodes and then translates this into the native language of your
specific computer and then runs it. You just run your programs and you never have to worry
about linking and loading with libraries, etc.
Extensible
If needed, Python code can be written in other languages like C++. This makes Python an
extensible language, meaning that it can be extended to other languages. Python extensions
can be written in C and C++ for the standard implementation of python in C. The Java
language implementation of python is called Jython. Finally, there is Ironpython, the C#
implementation for the .NET.
Powerful
From a features perspective, Python is something of a hybrid. Its toolset places it between
traditional scripting languages (such as Tcl, Scheme, and Perl) and systems development
languages (such as C, C++, and Java).Python is useful for large-scale development projects.
The following features make Python language more powerful.
● Dynamic typing
● Automatic memory management
● Programming-in-the-large support
● Built-in object types
● Built-in tools
● Library utilities
Example:
1.Hello, World! in python is the first python program which we learn when we start learning
any program. It’s a simple program that displays the message “Hello, World!” on the screen.
Here’s the “Hello World” program:
print("Hello, World!")
Output: Hello World
1.3 Variables:
In Python, variables are used to store data that can be referenced and manipulated
during program execution. A variable is essentially a name that is assigned to a value. Unlike
many other programming languages, Python variables do not require explicit declaration of
type. The type of the variable is inferred based on the value assigned. Variables act as
placeholders for data. They allow us to store and reuse values in our program.
Example:
# Variable 'x' stores the integer value 5
x=5
print(x)
print(name)
Output:
5
Keerthi
Valid Example:
age = 21
_colour = "lilac"
total_score = 90
Invalid Example:
Example:
# Casting variables
s = "10" # Initially a string
n = int(s) # Cast string to integer
cnt = 5
f = float(cnt) # Cast integer to float
age = 25
s2 = str(age) # Cast integer to string
# Display results
print(n)
print(f)
print(s2)
Output:
10
5.0
25
This code assigns variable ‘x’ different values of few Python data types – int, float, list, set
and string. Each assignment replaces the previous value, making ‘x’ take on the data type
and value of the most recent assignment.
b = 5.0
print(type(b))
c = 2 + 4j
print(type(c))
Output
<class 'int'>
<class 'float'>
<class 'complex'>
1.4.2. Sequence Data Types in Python
The sequence Data Type in Python is the ordered collection of similar or different Python
data types. Sequences allow storing of multiple values in an organized and efficient fashion.
There are several sequence data types of Python:
Python String
Python List
Python Tuple
String Data Type
Python Strings are arrays of bytes representing Unicode characters. In Python, there is
no character data type Python, a character is a string of length one. It is represented by str
class.
Strings in Python can be created using single quotes, double quotes, or even triple quotes. We
can access individual characters of a String using index.
Example:
s = 'Welcome to the CSE World'
print(s)
Output
[1, 2, 3]
Example:
t2 = ('tech', 'For')
print("\nTuple with the use of String: ", t2)
Output
Tuple with the use of String: ('tech', 'For')
Note – The creation of a Python tuple without the use of parentheses is known as Tuple
Packing.
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)
Output
Set with the use of String: {'s', 'o', 'F', 'G', 'e', 'k', 'r'}
Set with the use of List: {'Geeks', 'For'}
1.4.5. Dictionary Data Type
A dictionary in Python is a collection of data values, used to store data values like a
map, unlike other Python Data Types that hold only a single value as an element, a
Dictionary holds a key: value pair. Key-value is provided in the dictionary to make it more
optimized. Each key-value pair in a Dictionary is separated by a colon : , whereas each key is
separated by a ‘comma’.
Create a Dictionary in Python
Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be
repeated and must be immutable. The dictionary can also be created by the built-in
function dict().
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be
treated distinctly.
# initialize empty dictionary
d = {}
Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
“”” This would be a multiline commentin Python that includes several lines and
describesthecode,or anything you want it to…
“””
1.6 Indentation
In Python, indentation is used to define blocks of code. It tells the Python
interpreter that a group of statements belongs to a specific block. All statements with the
same level of indentation are considered part of the same block. Indentation is achieved using
whitespace (spaces or tabs) at the beginning of each line.
For Example:
if 10 > 5:
print("This is true!")
print("I am tab indentation")
Output
This is true!
I am tab indentation
I have no indentation
if 10>5:
print("GeeksforGeeks")
1.7 Python Input and Output Functions
print("Hello, World!")
3. Formatting Output (f-strings, format())
Using f-strings:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Using .format():
1.8 Operators
Operators are special symbols which can manipulate the value of operands. Operators
can manipulate individual items and returns a result.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.
Python language supports the following types of operators.
● Arithmetic Operators
● Relational Operators
● Assignment Operators
● Logical Operators
● Bitwise Operators
● Membership Operators
● Identity Operators
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication and division etc. Assume variable a holds 10 and variable b holds 20, then
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
// Floor Division The division of operands where the result is the 9//2 = 4 and
quotient in which the digits after the decimal point are 9.0//2.0 = 4.0, -
removed. But if one of the operands is negative, the 11//3 = -4,
result is floored, i.e., rounded away from zero
(towards negative infinity) − -11.0//3 = -4.0
Relational Operators
Relational operators compare the values of two operands. It either returns True or False
according to the condition. Assume variable a holds 10 and variable b holds 20, then
== If the values of two operands are equal, then the condition (a == b) = False
becomes true.
!= If values of two operands are not equal, then condition becomes (a != b) = True.
true.
<> If values of two operands are not equal, then condition becomes (a <> b) = True.
true. This is similar to !
= operator.
> If the value of left operand is greater than the value of right (a > b) = False.
operand, then condition becomes true.
< If the value of left operand is less than the value of right operand, (a < b) = Ttrue.
then condition becomes true.
>= If the value of left operand is greater than or equal to the value of (a >= b)=False.
right operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of (a <= b) = True.
right operand, then condition becomes true.
Assignment Operators
Python assignment operators are used for assigning the value of the right operand to the left
operand. Various assignment operators used in Python are (+=, - = , *=, /= , etc.)
Logical Operators
Logical operators in Python are used for conditional statements are true or false. Logical
operators in Python are AND, OR and NOT. For logical operators following condition are
applied.
● For AND operator – It returns TRUE if both the operands (right side and left side)
are true
● For OR operator- It returns TRUE if either of the operand (right side or left side) is
true
● For NOT operator- returns TRUE if operand is false
Example
a = True
b = False
print(('a and b is',a and b))
print(('a or b is',a or b))
print(('not a is',not a))
Bitwise Operators
Operato
Meaning Example
r
Membership operators
in and not in are the membership operators in Python. They are used to test whether a value
or variable is found in a sequence.
In a dictionary we can only test for presence of key, not the value.
Operato
Meaning Example
r
Identity operators
is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does not
imply that they are identical.
is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True
i = 20
if (i> 10):
print ("10 is less than 20")
print ("I am Not in if")
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else if
the condition is false.
Here comes the else statement. We can use the else statement with if statement to execute a
block of code when the condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
nested-if Statement
A nested if is an if statement that is the target of another if statement. Nested if
statements means an if statement inside another if statement. Yes, Python allows us to nest if
statements within if statements. i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
# python program to illustrate nested If statement
i = 10
if (i == 10):
# First if statement
if (i< 15):
print ("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i< 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 15")
if-elif-else ladder
Here, a user can decide among multiple options. The if statements are executed from
the top down. As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.
Syntax:-
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Python program to illustrate if-elif-else ladder
a,b,c=10,20,30
if (a >= b) and (a >= b):
largest = a
Syntax
whilecondition:
# execute these statements
else:
# execute these statements
Example
for letter in 'Python': # First Example
print 'Current Letter :', letter
2.Continue statement
It returns the control to the beginning of the while loop.. The continue statement rejects all
the remaining statements in the current iteration of the loop and moves the control back to the
top of the loop.
The continue statement can be used in both while and for loops.
Syntax
continue
Example
var = 10
whilevar> 0:
var = var -1
ifvar == 5:
continue
print(“'Current variable value :”, var)
Output
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
3.pass Statement
It is used when a statement is required syntactically but you do not want any command or
code to execute.
The pass statement is a null operation; nothing happens when it executes. The pass is also
useful in places where your code will eventually go, but has not been written yet (e.g., in
stubs for example
Syntax
pass
Example
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
Output
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
1.11 Functions
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.Python provides many built-in functions like print(), etc. but the user can also create
their own functions. These functions are called user-defined functions.
Defining a Function
Functions can be defined to provide the required functionality. Here are simple rules to
define a function in Python.
● Function blocks begin with the keyword def followed by the function name and
parentheses ( ).
● Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
● The code block within every function starts with a colon (:) and is indented.
● The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
Syntax of Function
deffunction_name(parameters):
"""docstring"""
statement(s)
Example of a function
def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")
● Default arguments
● Required arguments
● Keyword arguments
● Variable-length arguments
Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an idea on
default arguments, it prints default age if it is not passed.
Below is a typical syntax for default argument. In function call2 the default value of age is
35.
Output
Name: arun
Age 50
Name: Anand
Age 35
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function
definition.
To call the function emp(), you definitely need to pass two arguments, otherwise it gives a
syntax error as follows
Name: arun
Age 50
emp( name="Anand" )
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter name.This
allows you to skip arguments or place them out of order because the Python interpreter is able
to use the keywords provided to match the values with parameters.
defemp( name, age = 35 ):
print("Name: ", name)
print( "Age: ", age)
Output
emp( name="Anand" ,35) #Function call2
^
SyntaxError: non-keyword arg after keyword arg
In the function call2 the second argument age can not be identified with its name.
This is very useful when we do not know the exact number of arguments that will be passed
to a function.You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-length arguments and are
not named in the function definition, unlike required and default arguments. n asterisk (*) is
placed before the variable name that holds the values of all nonkeyword variable arguments.
# Function definition
def print_info(arg1, *vartuple):
"""This prints a variable passed as arguments"""
print("Output: ")
print(arg1)
for var in vartuple:
print(var)
Output
Output:
10
Output:
70
60
50
1.12 Python Anonymous/Lambda Function
In Python, anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword, in Python anonymous functions
are defined using the lambda keyword.
Hence, anonymous functions are also called lambda functions.
Lambda functions can have any number of arguments but only one expression. The
expression is evaluated and returned. Lambda functions can be used wherever function
objects are required.
Here is an example of lambda function that doubles the input value.
Eg1:
# Program to show the use of lambda functions
double = lambda x: x * 2
print(double(5))
# Output: 10
Eg2:
print(sum(5,10,15))
# Output: 30
Filter Function
In Python, we generally use it as an argument to a higher-order function (a function that takes
in other functions as arguments). Lambda functions are used along with built-in functions
like filter(), map() etc.
# Define a list
list1 = [1, 5, 4, 6, 8, 11, 3, 12]
output:
[4, 6, 8, 12]
Map Function
The map() function in Python takes in a function and a list.
The function is called with all the items in the list and a new list is returned which contains
items returned by that function for each item.
Here is an example use of map() function to double all the items in a list.
# Define a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
output:
[2, 10, 8, 12, 16, 22, 6, 24]