Module 1
Python Basic Concepts and
Programming
Prepared By: Shweta Dhareshwar
Department of MCA
Program Structure
The typical structure of a python program include 3 parts
Import statements // import statements are used to include library files to the
python program
Function definitions //This section include the definitions of various functions
written in a Python Program
Program statements // This section include the set of statements for solving the
given problem.
Examples:
print('Welcome to second semester MCA')
Identifiers
Identifiers is nothing but name in python program. It can be class_name,function_name,variable_name.
Following are the rules to create an identifier.
1. The allowed characters are a-z, A-Z, 0-9 and underscore (_)
2. It should begin with an alphabet or underscore
3. It should not be a keyword
4. It is case sensitive
5. No blank spaces are allowed.
6. It can be of any size
si, rate_of_interest, rate of interest , student1, 1student ,ageStudent , @age
Keywords
Keywords are the identifiers which have a specific meaning in python, there
are 33 keywords in python. These may vary from version to version.
Variables
Variable means linking of the data to a name. Variable refers to the memory location
that contains the data.
Unlike other programming languages, python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example : X=60 # declaring the variable
print(x) # To display
Variables do not need to be declared with any particular type and can even change type
after they have been set.
Below are the rules to define a variable:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Python is case sensitive hence variable names are case-sensitive .
Python allows to assign values to multiple variables in one line.
A keyword cannot be used as a variable.
Operators
Operators are special symbols which represents specific operations
Arithmetic Operators
Comparison Operators
Logical Operators
Assignment Operators
Bitwise Operators
Identity Operators
Membership Operators
Arithmetic Operators
Arithmetic Operators comprise of operands and operators.
# Examples of Arithmetic Operator
a=9 b=4
add = a + b # Addition of numbers
sub = a – b # Subtraction of numbers
mul = a * b # Multiplication of number
div1 = a / b # Division(float) of number
div2 = a // b # Division(floor) of number
mod = a % b # Modulo of both number
p = a ** b # Power
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)
Comparison Operators
Python supports different types of comparison operators.
# Examples of Relational Operators
a = 13
b = 33
# a > b is False
print(a > b)
# a < b is True
print(a < b)
# a == b is False
print(a == b)
# a != b is True
print(a != b)
# a >= b is False
print(a >= b)
# a <= b is True
Logical Operators
Python offers “or”, “and” and “not” as logical operators.
Example
6>10 and 20>12
6>10 or 20>12
not 5>1
Bitwise Operators
Python programming perform binary bitwise operations.
a=242
b=12
a|b
254
Continued…..
# Examples of Bitwise operators
a = 10
b=4
# Print bitwise AND operation
print(a & b)
# Print bitwise OR operation
print(a | b)
# Print bitwise NOT operation
print(~a)
# print bitwise XOR operation
print(a ^ b)
# print bitwise right shift operation
print(a >> 2)
# print bitwise left shift operation
print(a << 2)
Assignment Operators
Example:
A=16
A+=5
Print(A)
A -= 3
Identity Operators
Identity operators determine whether the given operands point to the same
memory address.
is and is not are the identity operators part of the memory.
Example
a = 10 Operator Description
Is If two variables refer to the same memory
b = 20 location, then the “is“ operator returns True,
otherwise returns False.
print(a is not b) Is not If two variables refer to the same memory
location, then the “is“ operator returns False,
print(a is b) otherwise returns True.
Membership Operators
The membership operator checks whether the given item exists in the sequence or not.
in and not in are the membership operators.
str1= “Welcome”
print( “m” in str1)
Or
Operator Description
x = ["apple", "banana"]
in True if value is found in the sequence
print("banana" in x)
not in True if value is not found in the sequence
str1= “Welcome”
print ("x" not in str1)
Or
x = ["apple", "banana"]
print("pineapple" not in x)
Precedence and Associativity of Operators
Operator precedence and associativity determine the priorities of the operator.
Precedence:
P – Parentheses
E – Exponentiation
M – Multiplication (Multiplication and division have the same precedence)
D – Division
A – Addition (Addition and subtraction have the same precedence)
S – Subtraction
Associativity: If an expression contains two or more operators with the same
precedence then Operator Associativity is used to determine. It can either be Left
to Right or from Right to Left.
Data Types
Variables can store data of different types, and different types can do different things.
Mutable data types in Python are those whose value can be changed in place after
they have been created.
Immutable refers to a state in which no change can occur over time.
Example
Print the data type of the variable x:
X=50
x = 20.5
x = 1j
x = True
Getting the Data Type :You can get the data type of any object by using
the type() function:
Type Conversions
We can convert from one type to another with the int(), float(), and complex() methods
x = str("s1")
y = str(2)
z = str(3.0)
Python Indentation
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
• Python uses indentation to indicate a block of code.
The number of spaces is up to you as a programmer, but it has to be at least one.
Example:
You have to use the same number of spaces in the same block of code, otherwise
Python will give you an error:
You have to use the same number of spaces in the same block of code,
otherwise Python will give you an error:
Comments
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 when testing code.
Creating a Comment
Comments starts with a #, and Python will ignore them.
# This is a sample python program
print("Hello, World!")
Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line.
Reading Input, User Input, Print Output
Programs often need to obtain data from the user, usually by way of input from the keyboard. One way to
accomplish this in Python is with input():
Syntax
input([<prompt>])
name = input ("What is your name? ")
print(name)
Control Flow Statements
Control structure Without using Control structure sequence of execution of
statements in a program is line by line and every statement is executed once .
In python we can divide the control structure into two parts
1. conditional control statement
i. If ... Else
ii. if....else
iii. if.......elif....... Else
2. looping/iterative control structure
i. While Loops
ii. For Loops
conditional control Statement
i) if Example: If statement
Syntax
I. if (condition) :
Statement 1
Statement 2
…………
Statement n
II. if....else
Syntax
if (condition) : Example: If…else statement
Statement 1
Statement 2
…………
Statement n
else : Statement A
Statement 2
…………
Statement n
if.......elif....... else
Syntax
if (condition) : Example: if.......elif....... else statement
Statement 1
Statement 2
…………
elif (condition) :
Statement i
Statement ii
…………
elif (condition) :
Statement a
Statement b
…………
else
Statement A
Statement B
While loop
Syntax
While (condition):
statements to be executed in while loop
Example:
For loop
For <variable> in range (<an integer expression>):
statements(s)
Example:
for i in range(5):
print(i)
Break statement is used to force fully terminate a loop.
Continue Statement Continue statement is used to skip the execution of loop statements.
Pass statement is used in situations where there are no statements for execution in a particular section of
program but for following syntax rules the inclusion of section is must.
Functions
A function is a block of code which only runs when it is called. The idea is to put some commonly or
repeatedly done tasks together and make a function so that instead of writing the same code again and
again for different inputs, we can do the function calls to reuse code contained in it over and over again.
Creating a Function
In Python a function is defined using the def keyword.
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Return statement in Python function
The function return statement is used to exit from a function and go back to the
function caller and return the specified value or data item to the caller.
Syntax:
return [expression_list]
The return statement can consist of a variable, an expression, or a constant which is
returned to the end of the function execution. If none of the above is present with the
return statement a None object is returned.
Example:
def square_value(num):
/ /This function returns the square value of the entered number
return num**2
print(square_value(2))
print(square_value(-4))
Types of Function Arguments in Python
Arguments are used to call a function and there are primarily 5 types of functions that one can use:
Positional (Required )arguments
Default Arguments
Keyword Arguments
Variable-length arguments (Arbitrary Arguments)
Command line arguments
Positional 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.
Example:
def add(a,b):
sum =a+b
return sum
result=add(7,6)
print(result)
Default Arguments - In Python the default argument is an argument that takes a default value if no
value is provided in the function call. The following example uses default arguments, that prints
default salary when no argument is passed.
Example:
def add(a=10,b=20):
sum =a+b
return sum
result=add(7)
print(result)
Keyword arguments will invoke the function after the parameters are recognized by their parameter
names. The value of the keyword argument is matched with the parameter name and so, one can also put
arguments in improper order (not in order).
Example:
def display(a,b):
print(a,b)
display(b=20,a=10)
Variable-Length Arguments -In some instances you might need to pass more arguments than
have already been specified. Going back to the function to redefine it can be a tedious process.
Variable-Length arguments can be used instead. These are not specified in the function’s
definition and an asterisk (*) is used to define such arguments.
Example:
def display(*course):
for i in course:
print(i)
display(“MCA”,”MBA”,”BCA”)
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. Python provides various ways of dealing with these types
of arguments.
Anonymous functions
In Python Function - In Python, an anonymous function means that a function is without a name. As we already know the def
keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.
Syntax
lambda argument : expression
•A lambda function is created using the lambda keyword.
•The keyword is followed by one or many parameters.
•Lastly, an expression is provided for the function. This is the part of the code that gets executed/returned
Example :
add_numbers = lambda a,b : a + b
print(add_numbers(2,3))
def cube(x): return x*x*x
cube_v2 = lambda x : x*x*x
print(cube(7))
print(cube_v2(7))