Dap M1
Dap M1
Python
Module1: Python Basic Concepts and
Programming
Presented By,
Kavya HV
Asst Professor
Dept of MCA
PESITM
Interpreter:
Interpreter is a computer program that
converts each high-level program statement into machine
code.
• An interpreter translates program one statement at a
time.
• No intermediate object code is generated so it requires
less memory.
• Debugging is faster.
• It takes less amount of time to analyze the source code but
the overall execution time is slower.
• Programming languages like Python, Ruby uses interpreter.
Parts of Python Programming Language:
Identifiers
Keywords
Statements and Expressions
Variables
Operators
Precedence and Associativity
Data Types
Indentation
Comments
Reading Input
Print Output
Identifiers:
Identifier is the name used to identify a variable,
function, class, module or other object.
• An identifier can contain a letter A to Z (or) a to z (or) an
underscore(_) (or) digits(0 to 9).
• Python does not allow punctuation characters such as @, $,
and % within Identifiers.
• Python is a case sensitive programming language. Thus,
Manpower and manpower are two different identifiers in
Python.
Eg: a=10, class A, m1() etc.
Keywords:
Keywords are predefined and also called as
reserved words that have special meaning.
• Keyword cannot be used as an identifier, function name
(or) variable name.
• There are 32 keywords in python some of them are break,
continue, import, return, class, if, else, print, and, or not
etc.
Statements:
A statement is a unit of code that the python
interpreter can execute.
• It is used for creating variables (or) for displaying values.
Assignment Statement: We assign a value to a variable
using assignment statement(=).
An assignment statement consists of an expression on the
right-hand side and a variable to store the result.
Eg: x = 5 + 5
Print Statement: Print is a function which takes string (or)
variable as an argument to display it on the screen.
Eg: print(x)
Expressions:
An expression is a combination of values,
variables and operators.
• It is a combination of operands and operators.
Eg: x = 7
x+1
print(x)
There are different types of Expressions:
1) Arithmetic Expressions
2) String Expressions
3) Relational Expressions etc.
Variables:
Variables are containers for storing data values (or)
variable is a named place in the memory where a
programmer can store data and later retrieve the data using
variable name.
• An assignment statement creates new variables and gives
them values.
• In python a variable need not be declared with specific
type before its usage. The type of it will be decided by
the value assigned to it.
Eg: n = 17, pi = 3.14
Rules for creating variables:
Variable name can contain letters, numbers and the
underscore.
Variable names cannot contain spaces and other special
characters.
Variable name cannot start with a number.
Keywords can not be used as a variable.
Eg: Spam, spam87,_speed, my_first_class
Operators:
Operators are used to perform operations on
variables and values.
Types of Operators:
1. Arithmetic operators
2. Relational Operators or Comparison Operators
3. Assignment Operators
4. Logical Operators
1. Arithmetic operators: It is used to perform basic
mathematical operations like addition, subtraction,
multiplication and division.
2. Relational Operators(or)Comparison Operators: It is used
to check the relationship like less than, greater than between the
operands.
-These operators return a Boolean value True or false.
3. Assignment Operators: It is used for assigning values
to variables.
4. Logical Operators: The logical operators AND, OR, NOT are used for
comparing logical values of their operands and to return the resulting
logical value.
Precedence and Associativity:
• When an expression contains more than one operator, the
evaluation of operators depends on the precedence of
operators.
• The python operators follow the precedence rule:
a) Parenthesis have the highest precedence in any
expression. The operations within parenthesis will be
evaluated first.
b) Exponentiation has the 2nd precedence. But it is right
associative that is if there are two exponentiation operations
continuously, it will be evaluated from right to left.
c) Multiplication and Division are the next priority. In this
two operations, whichever comes first in the expression is
evaluated.
d) Addition and Subtraction are the less priority. In this two
operations, whichever appears first in the expression is
evaluated i,e they are evaluated from left to right.
Eg: x = 1 + 2 ** 3 / 4 * 5
Datatypes: Data types specify the type of data like
numbers and characters to be stored and manipulated within
a program.
Datatypes of Python are:
1) Numbers: Integers, floating point numbers and complex
numbers fall under python numbers category.
• They can be defined as int, float and complex class in
Python.
• Integers can be of any length, it is only limited by the
memory available.
• A floating-point number is accurate up to 15 decimal
places.
• Integer and floating points are separated by decimal
points.
Eg: 1 is an integer, 1.0 is floating point number and complex
numbers are written in the form x+yj, where x is real part
and y is the imaginary part.
Output:
Enter username: Brunda
Username is: Brunda
Print Output:
In-order to print the output, python provides us
with a built-in function called print().
Example:
print("Hello Python")
print("Hello Good Morning")
Output:
Hello Python
Hello Good Morning
Type Conversions Function: It refers to the conversion
of one datatype to another datatype.
There are two types of Type Conversion:
1) Implicit type conversion
2) Explicit type conversion
1) Implicit type conversion: In Implicit type conversion of
data types in Python, the Python interpreter
automatically converts one data type to another without
any user involvement.
2) Explicit type conversion: In Explicit Type Conversion in
Python, the data type is manually changed by the user as
per their requirement. With explicit type conversion,
there is a risk of data loss since we are forcing an
expression to be changed in some specific data type.
The type() Function: type function is called to know the
datatype of the value.
• The expression in parenthesis is called the argument of
the function.
• The argument is a value (or) variable that we are passing
into the function as input to the function.
Example:
a = ('apple', 'banana', 'cherry')
b = "Hello World"
c = 33 Output:
print(type(a)) <class 'tuple'>
print(type(b)) <class 'str'>
print(type(c)) <class 'int'>
Is Operator: The is keyword is used to test if two variables
refer to the same object.
• The test returns True if the two objects are the same
object.
• The test returns False if they are not the same object,
even if the two objects are 100% equal.
Example:
list1 = ["banana", "grapes", "orange"]
list2 = ["banana", "grapes", "orange"]
print(list1 == list2)
print(list1 is list2) Output: True
False
list1 = ["banana", "grapes", "orange"]
list2 = ["banana", "grapes", "orange"]
list1 = list2
print(list1 is list2)
print(id(list1))
print(id(list2))
Output:
True
22538031619264
22538031619264
Control Flow Statements: Control flow statements in
Python are used to manage the flow of execution of a
program based on certain conditions.
Syntax:
if condition:
# code to execute if condition is true
• The condition can be any expression that evaluates to a
Boolean value (True or False).
• If the condition is True, the code block below the if
statement will be executed.
• If the condition is False, the code block will be skipped.
Flow Chart:
Example:
num = 5
if num > 0:
print("The number is positive.")
Output:
The number is positive.
2) The if…else Decision Control Flow Statement:
Syntax:
if condition:
# code to execute if condition is true
else:
# code to execute if condition is false
• If the condition is True, the code block below
the if statement will be executed, and the code block
below the else statement will be skipped.
• If the condition is False, the code block below
the else statement will be executed, and the code block
below the if statement will be skipped.
Flow Chart:
Example:
num = -5
if num > 0:
print("The number is positive.")
else:
print("The number is negative.")
Output:
The number is negative.
3) The If…elif…else Decision Control statement:
The elif statement
allows you to check multiple conditions in sequence and
execute different code blocks depending on which condition
is true.
• The elif statement is short for "else if" and can be used
multiple times to check additional conditions.
Syntax:
if condition1:
# code to execute if con1 is true
elif condition2:
# code to execute if con1 is false and con2 is true
elif condition3:
# code to execute if con1 and con2 are false, and con3 is true
else:
# code to execute if all conditions are false
Example: Flow Chart:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Output:
a is greater than b
4) Nested If Statement: The nesting of an if statement
inside another if statement with (or) without an else
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
Example: Flow Chart:
x = 41
if x > 10:
print("Above ten")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Output:
Above ten
and also above 20!
Iteration (Looping statement):
while (condition):
statements
The flow of execution for while loop:
• The condition is evaluated first, whether it is True (or)
False.
• If the condition is false, the loop is terminated and
statements after the loop will be executed.
• If the condition is true, the body of the loop(block of
statements) will be executed and then goes back to
condition evaluation.
Flow Chart:
Example:
x=0
Output:
0
1
2
3
4
2) For Loop:
For loop in Python is used to iterate over items
of any sequence, such as a list, tuples (or) a string etc.
Example:
colors = ['blue', 'black', 'green', 'purple']
for i in colors:
print(i)
Output:
blue
black
green
purple
Syntax:
Loop{
Condition:
break
}
Flow Chart:
Example: Output:
for i in range(10): 0
print(i) 1
if i == 2: 2
break
Continue Statement: It is a loop control statement that
forces to execute the next iteration of the loop while
skipping the rest of the code inside the loop for the current
iteration.
• When the continue statement is executed in the loop, the
code inside the loop following the continue statement will
be skipped for the current iteration and the next iteration
of the loop will begin.
Flow Chart:
Example:
for i in range(1, 11):
if i == 6:
continue
else:
print(i, end=" ")
Output: 1 2 3 4 5 7 8 9 10
Commonly Used Modules
Math functions
Python has a math module that provides most of the
frequently used mathematical functions. Before we use
those functions, we need to import the module as below:
>>>import math
The math module has a set of methods and constants
Example:
import math
print(math.sqrt(3))
print(math.sin(30))
print(math.cos(30))
print(math.sqrt(2))
Output:
1.7320508075688772
-0.9880316240928618
0.15425144988758405
1.4142135623730951
Random numbers: A random number in python is
any number between 0.0 to 1.0 generated with pseudo-
random number generator.
It is possible to create integers, doubles, floats and even
long.
It generates the number randomly.
Example:
import random
num = random.random()
print(num) Output: 0.5309931550748984
num=random.randint(10,20)
print(num) Output: 16
num = random.randrange(10,20,2)
print(num) Output: 12
num=random.randint(10,20)
print(num) Output: 18
Functions: A function is a block of code which only runs
when it is called. We can pass data, known as parameters,
into a function.
Function Declaration:
• In Python a function is defined using the def keyword
Example:
def my_function():
print("Hello Good Morning")
my_function()
Types of Function:
Built-in functions
User Defined Functions
1) Built-in Functions:
Built-in functions in Python are pre-
defined functions provided by the Python language that can
be used to perform some tasks.
Syntax:
function_name(argument1, argument2)
Built-in Functions:
2) User Defined Functions:
This are the functions which are
defined by the user called as user defined functions.
Syntax:
def fname(arg_list):
statement 1
statement 2
………
statement n
return value
Example:
def square( num ):
return num*2
n = square(6)
print( "The square of number is: ", n )
Output:
12
Calling a function: Once we defined a function, we can call
the function as many times as we need.
• To call a function in Python, type the name of the function
followed by parentheses (). If the function takes any
arguments, they are included within the parentheses.
Example:
def MyFun():
print("Hello World")
MyFun()
Output:
Hello World
Return Statement and void Function:
• A special statement that you can use inside a function or
method to send the function's result back to the caller.
• A return statement is used to end the execution of the
function call and “returns” the result to the caller.
• Return statement can not be used outside the function.
Syntax:
def fun():
statements
.
.
return [expression]
Example:
def add(a, b):
result = a + b
return result
print(add(20, 22))
Output: 42
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Output:
I am from Sweden
I am from India
I am from Norway
I am from Brazil
Keyword Arguments
• If we have some functions with many parameters and we
want to specify only some of them, then we can give
values for such parameters by naming them – this is called
Keyword arguments we use the name (keyword) instead of
the position to specify the arguments to the function.
There are two advantages:
Using the function is easier since we do not need to worry
about the order of the arguments.
We can give values to only those parameters to which we
want to, provided that the other parameters have default
argument values.
Example:
def student(firstname, lastname ='Roy', std ='Fifth'):
print(firstname, lastname, 'studies in', std, 'Standard')
student('John')
student(firstname = 'Nishani', lastname = 'Raj')
student(firstname = 'Vindhya', std = 'Eighth’)
Output:
John Roy studies in Fifth Standard
Nishani Raj studies in Fifth Standard
Vindhya Roy studies in Eighth Standard
args and kwargs, Command Line Arguments
• Sometimes we want to define a function that can take
any number of parameters i,e. variable number of
arguments, this can be achieved by using the stars.
add(1,2) Output:
add(6,5,6) Sum is: 3
add(1,2,3,4,48,8) Sum is: 17
Sum is: 66
Example for **kwargs:
def info_person(**info):
print("\nData type of argument:",type(info))
for key, value in info.items():
print(key, value)
info_person(name="Ram", age=24, dept="MCA")
info_person(name="Rukmini", dept="CS")
Output:
Data type of argument: <class 'dict'>
name Ram
age 24
dept MCA
Data type of argument: <class 'dict'>
name Rukmini
dept CS
Command Line Arguments:
The arguments that are
given after the name of the program in the command line
shell of the operating system are known as Command Line
Arguments.
• The sys module provides functions and variables used to
manipulate different parts of the Python runtime
environment.
• Using sys.argv is a simple list in python that contains all
the command-line arguments passed to the script.
• len(sys.argv) provides the number of command line
arguments.
• sys.argv[0] is the name of the current Python script.
import sys
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
# Arguments passed
print("\nName of Python script:", sys.argv[0])
print("\nArguments passed:", end = " ")
for i in range(1, n):
print(sys.argv[i], end = " ")
# Addition of numbers
Sum = 0
for i in range(1, n):
Sum += int(sys.argv[i])
print("\n\nResult:", Sum)
THANK YOU