Selenium With Java and Python For Mobile Apps & Web Apps......!

Latest Posts

Wednesday, 19 October 2016

Variables and Memory in Python.

Variables and Memory


Application memory
Heap
Stack
Global
Code


Contains Remaining Memory


Contains local variables
Contains global variable
Contains general instructions


The variables defined inside functions are stored in stack and the global variables lies within Global .After the function returns the memory occupied by stack variable is free. Memory consumed by global variables can only be collected after the program terminates.
Scope of variable: Global and Local
E.g. 
pi = 3.14
def cube(num):
‘’’
number->number
Given a number, this program returns the third power of the given  number.
>>>cube(2)
8
‘’’
            cubed = num * num * num
            print(pi)
            return cubed
def  circlearea(radius):
            ‘’’
            number->number
            Given a number(radius) this program gives area of the circle.
            Formula:
            Area= pi * radius * radius
            >>>circlearea(10)
            314
            ‘’’
            area = pi *  radius * radius
            print(pi)
            return area
print(pi)
Inside Stack
Frame 1
Frame 2
….
Frame n

Variable
Definition: It is a construct or identifier that refers to a value in memory location.
[Variable is analogical to shopping mall luggage counter token.]

X  Y
x1001
x1002
….
….
….
x1001
2
x1002
3




A variable does not contain a value , it refers to it.
Variable as Storage unit.
Since variables hold reference to  data for manipulation. Popular database operations like Insert, Update, Delete should also be possible on variable.
To something like insert or assign or define:
Syntax is :                                           variable = value
                                                            E.g. >>>x=5 
To update a variable value:
Syntax is :                                           variable = new _value
                                                            E.g. >>>x=10
After new value assignment, the variables are pointer is pointed to new value. Since one variable can point to only one location at a time. The value old value is garbage collected.

To delete a variable:
Syntax is :                                           del variablename
                                                            E.g. >>>del x
id() function:
This is used to determine the id of a variable. It is value based and not variable name based.
>>>x=5
>>>id(x)
140566819039352
>>>y=6
>>>id(y)
140566819039328
>>>z=5
>>>id(z)
140566819039352
Here two different variables x and z have same id because they refer to same value.
Unique property of the = (assignment) operator
It right to left hence , in variable = value , value is considered first and the identification is value based.
Variable Nomenclature
1. Variable name must start with [_a-z, A-Z] then followed by [_a-z, A-Z, 0-9]
2. Variable names are case sensitive
3. Keywords cannot be used as Python Variable names
>>>import keyword
>>>keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
Examples of valid and invalid variable name.
_a=3                            #valid
Apple = “apple”          #valid
0time = 0                     #in-invalid
Variable and Data Types
number  = 100       # An integer assignment
miles   = 1000.0     # A floating point
name    = "John"    # A string

x = [1,2,”users”]    # A List
y = (“username”, “password”) # A Tuple
dict ={'name':'john','code':6734,'dept':'sales'} # A dictionary
Data type conversion
Function
Description
int(x [,base])
Converts x to an integer. base specifies the base if x is a string.
long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.
float(x)
Converts x to a floating-point number.
complex(real [,imag])
Creates a complex number.
str(x)
Converts object x to a string representation.
repr(x)
Converts object x to an expression string.
eval(str)
Evaluates a string and returns an object.
tuple(s)
Converts s to a tuple.
list(s)
Converts s to a list.
set(s)
Converts s to a set.
dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s)
Converts s to a frozen set.
chr(x)
Converts an integer to a character.
unichr(x)
Converts an integer to a Unicode character.
ord(x)
Converts a single character to its integer value.
hex(x)
Converts an integer to a hexadecimal string.
oct(x)
Converts an integer to an octal string.
Values that a variable can point to
variable = data-type
variable = expression
variable =  variable
variable = function()


Python Variable properties
1. Implicitly defined
Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
2. Strongly typed
Python is strongly typed as the interpreter keeps track of all variables types. Compiler here cannot can tell which type a variable refers to.
Type() function
type(object) -> the object's type
>>>x=”name”
>>>type(x)
<type 'str'>

Multiple assignment
Ex:                                           >>>a=b=c=1
            >>>a,b,c= 1,2,”name

