Python Basics
Python Basics
Chapter-1
INTRODUCTION
What Is a Program
A program is a sequence of instructions that specifies how to perform a computation.
The computation might be something mathematical, such as solving a system of equations or finding the roots of a
polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document or
something graphical, like processing an image or playing a video.
Once Python is installed, typing python in the command line will invoke the interpreter in
immediate mode. We can directly type in Python code, and press Enter to get the output.
Try typing in 1 + 1 and press enter. We get 2 as the output. This prompt can be used as a
calculator. To exit this mode, type quit() and press enter.
Python IDLE
Now you can create a new file and save it with .py extension.
For example, [Link]
Write Python code in the file and save it.
To run the file, go to Run > Run Module or simply click F5.
Running a Python program in IDLE
The First Program:
Operators:
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Let us have a look on all operators one by one.
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
* Multiplication Multiplies values on either side of the operator a * b = 200
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
** Exponent Performs exponential (power) calculation on operators a**b =10 to the power
20
If you are not sure what type a value has, the interpreter can tell you:
>>> type(2)
<class 'int'>
>>> type(42.0)
<class 'float'>
>>> type('Hello, World!')
<class 'str'>
In these results, the word “class” is used in the sense of a category; a type is a category
of values.
What about values like '2' and '42.0'? They look like numbers, but they are in quotation
marks like strings:
>>> type('2')
<class 'str'>
>>> type('42.0')
<class 'str'>
Therefore they’re strings.
Chapter-2
Note: If you give a variable an illegal name, you get a syntax error:
2. Script Mode:
Inscript mode type code in a file called a script and savefile with .py extention. script mode to execute
the script. By convention, Python scripts have names that end with .py.
for ex: if you type the following code into a script and run it, you get no output at all. Why because but it
doesn’t display the value unless you tell it to. But it displays in interactive mode.
miles = 26.2
miles * 1.61
Sol is:
miles = 26.2
print(miles * 1.61)
3. Order of perations:
When an expression contains more than one operator, the order of evaluation depends on the order of
[Link] mathematical operators, Python follows order PEMDAS.
P-parentheses,
E- Exponentiation,
M- Multiplication
D-Division
A-Addition,
S- Substraction
4. Operations on strings:
Note : Mathematical operations on strings are not allowed so the following are illegal:
'2'-'1' 'eggs'/'easy' 'third'*'a charm'
Membership (in):This operator returns ‘True’ value if the character is present in the given String.
# example
var1 = 'Python'
print ('n' in var1) # True
Membership (not in):
:
It returns ‘True’ value if the character is not present in the given String.
# example
var1 = 'Python'
print ('N' not in var1)
# True
Iterating (for): With this operator, we can iterate through all the characters of a string.
# example
for var in var1: print (var, end ="") # Python
Raw String (r/R):We can use it to ignore the actual meaning of Escape characters inside a string.
For this, we add ‘r’ or ‘R’ in front of the String.
# example
print (r'\n') # \n
print (R'\n') # \n
OUTPUT:
#Hello Python
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the original string.
Method Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it was found
index() Searches the string for a specified value and returns the position of where it was found
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was
found
rindex() Searches the string for a specified value and returns the last position of where it was
found
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
zfill() Fills the string with a specified number of 0 values at the beginning
EXAMPLE2:
var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python'
When the above code is executed, it produces the following result −
Updated String :- Hello Python
5. Comments:
Comments are of two types .
Single-line comments
Multi line Comments
Single-line comments are created simply by beginning a line with the hash (#) character,
and they are automatically terminated by the end of line.
For Ex: #This would be a comment in Python
Multi Line Comments that span multiple lines and are created by adding a delimiter (“””) on
each end of the comment
For Ex:
"""
This would be a multiline comment in Python that spans several lines and describes your code,
your day, or anything you want it to """
Chapter-3
Functions
Function in Python is defined by the "def " statement followed by the function name and
parentheses ( () )
Example:
Let us define a function by using the command " def func1():" and call the function. The
output of the function will be "I am learning Python function"
The function print func1() calls our def func1(): and print the command " I am learning
Python function None."There are set of rules in Python to define a [Link] args or input
parameters should be placed within these [Link] function first statement can be an
optional statement- docstring or the documentation string of the function The code within
every function starts with a colon (:) and should be indented (space) The statement return
(expression) exits a function, optionally passing back a value to the caller. A return statement
with no args is the same as return None.
Significance of Indentation (Space) in Python:
Before we get familiarize with Python functions, it is important that we understand the
indentation rule to declare Python functions and these rules are applicable to other elements
of Python as well like declaring conditions, loops or variable.
Python follows a particular style of indentation to define the code, since Python functions
don't have any explicit begin or end like curly braces to indicate the start and stop for the
function, they have to rely on this indentation. Here we take a simple example with "print"
command. When we write "print" function right below the def func 1 (): It will show an
"indentation error: expected an indented block".
Now, when you add the indent (space) in front of "print" function, it should print as expected.
When you run the command "print square (4)" it actually returns the value of the object since
we don't have any specific function to run over here it returns "None".
Step 3) Now, here we will see how to retrieve the output using "return" command. When you
use the "return" function and execute the code, it will give the output "16."
Step 4) Functions in Python are themselves an object, and an object has some value. We will
here see how Python treats an object. When you run the command "print square" it returns
the value of the object. Since we have not passed any argument, we don't have any specific
function to run over here it returns a default value (0x021B2D30) which is the location of the
object. In practical Python program, you probably won't ever need to do this.
Arguments in Functions
The argument is a value that is passed to the function when it's [Link] other words on the calling side,
it is an argument and on the function side it is a parameter. Let see how Python Args works -
Step 1) Arguments are declared in the function definition. While calling the function, you can
pass the values for that args as shown below
Example: x has no default values. Default values of y=0. When we supply only one argument
while calling multiply function, Python assigns the supplied value to x while keeping the
value of y=0. Hence the multiply of x*y=0
Step 3) This time we will change the value to y=2 instead of the default value y=0, and it will
return the output as (4x2)=8.
Step 4) You can also change the order in which the arguments can be passed in Python. Here
we have reversed the order of the value x and y to x=4 and y=2.
Step 5) Multiple Arguments can also be passed as an array. Here in the example we call the
multiple args (1,2,3,4,5) by calling the (*args) function.
Example: We declared multiple args as number (1,2,3,4,5) when we call the (*args) function;
it prints out the output as (1,2,3,4,5)
Syntax:
def functionname( parameters ):
function_suite
return [expression]
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")
The lifetime of a variable is the period throughout which the variable exits in the memory.
The lifetime of variables inside a function is as long as the function [Link] are
destroyed once we return from the function. Hence, a function does not remember the value
of a variable from its previous [Link] is an example to illustrate the scope of a variable
inside a function.
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output
Value inside function: 10
Value outside function: 20
2. Math Functions:
Python has a math module that provides mathematical functions. A module is a file that
contains a collection of related [Link] we can use the functions in a module, we
have to import it with an import statement:
>>> import math
Note: The module object contains the functions and variables defined in the module. To
access one of the functions, you have to specify the name of the module and the name
of the function, separated by a dot (also known as a period). This format is called dot
notation.
For ex:
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = [Link](radians)
Some Constants
These constants are used to put them into our calculations.
[Link]. Constants & Description
1 ceil(x)
Return the Ceiling value. It is the smallest integer, greater or equal to the number
x.
3 fabs(x)
Returns the absolute value of x.
4 factorial(x)
Returns factorial of x. where x ≥ 0
5 floor(x)
Return the Floor value. It is the largest integer, less or equal to the number x.
6 fsum(iterable)
Find sum of the elements in an iterable object
7 gcd(x, y)
Returns the Greatest Common Divisor of x and y
8 isfinite(x)
Checks whether x is neither an infinity nor nan.
9 isinf(x)
Checks whether x is infinity
10 isnan(x)
Checks whether x is not a number.
11 remainder(x, y)
Find remainder after dividing x by y
Example program:
import math
print([Link](23.56) )
O/P:
24
42.13999999999999
The GCD of 24 and 56 : 8
It is not a number
It is Infinity
False
True
>>>
1 pow(x, y)
Return the x to the power y value.
2 sqrt(x)
Finds the square root of x
3 exp(x)
Finds xe, where e = 2.718281
4 log(x[, base])
Returns the Log of x, where base is given. The default base is e
5 log2(x)
Returns the Log of x, where base is 2
6 log10(x)
Returns the Log of x, where base is 10
Example Code
import math
print('The value of 5^8: ' + str([Link](5, 8)))
print('Square root of 400: ' + str([Link](400)))
print('The value of 5^e: ' + str([Link](5)))
print('The value of Log(625), base 5: ' + str([Link](625, 5)))
print('The value of Log(1024), base 2: ' + str(math.log2(1024)))
print('The value of Log(1024), base 10: ' + str(math.log10(1024)))
Output
The value of 5^8: 390625.0
Square root of 400: 20.0
The value of 5^e: 148.4131591025766
The value of Log(625), base 5: 4.0
The value of Log(1024), base 2: 10.0
The value of Log(1024), base 10: 3.010299956639812
1 sin(x)
Return the sine of x in radians
2 cos(x)
Return the cosine of x in radians
3 tan(x)
Return the tangent of x in radians
4 asin(x)
This is the inverse operation of the sine, there are acos, atan
also.
5 degrees(x)
Convert angle x from radian to degrees
6 radians(x)
Convert angle x from degrees to radian
Example Code
import math
print('The value of Sin(60 degree): ' + str([Link]([Link](60))))
print('The value of cos(pi): ' + str([Link]([Link])))
print('The value of tan(90 degree): ' + str([Link]([Link]/2)))
print('The angle of sin(0.8660254037844386): ' +
str([Link]([Link](0.8660254037844386))))
Output
The value of Sin(60 degree): 0.8660254037844386
The value of cos(pi): -1.0
The value of tan(90 degree): 1.633123935319537e+16
The angle of sin(0.8660254037844386): 59.99999999999999
3. Composition:
So far, we have looked at the elements of a program—variables, expressions, and statements—in
isolation, without talking about how to combine(Composition) [Link] example, the argument of a
function can be any kind of expression, including arithmetic operators:
x = [Link](degrees / 360.0 * 2 * [Link])
And even function calls:
x = [Link]([Link](x+1))
#!/usr/bin/python
Here, we are maintaining reference of the passed object and appending values in the same
object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
Scope of Variables:All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a [Link] scope of a variable
determines the portion of the program where you can access a particular identifier. There
are two basic scopes of variables in Python −
Global variables
Local variables
Global vs. Local variables:Variables that are defined inside a function body have a local scope,
and those defined outside have a global [Link] means that local variables can be accessed
only inside the function in which they are declared, whereas global variables can be accessed
throughout the program body by all functions. When you call a function, the variables declared
inside it are brought into scope. Following is a simple example −
#!/usr/bin/python
5. Flow of Execution
The order in which statements are executed is called the flow of execution
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order, from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember that
statements inside the function are not executed until the function is called.
Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the statements
there, and then comes back to pick up where it left off.
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 printme(), you definitely need to pass one argument, otherwise it gives a
syntax error as follows −
#!/usr/bin/python
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. You can also make
keyword calls to the printme() function in the following ways −
#!/usr/bin/python
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 −
#!/usr/bin/python
Variable-length arguments
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 [Link] for a function with non-
keyword variable arguments is this − def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified during
the function call. Following is a simple example −
#!/usr/bin/python
Example
def my_function(fname):
print(fname +" krishna")
my_function("Rama")
my_function("Siva")
my_function("Hari")
o/p: Ramakrishna
Sivakrishna
Harikrishna.
Parameters Vs Arguments
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.
Number of Arguments
A function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and
not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname +" "+ lname)
my_function("Srinu", "vasulu")
Return Values:
To return a value, we use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3)) # o/p: 15
print(my_function(5)) # o/p: 25
print(my_function(9)) # o/p: 45
here cat_twice terminates, the variable cat is destroyed. If we try to print it, we get
an exception:
>>> NameError: name 'cat' is not defined
8. Stack Diagrams:
Stack diagram used to keep track of which variables can be used which function.
For ex, consider the following code:
Here each function is represented by a frame. A frame is a box with the name of a function
beside it and the parameters and variables of the function inside it.
The frames are arranged in a stack that indicates which function called which, and so on. In
this example, print_twice was called by cat_twice, and cat_twice was called by main ,
which is a special name for the topmost frame. When you create a variable outside of any
function, it belongs to main .
Fruitful Functions:
Ex :def add(x,y):
return (x+y)
Z
=
a
d
d
(
1
,
2
)
p
r
i
n
t
(
z
)
void Functions:
Ex : def add(x,y):
print(x+y)
add(1,2)