Ge8151 Problem Solving & Python Programming: (Pick The Date)
Ge8151 Problem Solving & Python Programming: (Pick The Date)
Ge8151 Problem Solving & Python Programming: (Pick The Date)
Scalable:
Python provides a better structure and support for large programs than shell scripting
Interpreted
Python Program is processed at runtime by interpreter
Interactive:
We can interact with python interpreter by writing programs/instructions to it
Interpreter:
Python does not need compilation to binary.
Internally python converts the source code into an intermediate form called byte code
and then translates this into the native language of our computer and then runs it.
Object-Oriented:
Python Supports Object-Oriented technique of programming that encapsulates code
within objects
Desktop GUIs
Software Development
Business Applications
Game Programming
Distributed Programming
This will provide the example1.py file to the Python interpreter for execution.
Let’s assume that we write a Python Program first.py, where first is the name of the
program and .py is the extension
Next step is to compile the program using the python compiler. The python compiler
converts the python program into Byte code
Byte code is the fixed set of instructions that represent all operations which run on
any operating systems.
These byte code instructions are contained in the file first.pyc, python compiled file
Python Virtual Machine (PVM) uses an interpreter which understands the byte code
and converts it into machine code.
These machine codes are then executed by the processor and results are displayed.
S No Types Example
1 int 10,100,-256,789656
2 float 3.14,2.56789,-21.9
3 boolean True or False
4 string “Hai” or ‘Hi’
5 list [0,1,2,3,4]
>>>type(17)
< class 'int'>
Numbers with a decimal point belong to a type called float, because these numbersare
represented in a format called floating-point.
>>>type(3.2)
<class 'float'>
Values like '17' and '3.2' are strings since they are quoted eventhough they look like
numbers.
>>>type('17')
<class 'str'>
>>>type('3.2')
<class 'str'>
2.3.1 Variables
Variables are defined as reserved memory locations to store values.
Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory.
Therefore, by assigning different data types to the variables, we can store integers,
decimals or characters in these variables.
The operand to the left of the = operator is the name of the variable and the operand to
the right of the = operator is the value stored in the variable.
For example −
print(counter)
print(miles)
print(name)
100
1000.0
John
a = b = c =1
Here, an integer object is created with the value 1, and all the three variables are
assigned to the same memory location.
We can also assign multiple objects to multiple variables. For example −
a, b, c =1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to the variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
String
List
Tuple
Dictionary
1. Python Numbers
Number data types store numeric values. Number objects are created when we assign
a value to them.
For example −
var1 =1
var2 =10
2. Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks.
Python allows either pair of single or double quotes.
Subsets of strings can be taken using the slice operator [] and [:] with indexes starting
at 0 in the beginning of the string and working their way from -1 to the end.
The plus (+) sign is the string concatenation operator and the asterisk (∗) is the
repetition operator.
For example −
#!/usr/bin/python3
str='Hello World!'
print(str) # Prints complete string
print(str[0]) # Prints first character of the string
print(str[2:5]) # Prints characters starting from 3rd to 5th
print(str[2:]) # Prints string starting from 3rd character
print(str*2) # Prints string two times
print(str+"TEST") # Prints concatenated string
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
3. Python Lists
It is an ordered sequence of values of any data type like string, integer, float etc.
Values in the list are called elements/items.
A list contains items separated by commas and enclosed within square brackets [].
The values stored in a list can be accessed using the slice operator [] and [:] with
indexes starting at 0 in the beginning of the list and working their way to end -1.
The plus (+) sign is the list concatenation operator, and the asterisk (∗)is the
repetition operator.
For example −
#!/usr/bin/python3
list=['abcd',786,2.23,'john',70.2]
tinylist=[123,'john']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element
4. Python Boolean
Boolean is the type of the built-in values True and False.
Useful in conditional expressions, and anywhere else we want to represent the true or
false of some condition.
Mostly interchangeable with the integers 1 and 0.
The type object for this new type is named bool
>>> bool(1)
True
>>> bool(0)
False
>>>type(2>3)
class ‘bool’
2.4 OPERATORS
Operators are special symbols that represent computations like addition and
multiplication.
The values the operator is applied to are called operands.
Performs division and returns quotient. If the quotient value 9//2 = 4 and
// is decimal value then it is rounded to lowest whole integer. 9.0//2.0 = 4.0,
Floor Division -11//3 = -4,
-11.0//3 = -4.0
Example:
a=4
b=2
print ("Sum = ", a+b)
print ("Difference = ", a-b )
print ("Product = ", a*b)
print ("Division = ", a/b )
print ("Modulus = ", a%b)
print ("Exponent = ", a**b)
print ("Floor Division = ", a//b)
Output:
Sum = 6
Difference = 2
Product = 8
Division = 2.0
Modulus = 0
Exponent = 16
Floor Division = 2
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, a>b is not
>
then condition becomes true. true.
If the value of left operand is less than the value of right operand, then
< a<b is true.
condition becomes true.
If the value of left operand is greater than or equal to the value of right a>=b is not
>=
operand, then condition becomes true. true.
If the value of left operand is less than or equal to the value of right a<=b is
<=
operand, then condition becomes true. true.
Example:
x=40
y=5
print("Greater than = ",(x>y))
print("Less than = ",(x<y))
print("Equals to = ",(x==y))
print("Not Equals to = ",(x!=y))
print("Greater than or equal to =",(x>=y))
print("Less than or equal to = ",(x<=y))
Output:
Greater than = True
Less than = False
Equals to = False
Not Equals to = True
Greater than or equal to = True
Less than or equal to = False
Assigns values from right side operands to left side operand c=a+b
= assigns value of
a + b into c
a=4
b=2
a+=b
print ("Sum = ", a)
a-=b
print ("Difference = ", a)
a*=b
print ("Product = ", a)
a/=b
print ("Division = ", a )
b=3
a%=b
print ("Modulus = ", a)
a**=b
print ("Exponent = ", a)
a//=b
print ("Floor Division = ", a)
Output:
Sum = 6
Difference = 4
Product = 8
Division = 4.0
Modulus = 1.0
Exponent = 1.0
Floor Division = 0.0
The left operand's value is moved left by the number a << = 240
<<
of bits specified by the right operand. means
Binary Left Shift
11110000
and If both the operands are true then condition becomes true.
a and b is False.
Logical AND
not Used to reverse the logical state of its operand. not(a and b) is
Logical NOT True.
Program:
x=14
y=7
print(x>y and x==y)
print(x>y or x<y)
print(not(x<y))
Output:
False
True
True
y.
Output:
True
False
Evaluates to false if the variables on either side of the operator point x is not y,
to the same object and true otherwise. here is
is not not results in 1
if id xx is not
equal to id yy.
Example:
x=15
y=15
z=10
print(x is y)
print(y is z)
print(x is z)
print(x is not y)
print(y is not z)
print(x is not z)
Output:
True
False
False
False
True
True
2.4 EXPRESSIONS AND STATEMENTS
An expression is a combination of values, variables, and operators.
A value itself is considered an expression, and so is a variable, so the following are all
legal expressions
Examples:
17
x
x + 17
A statement is a unit of code that the Python interpreter can execute.
(1+1)**(5-2) is 8.
Exponentiation has the next highest precedence
2**1+1 is 3, not 4, and
3*1**3 is 3, not 27.
Multiplication and Division have the same precedence, which is higher
thanAddition and Subtraction, which also have the same precedence.
2*3-1 is 5, not4, and
6+4/2 is 8, not 5.
Operators with the same precedence are evaluated from left to right (except
exponentiation).
So in the expression degrees / 2 * pi, the division happens first and
the result is multiplied by pi.
The following table lists all operators from highest precedence to the lowest.
**
1
Exponentiation raise to the power
~ +-
2
Complement, unary plus and minus
* / % //
3
Multiply, divide, modulo and floor division
+-
4
Addition and subtraction
>> <<
5
Right and left bitwise shift
&
6
Bitwise 'AND'
^|
7
Bitwise exclusive `OR' and regular `OR'
Comparison operators
<> == !=
9
Equality operators
= %= /= //= -= += *= **=
10
Assignment operators
is is not
11
Identity operators
in not in
12
Membership operators
not or and
13
Logical operators
2.6 COMMENTS
A comment is a piece of program text that the interpreter ignores but that provides
useful documentation to programmers.
Comments start with the # symbol
Example:
# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
In this case, the comment appears on a line by itself. We can also put comments at the
end of a line:
percentage = (minute * 100) / 60 # percentage of an hour
We can also use triple single (‘’’) or triple double quotes (“””) at the start and end of a
multiple-line comment.
Example:
‘’’ Multiline Comment
This is an example’’’
print(“Hello World”)
temp = a
a=b
b = temp
(a,b) = (b,a)
The left side is a tuple of variables; the right side is a tuple of values.
Each value is assigned to its respective variable.
All the expressions on the right side are evaluated before any of the assignments.
Naturally, the number of variables on the left and the number of values on the right
have to be the same.
>>>(a,b,c,d)=(1,2,3)
ValueError: need more than 3 values to unpack
2.8 FUNCTIONS
A function is a block of organized, reusable code that is used to perform a single,
related action.
Functions provide better modularity for our application and a high degree of code
reusing.
Types of Functions:
Built-in Function
Syntax
Example
def printme(str):
print (str)
return
2.8.3 Parameters:
When a function is invoked, a value is passed to the parameter. This value is referred
to as actual parameter or argument. Parameters provide the data communication
between calling function and called function.
Two types:
Actual parameters:
These are the parameters transferred from the calling function [main function]
to the called function [user defined function].
Formal parameters:
Passing the parameters from the called functions [user defined function] to the
calling functions [main function].
Note:
Actual parameter – This is the argument which is used in function call.
Formal parameter – This is the argument which is used in function definition.
def printme(str):
print (str)
return
# Now you can call printme function
printme("First Call")
printme("Second call")
First Call
Second Call
Here, we are maintaining reference of the passed object and appending values in the same
object. Therefore, this would produce the following result −
Example 2: List assigned to new value and thus changes will not be reflected in caller
The parameter mylist is local to the function changeme. Changing mylist within the
function does not affect mylist. The function accomplishes nothing and finally this
would produce the following result −
The order in which statements are executed, which 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 statements
inside the function are not executed until the function is called.
A function call is like a detour in the flow of execution.
Instead of going to the next statement, the flow jumps to the body of the function,
executes all the statements there, and then comes back to pick up where it left off.
printme();
TypeError:printme() takes exactly 1 argument (0 given)
2. Keyword arguments
Keyword arguments are related to the function calls.
When we use keyword arguments in a function call, the caller identifies the
arguments by the parameter name.
This allows us 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.
Example:
def printme(str):
#This prints a passed string into this function
print (str)
return
Mystring
The following example gives clearer picture. Note that the order of parameters does not
matter.
Name: miki
Age: 50
3. 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.
Example;
Name:miki
Age50
Name:miki
Age35
4. Variable-length arguments
We may need to process a function for more arguments than we specified while
defining the function.
These arguments are called variable-length arguments and are not named in the
function definition
Syntax for a function with variable length argument −
def functionname([formal_args,]*var_args_tuple):
function_suite
return[expression]
An asterisk (*) is placed before the variable name that holds the values of all variable
length arguments.
This tuple remains empty if no additional arguments are specified during the
function call.
Following is a simple example −
Output is:
10
Output is:
70
60
50
2.10.1 The return Statement
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.
Example
#!/usr/bin/python
total =0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
2.13 MODULES
A module allows us to logically organize our Python code.
Grouping related code into a module makes the code easier to understand and use.
A module is a Python object with arbitrarily named attributes that we can bind and
reference.
Simply, a module is a file consisting of Python code.
A module can define functions, classes and variables.
A module can also include runnable code.
Example
return
2.13.1 The import Statement
We can use any Python source file as a module by executing an import statement in
some other Python source file.
The import has the following syntax:
When the interpreter encounters an import statement, it imports the module if the
module is present in the search path.
For example, to import the module support.py, we need to put the following
command at the top of the script −
#!/usr/bin/python
# Import module support
import support
# Now we can call defined function that module as follows
support.print_func("Zara")
Hello:Zara
A module is loaded only once, regardless of the number of times it is imported. This
prevents the module execution from happening over and over again if multiple
imports occur.
2.13.2 The from...import Statement
Python's from statement lets us import specific attributes from a module into the
current namespace.
The from...import has the following syntax −
For example, to import the function fibonacci from the module fib, use the following
statement −
This statement does not import the entire module fib into the current namespace; it
just introduces the item fibonacci from the module fib into the global symbol table of
the importing module.
This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.
['__doc__','__file__','__name__','acos','asin','atan',
'atan2','ceil','cos','cosh','degrees','e','exp',
'fabs','floor','fmod','frexp','hypot','ldexp','log',
'log10','modf','pi','pow','radians','sin','sinh',
'sqrt','tan','tanh']
Here, the special string variable __name__ is the module's name, and __file__is the
filename from which the module was loaded.
Output
Enter value of x:6
Enter value of y:7
The value of x after swapping: 7
The value of y after swapping: 6
Output
Enter the X-Coordinate of first point 4
Enter the Y-Coordinate of first point 0
Enter the X-Coordinate of Second point 6
Enter the Y-Coordinate of Second point 6
6.324555320336759