Python default variable ‘_’
‘_’ is a variable auto defined by Python and it stores last calculation. It is like ANS button on calculator.
>>> 20 + 30
50
>>> 50 + _
100
Operators in Python
Variables serve as storage unit for input data of any type or functions return value. Variables exist because data cannot be stored in continuous memory blocks due to multitasking. Continuous data memory mapping will also cause fragmentation and other losses. Thus all applications think as the entire computer memory belongs to them so the data is stored randomly and variables keep reference to them, else the data will be lost. One variable has only one referring arm so it can only point to one expression value at a time. It’s good to have data stored randomly at best available space and keep a variable reference to them. But if we don’t manipulate data what is the use. Computer is a data processor and not data storage unit. It just stores for processing and keeps processed data.
Processing ability comes from the use of operators on data or variables pointing to data.
Syntax: Variable/Data  operator Variable/Data
Most commonly used operators are
1) Arithmetic operators:
+, -, *,/,//,%,**,-
+,-,*,/ works as expected from their algebra class notations.
// is called floor division and it truncates the floating point value while preserving the data type.
% is called modulus and gives reminder of division. It works right to left.(?)
** is exponential.
2) Conditional operators
<,>,==,<=,>=,!=
These operators result in Boolean True or False value. They are good for using in conditions
3) Membership operators
in, not in simply checks if the value is in a particular sequence or range and return True and False accordingly.
>>>5 in [1,2,3,45]

True

Sunday, 16 October 2016

Function in Python.

