Python Programming Basics and Concepts
Python Programming Basics and Concepts
Extendable / Extensible
INTERPRETED
HUGE LIBRARIES
Python was developed by Guido van Rossum in the late
eighties and early nineties at the National Research
Institute for Mathematics and Computer Science in the
Netherlands.
Python is derived from many other languages, including
ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell
and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now
available under the GNU General Public License (GPL).
Python is now maintained by a core development team at
the institute, although Guido van Rossum still holds a vital
role in directing its progress.
HISTORY OF PYTHON
Guido van Rossum created the Python programming language in the late 1980s. Python source code is available
under the GNU General Public License (GPL).
A code editor is a tool that is used to write and edit code. They are usually
lightweight and can be great for learning. However, once your program gets larger,
you need to test and debug your code, that's where IDEs come in.
some of them are free to use so you can start using it as a beginner, and
become handy to use the enhanced and paid versions that are helpful while
working on larger projects. The more intelligence they have, the less work you
need on the code.
HOW TO INSTALL PYTHON
CLICK DOWNLOADS
DOWNLOADS
ith Python for
Dev
IDLE is Python's Integrated Development a n d Learning Environment
PYTHON VARIABLES
Variables are nothing but reserved memory locations to store values.
When you create a variable you reserve some space in memory.
In Python , a variable is seen as a tag that is tied to some value.
Example : num = 1
• Python consider the value as objects.
• Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory.
• By assigning different data types to variables, you can store integers, decimals or
characters in these variables.
• We do not need to declare variables before using them or declare their type.
PYTHON VARIABLES
Example
X = 10
Y= “ABC”
Z= 35.10
X=Y=Z= 20
A ,B,C = 2, 10.2 , “HELLO ”
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
% Modulus Divides left hand operand by right hand operand and returns remainder b%a=0
The division of operands where the result is the quotient in which the 9//2 = 4 and 9.0//2.0 =
// Floor Division
digits after the decimal point are removed. 4.0
Comparison (Relational) Operators
Operator Description Example
== If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!= If values of two operands are not equal, then condition becomes true. (a != b) is true.
If the value of left operand is greater than the value of right operand, then condition
> (a > b) is not true.
becomes true.
If the value of left operand is less than the value of right operand, then condition
< (a < b) is true.
becomes true.
If the value of left operand is greater than or equal to the value of right operand, then
>= (a >= b) is not true.
condition becomes true.
If the value of left operand is less than or equal to the value of right operand, then
<= (a <= b) is true.
condition becomes true.
A SSIG N M EN TO PERATO R
Operator Description Example
c = a + b assigns value of a + b
= Assigns values from right side operands to left side operand
into c
+= It adds right operand to the left operand and assign the result to left
c += a is equivalent to c = c + a
Add AND operand
-= It subtracts right operand from the left operand and assign the result to
c -= a is equivalent to c = c - a
Subtract AND left operand
*= It multiplies right operand with the left operand and assign the result to
c *= a is equivalent to c = c * a
Multiply AND left operand
/= It divides left operand with the right operand and assign the result to left
c /= a is equivalent to c = c / a
Divide AND operand
%=
It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a
Modulus AND
//= It performs floor division on operators and assign value to the left
c //= a is equivalent to c = c // a
Floor Division operand
LOGICAL OPERATOR
| (a | b) = 61
It copies a bit if it exists in either operand.
Binary OR (means 0011 1101)
^ It copies the bit if it is set in one operand but (a ^ b) = 49
Binary XOR not both. (means 0011 0001)
(~a ) = -61 (means 1100 0011 in 2's
~
It is unary and has the effect of 'flipping' bits. complement form due to a signed binary
Binary Ones Complement
number.
<< The left operands value is moved left by the a << 2 = 240
Binary Left Shift number of bits specified by the right operand. (means 1111 0000)
a = 20
b = 10
c = 15
d=5
exp1 = (a+b) * c/d #( 30 * 15 ) / 5
print("expression1 result = " , exp1)
exp2 = ((a+b) *c )/d #(30 * 15 ) / 5
print("expression2 result :" , exp2)
exp3 = (a+b) *(c/d) #(30) * (15/5)
print("expression result3 :" , exp3)
exp4 = a +(b*c)/d #20 + (150/5)
print("expression4 result ; " , exp4
# Sim p le Pro g ra m s in Pytho n
# First Pro g ra m
# This p ro g ra m a d d s tw o num b e rs
num 1 = 5
num 2 = 10
# A d d two numbers
sum = num 1 + num 2
# D isp la y the sum
p rint('The sum o f tw o num b e rs = ' , sum )
# Sec o nd Pro g ra m
FUNCTIONS
BUILT-IN FUNCTIONS
or USER DEFINED
PRE-DEFINED FUNCTIONS
FUNCTIONS
FUNCTIONS
Type Conversion Functions
The process of converting a Python data type into another data type is known as type conversion.
There are mainly two types of type conversion methods in Python, namely, implicit type conversion and
explicit type conversion.
In Python, when the data type conversion takes place during compilation or during the run time, then it’s
called animplicit data type conversion.
Example
a=5
b = 5.5
sum = a + b print (sum)
print (type (sum)) #type() is used to display the datatype of a variable
Output:
10.5
<class ‘float’>
Type Conversion in Python with Examples
Explicit type conversion is also known as typecasting.
Explicit type conversion takes place when the programmer clearly and explicitly defines the same in
the program. Various forms of explicit type conversion are explained below:
[Link](a, base): This function convertsany data type to integer. ‘Base’ specifies thebase in which string isif the
data type is a string.
[Link](): This function is used to convertany data type to afloating-pointnumber.
Example :
# adding string and integer data types using explicit type conversion
a = 100
b = “200”
result1 = a + b
print(result1)
b = int(b)
result2 = a + b
print(result2)
The math module is used to access mathematical functions in the Python. All methods of this functions are
used for integer or real type objects. import math
Functions
ceil(x)
Return the Ceiling value. It is the smallest integer, greater or equal to the number x.
factorial(x)
Returns factorial of x. where x≥0
floor(x)
Return the Floor value. It is the largest integer, less or equal to the number x.
gcd(x, y)
Returns the Greatest Common Divisor of x and y
pow(x, y)
Return the x to the power y value.
sqrt(x)
Finds the square root of x
log10(x)
Returns the Log of x, where base is 10
sin(x)
Return the sine of x in radians
cos(x)
Return the cosine of x in radians
tan(x)
Return the tangent of x in radians
User Defined Functions in Python
User User-defined functions (UDFs) are the functions defined by the user to perform a
specific task.
All the functions that are written by any of us come under the category of user-defined
functions.
SYNTAX
User Defined Functions in Python
Example
def area(r):
area= 3.14*r*r
print ("the area of the circle is:= ", area)
area(10)
Returning vs Printing
>>>def print_greeting():
… print("Hello, World")
>>>print_greeting()
Hello, World
>>>def ret_greeting():
… return "Hello, World"
>>>ret_greeting()
‘Hello, World’
COMPOSITION OF FUNCTIONS
Example 1
Given the functions f (x) = x2 + 6 and g (x) = 2x – 1, find (f∘g) (x).
Solution
Substitute x with 2x – 1 in the function f(x) = x2 + 6. (f∘g) (x)
= (2x – 1) 2 + 6 = (2x – 1) (2x – 1) + 6
IDENTATION
•Indentation in Python Programming is simply the spaces at the beginning of a code line
•Indentation in other languages like c, c++, etc., is just for readability,
•In Python, indentation is an essential and mandatory concept that should be followed when writing
Python code;
•Otherwise, the Python interpreter throws an Indentation Error.
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a
comma.
#One Argument
def greet(name):
print(name + " Happy Morning")
greet(“RAM,")
greet(“AADITHYA,")
greet(“ PRIYA,")
# Two Arguments
def greet(Fname, Lname):
print(Fname + " " + Lname)
greet(“Raja", "Ram“)
Function Arguments
You can call a function by using the following types of formal arguments−
•Required arguments
•Keyword arguments
•Default arguments
•Required arguments
Required arguments are the arguments passed to a function in the correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.
To call the function greet(), you need to pass one argument, otherwise, it gives a syntax error
as follows−
•Keyword arguments
Example
def printinfo( name, age ):
#This prints a passed info into this function
print ("Name: ", name)
print ("Age ", age )
return
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument.
quotation marks.
str ="WELCOME"
WORKING WITH FUNCTIONS
USING PYTHON
Definition OF Function
• A program is a set of statements that takes some input,
does specific computations based on given input and
produces desired output.
• A very Large program with a huge single list of
instructions increases complexity.
• Python allows us to divide a large program into some
small independent units or blocks known as functions.
• Decomposing a complex problem into simpler one
using functions improves clarity of the code.
• Functions are the most important segments or
subprograms of an application used to perform specific
tasks.
• A python program can have one or more functions.
The advantages of using functions
Syntax of function
def function-name(parameters)
:
#block of statement(s)
Example:
def hello_world(): #called function
print("hello world")
Output:
hello world
Defining functions in Python
def functionName( list of parameters):
function_block
return [expression]
# Output: Sum: 9
Function definition with example
•
import math
Code Reusable
•
• # sqrt computes the square root
square_root = [Link](4)
• # function definition
print("Square Root of 4 def get_square(num):
is",square_root)
• return num * num
• # pow() comptes the power
power = pow(2, 3) for i in [1,2,3]:
• # function call
print("2 to the power 3 is",power)
result = get_square(i)
print('Square of',i, '=',result)
HOW A FUNCTION WORKS
• Execution always begins from the first statement of the program.
• A python program may contain several funtion
definitions.
• If any function definition is found,python executes only function header
for the correctness of it and skips all lines of function body(block).
• When python sequentially reaches top level statement’s function call,
python transfers control to the function header and then execution of
function body takes place.
• Finally function execution ends with a return statement if any or the
last statement of function body.
FLOW OF EXECUTION IN A FUNCTION CALL
• Flow of execution refers to the order in which statements are
executed.
• A function body is executed in the execution frame.
• Whenever a function call statement is executed, an execution frame for
the called function is created and the control is transferred to invoke the
called function.
• Within the function’s execution frame, the body of the function gets
executed and after the last statement of the function the control returns to
the statement with/without any value(s) to the function from where it is
called(calling function).
Function Parameters:
The values being passed through a function call statement are called arguments or actual parameters.
The values received in the function definition are called parameters or formal parameters.
Note:
[Link] which is called by another Function is called Called Function. The called function contains
the definition of the function and formal parameters are associated with them.
2. The Function which calls another Function is called Calling Function and actual paramaters are
associated with them.
[Link] python, a function must be defined before the function calling otherwise python interpreter
gives an error.
Lambda function
Python lambda function doesn’t have any return statement. It has Example:
only a single expression which is always returned by default. The add = lambda x, y : x + y
def keyword and name. To create a Python lambda function, we print("Result from a Function")
have to use the lambda keyword.
def add_func(x, y):
return x + y
The basic syntax of Python lambda is
Lambda arguments : expression print(add_func(10, 20))
• What is a function?
• How a function works?
• Syntax of user-defined function
• Calling function and called function
• Formal parameter and actual parameter
SOLVED QUESTIONS
1. Differentiate between round () and floor() functions with suitable examples.
Ans. The function round() is used to convert a fractional number into whole as the nearest next whereas
the function floor() is used to convert the nearest lower whole number. e.g.,
round (4.1) = 5 and floor (6.9) = 6
2. Name the Python Library modules which need to be imported to invoke the
following functions:
(i) sin( ) (ii) randint ( )
1
Ans.
(i) math (ii) random
In programming, type conversion is the process of converting data of one type to another.
Let's see an example where Python promotes the conversion of the lower data type (integer) to the higher data type
(float) to avoid data loss.
integer_number = 123
float_number = 1.23
Output
Value: 124.23
Data Type: <class 'float'>
In the above example, we have created two variables:
Then we added these two variables and stored the result in new_number.
As we can see new_number has value 124.23 and is of the float data type.
It is because Python always converts smaller data types to larger data types to avoid the loss of data.
For example, '12' + 23. Python is not able to use Implicit Conversion in such conditions.
Python has a solution for these types of situations which is known as Explicit Conversion.
Explicit Conversion
In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the data type of the objects
Data types can be converted to each other in Python.
The functions used for type conversion are :
Example
num1 = 5.8
num2 = int(num1)
print(num2)
Output
5
Explicit Conversion
Example
num1 = 12
num2 = float(num1)
print(num2)
Output
12.0
value = “ TWO”
num1 = int(value)
print(num1)
Output
Value error
num1 = “8”
num2 = int(num1)
print(num2)
Output
8
Example 2: Addition of string and integer Using Explicit Conversion
num_string = '12'
num_integer = 23
Run Code
Output
num_string = int(num_string)
Here, we have used int() to perform explicit type conversion of num_string to integer type.
After converting num_string to an integer value, Python is able to add these two variables.
Finally, we got the num_sum value i.e 35 and data type to be int.
• Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions by
the user.
• In Type Casting, loss of data may occur as we enforce the object to a specific data type