Functions
A group of related statements to perform a specific task is known as a function. Python provides two type of functions
1) Built-in functions
2)User-defined functions
Function Definition
The following specifies simple rules for defining a function.
1.      function block or function header begins with a keyword def followed by the function name and parentheses(()).
2.      Any input parameters or arguments should be placed within these parameters. We can also define parameters inside these parentheses.
3.      The first string after function header is called the docstring and is short for documentation string. It is used t explain in brief, what a function does. Although optional, Documentation is good programming practice.
4.      The code block within every function starts with a colon(:) and is indented.
5.      the return statement [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
Syntax
            def functionname(parameters):
          "function_docstring"
          function_suite
          return [expression]
Example program
            def sum(a,b):
          sum = a+b
          return sum
Function Calling
After defining a function, we can call the function from another function or directly from python prompt. The order of the parameters specified in the function definition should be preserved in
function also function call also.
Example program
            a = int(input("enter first number:"))
     b = int(input("enter second number:"))
     s = sum(a,b)
     print("sum of",a,"and",b,"is", s)
output
     enter first number: 4
     enter second number: 3
     sum of 4 and 3 is 7
            All the parameters in python are passed by reference . It means if we change a parameter which refers to within a function, the change also reflects back in the calling function. Parameters defined inside a function have local scope. The scope of a variable determines the portion of the program where we can access a particular identifier. They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous call.
Example program
            def value_change(a):
          a=10
          print("value inside function:",a)
          return
     a= int(input("enter a number:")
     value_change(a)
     print("value outside function:",a)
output
     enter a number: 2
            value inside function: 10
     value outside function: 2
Function Arguments
We can call function by any of the following 4 arguments
1) Required arguments
2) Keyword arguments
3) Default arguments
4) Variable-length arguments
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. Consider the following example.
Example program
            def value_change(a):
          a=10
          print("value inside function:",a)
          return
     a= int(input("enter a number:")
     value_change()
     print("value outside function:",a)
output
            enter a number: 4
     Traceback (most recent call last):
       File "main.py", line 7, in <module>
         value_change()
     TypeError: value_change() take exactly 1 argument (0 given)
The above example contains a function which requires 1 parameter. In the main program code, the function is called without passing the parameter. Hence it resulted in an error.
Keyword Arguments
When we use keyword arguments in a function call, the caller identifies the argument by parameter name, This allows us to skip arguments or place them out of order because the python interpreter is able to use keywords provided to match the values with parameters
Example program
            def studentinfo(rollno,name,course):
          print("roll no: ",rollno)
          print("name: ",name)
          print("course: ",course)
          return
     studentinfo(course="UG",rollno=50,name="jack")
output
     roll no: 50
     name: Jack
     course: UG
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 shows how default arguments are invoked.
Example program
            def studentinfo(rollno,name,course="UG"):
          print("roll no: ",rollno)
          print("name: ",name)
          print("course: ",course)
          return
     studentinfo(course="UG",rollno=50,name="jack")
     studentinfo(rollno=51,name="Tom")
output
     roll no: 50
     name: Jack
     course: UG
     roll no: 51
     name: Tom
     course: UG
            In the above example the first function call to studentinfo passes the three parameters. In case of second function call to studentinfo, the parameter course is omitted. Hence it takes the default value "UG" given to course in the function.
Variable-Length Arguments
In some cases we may need to process a function for more arguments than specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. An asterisk(*) is placed before the variable name that holds the value of all non-keyword variable arguments. the tuple remains empty if no additional arguments are specified during the function call. the following shows the syntax of a function with variable-length arguments.
syntax
            def functionname([formal_srguments,]):
          "function_docstring"
          function_suite
          return [expression]
Example program
            def variablelengthfunction(*drgument):
          print("result:",)
          for i in argument: print(i)
          return
     variablelengthfunction(10)
     variablelengthfunction(10,30,50,80)
output
     Result: 10
     Result: 10
     30
     20
     80
Anonymous Functions(Lambda Functions)
            In python, anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword, in python anonymous functions are defined using lambda keyword. Hence, anonymous function are also called as lambda functions. The following are the characteristics of lambda functions.
1.      Lambda functions can also take any number of arguments but return only one value in the form of an expression.
2.      It cannot contain multiple expressions.
3.      It cannot have commands.
4.      A lambda function cannot be a direct call to print because lambda requires an expression.
5.      Lambda function have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
6.      lambda functions are not equivalent to inline functions in c or c++.
Syntax
            lambda [arg1 [arg2,.....argn]]:expression
  Example Program
     square = lambda x: x*x;
     n = int(input("enter a number: "))
     print("square of",n,"is",square(n))

output
     enter a number: 2
     square of 2 is 4
Uses of Lambda function
We use lambda function when we require a nameless function for a short period of time. In python we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter(), map(), etc.
Recursive Functions
Recursion is the process of defining something in terms of itself. A function can call other functions. It is possible for a function to call itself. This is known as recursion. the following example shows a recursive function to find the factorial of a number.
Example program
     def recursion_fact(x):
          if x==1: return 1
          else: return (x*recursion_fact(x-1))
     num = int(input("enter a number:")
     if num>=1:
     print("the factorial of ",num,"is",recursionfact(num))
output
     enter a number: 5
     the factorial of 5 is 120
Explanation
            recursion_fact(5)                 #1st call with 5
     5*recursion_fact(4)               #2nd call with 4
     5*4*recursion_fact(3)             #3rd call with 3
     5*4*3*recursion_fact(2)           #4th call with 2
     5*4*3*2*recursion_fact(1)         #5th call with 1
     5*4*3*2*1                         #return from 5th call
     number = 1
     5*4*3*2                           #return from 4th call
     5*4*6                             #return from 3rd call
     5*24                              #return from 2nd call
     120                               #return from 1st call
Functions with more than one return value
Python has a strong mechanism of returning more than one value at a time. This is a very flexible when the function needs to return more than one value. Instead of writing separate functions for returning individual values, we can return all values within same function. The following shows an example for function returning more than one value.
 Example program
            def calc(a,b):
          sum = a+b
          diff = a-b
     return sum,diff
     a = int(input("enter first number:"))
     b = int(input("enter second number:"))
     s,d=calc(a,b)
     print("sum=",s)
     print("Difference=",d)
output
     enter first number:  10
     enter second number: 5
            sum = 15
     Difference = 5
Practice Questions
1.      Write a python function to check whether a number is even or odd
2.      Writer a python function to test whether a number is within 100 or 1000 or 2000.
3.      Write a python program to calculate the sum of threegiven numbers, if the values are equal then return thrice of their sum.
4.      Write a python function to get a new string from a given string where "is" has been added to the front. If the given string already begins with "Is" then return the string unchanged.
5.      Write a python program to get a string which is n (non-negative integer) copies a given string.
6.      Write a python function that will return true if the two integer values are equal or their sum or difference is 5
7.      Write a python function that takes two lists and returns true if they have at least one common member.
8.      Write a python function to find GCD of 2 numbers.
9.      Write a python function to generate all the factors of a number.
10.  Write a python function to find the sum of digits of a number.
11.  Write a python function to concatenate two strings.
12.  Write a python function called compare which takes two strings s1 and s2 and an integer n as arguments. The function should return true if first character of both the strings are same else the function should return false.
13.  Write a python function to find whether a number is completely divisible by another number.
14.  Write a  python program to display fibonacci series using recursion
15.  Write a python program to find the sum of n natural numbers using recursion.
16.  Write a python program to convert decimal to binary using recursion.


Translate

Popular Posts

Total Pageviews