Wednesday, September 26, 2018

python 13 (Functions Arguments: hi friends checkout my previous lessons to learn from start)

Arbitrary argument list

The function can be called with arbitrary number of argument this arguments will be wrapped up in a tuple before the variable number of arguments zero or more normal arguments may occur

def write_multiple_items(file, separator, *args):
      file.write(separator.join(args))
Normally this variadic arguments comes last in the list of formal parameters because they scoop up all remaining input arguments that are passed to the function any formal parameters which occur after the *args are keyword only arguments means they can only be used as key words rather than positional arguments

>>> def concat(*args, sep="/"):
...     return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'

UnPacking Argument lists

The argument list can be unpacked if the arguments are in a tuple or list but need to be unpacked for a function call requiring positional arguments like the range() function expects seperate start and stop arguments if they are not available separately write the function call with the * - operator to unpack the arguments out of  a list or tuple

>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]

in the same fashion dictionaries can deliver key word arguments with the **- operator:


>>> def parrot(voltage, state='a stiff', action='voom'):
...     print("-- This parrot wouldn't", action, end=' ')
...     print("if you put", voltage, "volts through it.", end=' ')
...     print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !


Lambda expressions
The small anonymous function can be created with the lambda keyword this function returns the sum of its two arguments lambda a , b : a+b Lambda function can be used wherever function objects are required they are syntactically restricted to a single expression lambda function can reference variables from the containing scope :
>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
Other one giving above here an example of a lambda function to return a function another one given below is example to pass a small function as an argument
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
  
 

More on Lists

here are some of the list data type methods

list.append(x)
     add an item to the end of the list equivalent to a a[len(a):] = [x].

list.extend(iterable)
Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
list.remove(x)
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
list.clear()
Remove all items from the list. Equivalent to del a[:].
list.index(x[, start[, end]])
Return zero-based index in the list of the first item whose value is equal to x. Raises a ValuError if there is no such item.
The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular sub-sequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.
list.count(x)
Return the number of times x appears in the list.
list.sort(key=None, reverse=False)
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
list.reverse()
Reverse the elements of the list in place.
list.copy()
Return a shallow copy of the list. Equivalent to a[:]
 More will be added in the next page thanks for reading my blog kindly request to write feed back on the comment section and follow me and share this blog 

Saturday, June 16, 2018

python chap 12 (hi friends checkout my previous lessons to learn from start)

Function

It is also possible to define function with variable number of arguments this are the forms as

Default Argument Values

  In here we specify a default value for one or more arguments this how we can call a function with fewer arguments this creates a function that can be called with fewer arguments than it is defined to allow like :


def myfun(fight,leavestep = 4, sail = 'boat'):
    while True:
        ok = input(fight)
        if ok in ('sword','knife','gun'):
            return True
        if ok in ('no','pain','gain'):
            return False
        if leavestep <= 0:
            raise ValueError ('invalid user response')
        print(sail)         
The function can be called in several ways such as
  • giving only mandatory argument like myfun('tool to fight') :
>>> myfun('tool to fight')
tool to fight sword
True
  • or we can give one of the optional arguments like in here myfun('tool to fight',1):
>>> myfun('tool to fight',1)
tool to fightno
False
  • or even giving all the arguments as as myfun('tool to fight',1,'ship')

>>>myfun('tool to fight',1,'ship')
tool to fight
ship
Now here are given the ways first we give the first compulsary argument because in the function it is only without value so we have to give it a value in calling function and by running the code and writing the input we get the values as the process in the function and also can apply all three arguments can also get errors according to the value in the second argument we get as for example here is myfun('tool to fight',0,'ship')
>>> myfun('tool to fight',0,'ship')
tool to fight
Traceback (most recent call last):
  File "<pyshell#46>", line 1, in <module>
    myfun('tool to fight',0,'ship')
  File "<pyshell#38>", line 10, in myfun
    raise ValueError ('invalid user response')
ValueError: invalid user response
Note: The default value are evaluated at the function definition at the defining scope so that

>>> i = 5
>>> def by(arg = i):
    print(arg)

  
>>> i = 7
>>> by()
5
>>>
it will output 5
This here one thing to note as Warning : is that the due to the fact that default value is evaluated only once so in the case of mutable objects such as lists dictionaries or instances of most classes the following function accumulates the arguments passed to it on subsequent calls as

>>> def f(a,L=[]):
    L.append(a)
    return L

>>> print(f(1))
[1]
>>> print(f(2))
[1, 2]
>>> print(f(3))
[1, 2, 3]
>>>
The result will be as given above to prevent from the default to be shared between subsequent calls you can write the function like this instead and the result will be also as given below
>>> def f(a,L=None):
 if L is None:
  L=[]
  L.append(a)
  return L

 
>>> print(f(1))
[1]
>>> print(f(2))
[2]
>>> 

Keyword Arguments

The keyword arguments are used to call functions in the form as kwargs = value for instance the function is given below

 def plane (power,state = 'a big',action = 'fly high',type = 'sea blue'):
    print("This place will",action,end='')
    print("if you put",power,"power through it")
    print("__ So swift , the",type)
    print("It's",state , "!")
Accepts one required argument power and optional three arguments like state , action, type we can call this function in any of the following ways like
//1 positional argument
plane(1000)
//1 keyword argument
plane(power=1000)
//2 keyword argument
plane(power=1000,action='fly low')
//2 keyword argument
plane(action = 'fly low',power=1000)
//3 positional arguments
plane('thousand','jumbo','fly low')
//1 positional and 1 keyword argument
plane('a ten thousand',state ='jumbo' )

but there are also some invalid calls like

//no compulsary argument
plane()
//non keyword argument after a keyword argument
plane(power=2000,'fly jump')
//duplicate value for the same argument
plane(2000,power=1000)
//unknown keyword argument
plane(speed = 12)
And in the final formal parameter in the form **name receives a dictionary containing all keyword arguments except for those corresponding to a formal parameter and the formal parameter of the form *name may be combined with this which receives a tuple containing the positional arguments beyond the formal parameter list (*name must occur before **name) as

def grocery(kind,*quantity,**price):
    print("-- Do you have any ",kind,"?")
    print("--- Iam sorry we are all out of",kind)
    for arg in quantity:
        print(arg)
    print('-'* 40)
    for kw in price:
        print(kw,":",price[kw])
//result will be as
 grocery("broccoli",3,4,5,broccoligrade1 = 25,broccoligrade2 = 35,broccoligrade3 = 45)
-- Do you have any  broccoli ?
--- Iam sorry we are all out of broccoli
3
4
5
----------------------------------------
broccoligrade1 : 25
broccoligrade2 : 35
broccoligrade3 : 45

the point here to note is that the order in which the keyword arguments are printed is guaranteed to match the order in which they were provided in the function call


Thats all for this post guys hope you like it to get latest lessons follow by email and share if you want to know more about other languages and my other works or have any doubts please follow and comment below

Sunday, June 10, 2018

python chap 11 (Hi friends this post is made as chapters so read the previous chapters for better understanding. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section)

break , continue statements  and else clause on loop

                               This statements are used as it describe break statement break out of the innermost enclosing for or while loop and the continue statement continue through the next iteration of the loop and the loop may have an else clause it is executed when the loop terminates through exhaustion of the list with for or when the condition becomes false with while loop but not when the loop is terminated by a break statement

for x in range(10,20):
        if x==15:
            print("no way for 15")
            break
        if x%2 == 0:
            print("found an even number")
            continue
        print(x," is a prime number")


for x in range(2,10):
    for l in range(5,x):
        if l == 7:
            print(x,"i got from seven to 10")
            break
    else:
       print(x,"i got from two to seven")

In this code we can clearly see the job done by each of the statements first the for loop iterates from 10 to 20 and it checks in the if statement that the iterating value in x is it equal to 15 and if it is equal then it will print "no way for 15" and break statement is done which will terminate the loop and if it is not equal to 15 then it will check in the second  if statement that x%2 is equal to zero if it is then it will print "found an even number" and then the continue statement will be done the continue statement continues with the next iteration of the loop. and if x%2 is not equal to zero then prints "x is a prime number"
And here in the next code block the first for loop iterates from 2 to 10 and each iteration from 5 there is another for loop which iterates to the value of x next to 5 and in that for loop if value is equal to 7 then it will print x"i got from seven to 10" and there is an else clause which prints from the beginning of the for loop from two to seven here one thing to note is the else clause is the else of the second for loop not the if statement

pass statement

The pass statement does nothing it is used when we need a statement syntactically but the program requires no action
while True:
          pass
This will make a busy wait for keyboard interrupt (ctrl+c) can also be used to create minimal classes like

class MyClass :
           pass


Another place where pass can be used is as a placeholder for a function or conditional body when you are working on new code allowing to thinking at a more abstract level the pass is silently ignored
def  myfunc(*args):
          pass #remember to implement this

Functions

function is a named code block of the program where a specific task is executed in python there are many built in functions like print().
  • the function starts with the keyword def 
  •  followed by a name will be given to the function the conventional style for naming of a function is like lower_case_with_underscore 
  • next comes the parenthesized list of formal parameters we can also define parameters inside this parenthesis and the code block in python starts with a colon (:) and is indented
  • in the first line of the body of the code block  can be an optional string literal this string literal is the functions documentation string or doc string  
  • And then the code is written for the specific task and the statement return [expression] exits the function optionally passing back an expression to the caller the return statement without an expression argument returns None Falling of the end of a function also returns None 

More on functions will be included in the next post Hope you like the post and if you have any doubts or suggestions include it in the comment section and don't forget to share and follow to get latest posts on this blog follow by email 

Saturday, May 26, 2018

python chap 10 (Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section)

Control Flow Tools

The control flow is the way to control the code to process or control flow is the order in which the code executes simply by using control flow tools we control which code should execute and how many times a code should execute like stuffs more will be understood from the section given below

if Statements

Perhaps one of the popular statement is the if statement as we can see an example here

x = 12
if x==10:
     print('x is 10')
elif x == 21:
        print ('x is 21'):
elif x== 22:
       print('x is 22')
else:
       print ('x is 12')
#here the result will be 'x is 12'
here the statement checks if x is equal to 10 but it is already assigned 12 and then the code jumps to elif statement and checks the elif  is used to check another statement as if x is equal to 21 and it is also not equal to then it checks other elif and after that at last to finish if every thing returns false we use else as last resort to put a default value there we print as x is 12 then it will be the result here
Now we can make a nested if else statement the examples are given below
x = 12
if x < 15:
     if x==13:
         print('x is 13')
      else:
           print (x is 12)
if x==12:print('x is 12')
          print('hi everybody')
here we have learned that if statement without else and nested if statement is also made here
and if the suite of an if clause consists of single line then it may go on the same line as a statement like above statement where the out put will be x is 12 and in the next line hi everybody


while statement

The statements are executed sequentially one after the other there may be a situation when we need to execute a block of code several number of times here comes the loop statement which helps us in executing a code block several number of times one of that is the while statement 
now we can see it in the code here given below simply while statement is used for the repeated execution of code as long as the given expression is true  
x = 10
while x < 10:
        print (x)
        x = x + 1
5
6
7
8
9 #the output will be as follows till the condition in the while statement x<10 is true
In here we can see that what the while statement will do in here the statement puts a condition as x<10 so here the code below which is print (x) will print the value of x and after that the x is added  with 1 and until the condition become false x < 10 the print statement will print the value of x it will result in the out put of 5,6,7,8,9 

for loop statement

The for loop statement is somewhat different from other programming languages where the for loop statement in here the statement in the for loop is executed until the for statement iterates over the item of any sequence (a list of a string ),in the order that they appear in the sequence is complete as for example :

my_list = ['dog','god','direction','hit','yeild']
for letters in my_list:
       print (letters,len(letters))

dog 3
god 3
direction 9
hit 3
yeild 5
In here we can see that the values in my_list is printed one by one with its length here the process is that the items in the list my_list is put one by one in the letters and printed until all the items are printed and there is another way of using for loop is that the range() function here is an example
for letter in range(5):
              print(letter)

0
1
2
3
4
In here the values in the range from 0 to 5 is put one by one in letter and printed out more on range will be given in the next post and in for loop we can put the sliced sequence in the for loop to execute statement as example


my_list = ['man','jack','ace','mike','jill','cap','care']
for words in my_list[2:5]:
           print(words)

ace
mike
jill

We can see here that the items in the my_list from 2 to 5 is only printed by putting the sliced list in the for loop

Thats it friends more on this lesson like range() will be explained in the next post till then understand the stuff given here and if you have any doubts or suggestions please comment below your valuable suggestions can improve this blog further more and don't forget to share and if you want to get latest lessons please follow by email or follow me

python chap 9 (Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section)

PYTHON BOOLEAN OPERATORS
The boolean operators can be used as. Assume variable a holds true and variable b holds false
these are the boolean operations ordered  by ascending priority
  • or operator : it is used as : a or b : results if a is false then b else returns false : here it is a short circuit operator it only evaluates the second argument if only the first one is false
  • and operator : it is used as : a or b : if a is false then a else b  : it is also a short circuit operator it only evaluates the second argument if the first one is true
  • not operator : it is used as :  not b : if x is false then True else False : not has the lower priority than the non boolean operators so not(a==b) is interpreted as not (a==b) and a == not b is a syntax error
>>>a =True
>>>b = False
>>>a and b
 False
# here if a is true it will evaluate b and if both a and b
#are true then it returns true else false
>>>a or b
True
#here it is True if value of a or b is true it evaluates
#true if it finds a to be true first it will not evaluate
>>>not (a==b)
True
#it will return true because a is not equal to b


Here is another comparison type operator
here the identity operators compare the memory location of two objects here are two identity operator
  • is : a is b :returns true if the variable on the either side of the operator points to the same object and false otherwise
  • is not: a is not b : returns true if the variable on the either side of the operator does not point to the same object otherwise false
Python membership operator
this are the in and not in operators here are
  • in  :it returns true if it finds a variable in a specified sequence and otherwise false 
  • not in : it returns true if it doesn't find a variable in a specified sequence and otherwise false
>>>a = "nads"
>>>b = "sani"
>>>a is b
False
>>>a is not b
True
>>> c = [ 'raj' , 24 , 'kumar']
>>> d = 'raj'
>>>d in c
True
>>>d not in c
False

Python operator precedence  

The python operator priorities are which in a statement when multiple operators are used then the priorities are given to certain operator than the other this is called as operator precedence for example if multiplication ,division and addition are there then priorities have to be given to multiplication and division have high priority than addition  so here are given some operators with there precedence from lowest to highest
  •  not or and : logical operator
  • in , not in 
  • is , is not
  • Assignment operator:  =   %=  /=   //=   -=  +=   *=   **=
  • Equality operator:  <  >  ==  !=
  •  Comparison operator: <=  <  > >=
  • Bitwise Exclusive OR and regular OR:  ^  | 
  • bitwise and :&
  •  Right and left bitwise shift:<<  >>
  • x + y : sum of x and y 
  • x - y : difference of x and y
  • x * y : multiply x and y
  • x / y: division of x and y 
  • x // y : floored quotient of x and y 
  • x % y : remainder of x / y
  • ~ + - :Ccomplement , unary plus and minus(method names for the last two are +@ and -@)
  • ** : Exponentiation (raise to the power)
Thats all for this post guys hope you like this post you well understood it if you have any doubts please comment below and to get latest updates on this lesson follow by email or follow me and don't forget to share and comment

Friday, May 25, 2018

python chap 8 (Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section)

PYTHON OPERATORS

The other operators are Comparison operators: a = 10 and b = 30
  •  ( == ) equalto : here we put a == b if a is equal to b it will return true otherwise false so here it will return false
  • ( != ) not equal to , here we put a != b if a is not equal to b then it will return true so here it will return true
  • ( < ) less than , here we put a < b if a is less than b then it will return true other wise false so here it will return true
  •  ( > ) greater than, here we put a > b if a is greater than b then it will return true otherwise false so here it will return false 
  • ( >= ) greater than or equal to , here we put a >= b if a is greater than or equal to b then it will return true otherwise false so here it will return false
  •  (<=) less than or equal to : here we put a <= b if a is less than or equal to b then it will return true otherwise it will return false so here it will return true
Assignment operators
  • ( = ) Equal to assignment : c= a+b here c is assigned the value of a+b
  • ( += ) ADD AND : here we put as 10+= 5 by adding the two values 10 and 15 return 15
  • ( -= ) Subtract AND: here we put 10 -= 5  by subtracting 5 from 10 return 5
  • (  *= ) Multiply AND : here we put 10* = 5  by multiplying 5 and 10 returns 50
  • ( /= ) Divide AND: here we put 10 / = 5  by dividing  10 by 5 returns 2
  • (% = ) Modulus AND:here we put 21 %= 10 by modulus 21 and 10  and returns the coefficient is1
  • (**=) Exponent AND:here we put 2**=4 is 2 to the power of 4 returns 16
  • (//=) Floor Division: it is the same as a//=b is the same as a//b as explained earlier
Bit Wise Operators
The bitwise operators are which works on bits and performs bit by bit operation as simple computers knows only 0 and 1 the binary language. A bitwise operations operates on one or more bit patterns or binary numerals at the level of there induvidual bits it is a fast simple action supported by the processor and is used to manipulate values for calculation and comparison her are some examples given as  a = 50
b = 25 the binary of this numbers is
a =0011 0010
b= 0001 1001
the operations can be done as 
  • a & b = 16 binary is 0001 0000 : It is a binary AND operator here operator copies a bit to the result if it exists in both operands
  • a | b = 59  binary is  00111011: It is a binary OR operator It copies a bit if it exists in either operand
  • a ^ b = 43 binary is  0010 1011: It is a binary XOR operator It copies the bit if it is set in one operand but not both
  • ~a = -51 is the ones complement it is unary and has the effect of flipping the bits 
  • Binary Left shift operator << :the left operands value is moved by the number of bits specified by the right operand : a << 1 = 100 here a is 50
  • Binary Right shift operator the left operands value is moved right by the number of bits specified by the right operand : a >> 1 = 25 here a is 50

More on operators like logical operators will be discussed on the next section hope you understand this lesson if you have any doubts please comment below and to get latest lessons and updates on this lessons don't forget to follow by email or follow me and don't forget to share and comment your suggestions below

python chap 7 (Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section)

SET TYPES:set and frozenset

The sets are unordered collection of unique items that is iterative and mutable the benefits of using sets other than list is that they can highly optimized method for checking whether a specific element is contained in the set this is base on a data structure known as hash table (hash tables are a type of data structure in which the address or the index of the data element is generated from a hash function that makes accessing the data faster as index value behaves as a key for the data value.hash table is advanced topic we will learn about hash table later) simply there is no duplicate elements in the sets set object also supports mathematical operations like intersection , union ,difference and symmetric difference
                                      Curly braces or the set() function can be used to create sets and to create an empty set you have to create set() not empty curly braces {} this will only create an empty dictionary the sets are mutable they not have hash value and cannot be used as either a dictionary key or as an element of another set other one is the frozenset it is which is immutable and hashable its contents can't be altered after it is created therefore it can be used as a dictionary key or as an element of another set non empty set (not frozensets) can be created by placing comma separated list of  elements within braces for example {'vasu','ramu'}.in addition to the set constructor.
The constructor for both classes work the same for example
set([iterable])
frozenset([iterable])
which returns a new set or frozenset object whose elements are taken from iterable the elements of a set must be hashable to represent a set of set the innerset must be frozen set objects if iterable is not specified a new empty set is returned here are some examples given
Instance of sets and frozen set provides the following operation
  • len(s) : Returns the number of elements in the set (cardinality of s)
  • x in s : Test if x is a member of s 
  • x not in s : Test if is not a member of s
  • isdisjoint(other):Return true if the set has no elements in common with other set are disjoint if and only if their intersection is the empty set 
here are some samples of sets
my_set = {'swaraj','ramz','ayoob',25,56,89}
normalset = set(['arun','thariq',45,85])
print (my_set)
#will print the my_set set values
frozset = frozenset (["e","f","g"])
print(frozenset)  #this will print the complete frozenset values
More on this will be discussed later 

 OPERATORS

The operators are the special symbol in python that carry out arithmetic or logical computation the values which the operation takes place is the operands and the for example 5+3 the 5 and 3 are operands and + is the operator here we will learn about different types of python operators
  • Arithmetic operators : this operators which are (+) addition, (- )subtraction, (*) multiplication , ( / ) division, its simple every body knows what this operators do and there is one more operator which is floor ( // )  its a type of division were we get a result after discarding the fractional value we get a integer value simply the results are the quotients in which the digits after the decimal point are removed but if one of the operand is negative the result is floored rounded away from zero (towards negative infinity ) other one is the ( % ) Modulus divides left hand operand by right hand operand and returns remainder,(**)exponent performs exponential calculations on operators and here are some  examples for all
9//2 = 4
9.0//2.0 = 4.0
-11//3 = - 4
-11.0//3 = -4.0
#other examples for + , - , / , *
5 + 3 = 8
5 * 3 = 15
5 - 3 = 2
4 / 2 = 2
21 % 10 = 1 
2 ** 4 = 16

More on operators will be on the next post and thanks for viewing my post hope you like the post. Friends to get latest and next lessons on this subject please follow by email or follow me and don't forget to write your valuable suggestions on the comments and share this blog with your friends

Thursday, May 24, 2018

python chap 6(Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section )

TUPLE

A tuple is another sequence data type and they are immutable means we cannot update the items in the tuple they consists of number of items separated by commas the items may be of different types also. Unlike list tuples are enclosed within parenthesis. These are the main difference between lists and tuples that list are enclosed in square brackets and tuples are enclosed in parenthesis and tuples are immutable and lists are mutable. Like in the Lists tuples also can be indexed sliced and concatenated the tuples with one element can be written by placing a comma after the element and we can create an empty tuple and here are some examples for them 
 
my_tuple = ('jack',256,'mom',12.35,'lisy')
next_tuple = ('nadeem',457)
empty_tuple = ()       #empty tuple
single_tuple = (54,)  # a tuple with single element
print (my_tuple)       #prints complete tuple
print (my_tuple[0])   #prints first element of the tuple
print(my_tuple[1:3]) #prints elements from second to third element
print(my_tuple[2:])   #prints element from second to end
print (next_tuple*2)   #prints tuple two times
print (my_tuple + next_tuple ) #prints concatenated tuple

now we can see the results
('jack',256,'mom',12.35,'lizy')
jack
(256,'mom')
('mom',12.35,'lizy')
('nadeem',457,'nadeem',457)
('jack',256,'mom',12.35,'lisy')
And like in lists we can't update values in tuple because they are immutable here is an example below were we try to update a tuple and a list the list updates the value but the tuple will show error as the tuple can't be updated
my_tuple = (24,54,65,75)
my_list = [24,54,47,85]
my_tuple[2] = 321 #invalid syntax with tuple
my_list[2] = 542  # the syntax is a valid syntax



PYTHON DICTIONARY

                      Python dictionary are unordered set of key value pairs they are like associative arrays in other languages unlike sequences which are indexed by a range of number the dictionary are indexed by key's which can be any immutable type but are usually numbers and strings . Tuples can be used as key if they only contains strings, numbers or tuples if a tuple contains any mutable object directly or indirectly they can't be used as key's .Values in the dictionary are arbitrary objects
                     Dictionaries are enclosed by curly braces  ({}) and  a pair of braces creates empty dictionary and coma separated list of key:value pairs adds initial key:value pairs to the dictionary this is also the way dictionaries are written on the output and values can be assigned and accessed using square brackets.
                     In dictionary we can store a value with a key and access the value using the key it is also possible to delete the key value pair with the del if you store a value using a key that is already in use the old value in the already used key is forgotten. It is an error to extract a value using a non existent key.here some examples are given below

                       
my_dict = {}
my_dict = {'name':'nads','age':27,'height':6.6,'hair':'blue'}
my_dict1['name']={'majeed'}
my_dict1[27] = {'age'}
print (my_dict) #prints the complete my_dict
print(my_dict1['name']) #prints the value of 'name' key
print(my_dict1[27])    #prints the value of 27
print(my_dict.keys()) #prints the keys in my_dict


Now we can see the results
{'name' : 'nadeem','age':27 , 'height':6.6 ,'hair':'blue'}
majeed
age
['name','age','height','hair']

Data Type Conversions

Some times we need  conversions between built in data types like to change a data type of a value into another data type to convert a data type we simply use the type name as a function(function is a block of  organised reusable code to perform a single related action more on functions will be described on coming lessons) there are several builtin functions to perform conversion from one data type to another data type these functions returns the converted result (here the return means in a function after the process is complete in a function the result is outcomes as return you will understand more on returns in the coming lessons).Here are some examples of some builtin conversion functions given below

  • int (x ,base):This function converts any data type to integers base specifies the base in which the string is if data type is string
  • float (x) : This will convert any data type to floating point numbers
  • str(x) :Converts object x to string representation
  • complex(real,imag):Creates a complex number
  • hex(x): Converts integer to hexadecimal
  • oct(x):Converts integer to octal string 
  • ord(c):Converts a character to integer
  • tuple(s):This function is used to convert to a tuple 
  • list(s):This function is used to converts  s  to list
  •  dict(d):This function is used to convert a tuple of order (key,value ) into a dictionary 
  • chr(x):Converts an integer to character 
  • unichr(x):Converts an integer to Unicode character 

 learn more in the next post thanks for viewing this post guys follow by email to get new lesson updates of this blog and don't forget to follow ,share and comment your suggestions


Wednesday, May 23, 2018

python chap 5(Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section )

STRING

The built in string object is a sequence of character used to store and represent text based information (plain strings are also some times used to store and represent arbitrary sequences of binary bytes ).a string can be pair of single quoted or double quoted. Subsets of strings can be taken using the slice operater( [], [:] ) with indexes starting at 0 in the beginning of the string and working there way from -1 to the end strings.Strings are immutable
my_values = 'I\'m nadeem and this are my\
                  string object for the single quote' 
my_values1 = "I'm nadeem and this are my\
                 string object for the double quote"  
my_values2 = """I'm nadeem and this are my
                  string object for the triple quote"""
print(my_values)            # prints the whole string
print(my_values[0])        #prints the first character
print(my_values[2:5])    # prints character from third to five
print (my_values [2:])    #print the characters starting from the third to the end


In the above example you have seen the backslashes on the single quoted value which on printing the output will display only the single quote in between the I and m or you can use like in the second value were a pair of double quote is used. There the single quote is placed  between the I and m here backslash is not needed and in the single quote and double quote string here the line break is defined by using backslashes. And we can use triple quoted strings so that to break line we doesn't need backslashes line break is defined as we have defined in the string literal. And strings can be indexed and sliced in the given example with print() statement above were the first one prints the whole value and the second one prints the first character and the third one will print the characters from third to the fifth one and the fourth one will print the character from the third to the end character.String also supports concatenation and here are some examples given below

my_value ="My name is  "
my_second = my_value + "nadeem"
print(my_second)

the value here are concatenated and the result is as given here
My name is nadeem
Okay guys more will be discussed on string in the coming lessons

LISTS

The lists is a mutable sequence of items the items inside the lists are arbitrary objects and may be of different types like strings and numbers The list defined using a square bracket were the items are put with commas in between the items and optionally we can add a comma after the last item. To denote empty list define a empty square bracket examples are given below

nads_sad = []             #empty list
nads_sad = ['animals','birds',24,26,24.35]  #list with different data types

In the above example we saw the empty list and the list with values of different types .Like strings (and like all other builtin sequence type) lists can be indexed and sliced All slice operations returns a new list containing the requested elements .Lists also supports operations like concatenation and Unlike strings which are immutable lists are mutable it is possible to change their content you can also add items at the end of the list the built in function len() also applies to list which gets the length of the list it is also possible to nest lists can create list containing other lists here are some examples for this 
first we will see list indexed and sliced

my_list = ['a','b','c','d','e','f']
print(my_list[0])    #prints the first element in the list
print (my_list[2:])  #prints items from third to the end
#list concatenation
my_list2 = ['h','j','p']
print(my_list + my_list2) # outputs #['a','b','c','d','e','f','h','j','p']
#list append() statement adds element to the end of the list
my_list .append('x') #prints the value ['a','b','c','d','e','f','x']
#now applying the built-in function len()
len(my_list)
#prints 6
#nested list creating list containing another list
my_list3 = ['a','b','c']
my_list4 = [2,4,6]
a = [my_list3,my_list4]
# if a is printed it will out put as [['a','b','c'],[2,4,6]]



Thats all for this post friends more lessons will be on the next post 

THANKS FOR VIEWING MY BLOG HOPE YOU LIKE THE POST IF YOU WANT TO GET LATEST POSTS ON THIS PLEASE FOLLOW BY EMAIL ID AND FEEL FREE TO ASK YOUR DOUBTS AND DON'T FORGET TO SHARE,COMMENT AND FOLLOW


Tuesday, May 22, 2018

python chap 4 (Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section)

  

Tokens :

The python program is read by a parser this input to the parser is the tokens which is generated by the lexical analyser . Each token corresponds to the sub string of logical lines the normal token types are identifiers, keywords, operators ,delimiter and literals which will be covered in the coming section. As you may use whitespace between tokens to separate them. Some whitespace seperation is necessary between logically adjacent identifiers or keywords otherwise the python would parse them as single longer identifiers like the statement printj will be a single identifier so to write the j we need to put space between print and j as like print ("j") this will print j .


ASSIGNING VALUES TO VARIABLES

              
                    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 a value  to a variable the operand to the left of the equal sign is the name and the other one on the right is the value stored in the variable here is an example :



name_value = "this is a string value "       #this is a string value
num_value =   458
                             #this is a integer value
                        #we will come to string and integer later on

And in python a single value can be assigned to multiple variables simultaneously  for example

a = b = c = 2
here a single value is assigned to multiple variables like the value 1 is assigned to a,b and c and then in python multiple objects can be assigned to multiple variables for example :

a,b,c = 1,2,"nadeem"
In here two numbers 1 and 2 are applied to a and b respectively and nadeem is assigned to c 


DATA TYPES

                                      Data types are simply classification of data in to which tells the compiler or interpreter how the programmer intents to use the data .A data stored in memory can be of different types for example "john" is a string data type and 21 is a integer data type. Python has various standard datatypes that are used to define the operation possible on them and the storage method for each of them . simply the data type determines what kind of operation can be done on the data value. An object which can be altered is known as mutable and which cannot be altered is known as immutable objects (friends you will be confused with objects you will understand it in the coming lessons so be patient).

                                   python has built in data types such as  numbers,strings,lists,tuples and dictionaries and you can also create your user defined types known as classes will be discussed on the coming lessons             

NUMBERS

Number data type store numeric values like 1,2,3 and number objects are created when you assign a value to them. Number object supports integers (long and plain), floating point numbers  and complex numbers. You can also delete a reference to a  number object by the del statement python supports three different numerical types 
  • INTEGER (signed integers like 10,12,-23,-95):
             All integers in python 3 are represented as long integers there is no separate number type as long . python integer literal contains decimal , octal and hexa decimal values
          
  • FLOAT(floating point real vlaues like -21.3,32.3+e18,-32.54e100): 
            The floating point numbers are which contains sequence of decimal digits that includes decimal points(.) an exponent path (an e or E optionally followed by + or - followed by one or more digits ) or both but the leading character of a floating point literal can't be e or E. it may be any digit or period the example for floating point are given above .
  • COMPLEX NUMBERS(3.14j,45.j)
The complex numbers is made up of two floating point values one each for the real and imaginary part for example a complex number consists of an ordered pair of real floating point number denoted by x + yj where x and y are real numbers and j is the imaginary unit

More on number data types and how we can use them will be understood from the coming lessons 
so don't worry if you didn't get all of it .

THANKS FOR VIEWING MY BLOG HOPE YOU LIKE THE POST IF YOU WANT TO GET LATEST POSTS ON THIS PLEASE FOLLOW BY EMAIL ID AND FEEL FREE TO ASK YOUR DOUBTS AND DON'T FORGET TO SHARE,COMMENT AND FOLLOW 

Python chap 3(Basic syntax:Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section )

    

MULTI-LINE STATEMENT

                        In python the end of physical line marks the end of the statements and if there is a necessity of  multiple lines of code to be used python uses a backslash at the end of the line if there is no comment after the line and the other code comes as next line then it will be considered as one line in the code as example here a code is given 
if 2000<year<3000 and 1<= date<=30\
    and 1<=hour<=24 and 1<=minutes<=60\
    and 1<=seconds<=60:
             return 1
if you don't understand the code leave code and focus on backslashes that is our job if you are not sleeping you can see that more on codes will be explained in the coming lessons and the other thing to note here is that the statements contained within the [],{},() doesn't need the backslashes to use because it can identify the line using this braces like the statement given below :

animal_names = [cat,dog,fish,cow,camel,goat,     #here comes the comment
               sheep,wolf,bear,elephant,snake,
               dolphin,peacock,cat,whale,pigeon]                                        

                             Comments

A comment is used to it is a programmer readable part in the code which is ignored by the interpreters and compilers it is used for the purpose of humans to understand the source code. In python the comment starts with a # character which is not part of string literal and ends at the end of that same physical line . And also the comment signifies the end of the logical line and there is this other case that logical line is in a way which the statement is inside the braces like the statement given above it doesn't depict as end of the statement

here is an example of comment in single line
#here is the single line command
there is no appropriate multiline commenting feature for python but you can do it by commenting each line individually or there is a little difficult way like triple quotes which has a problem when you are inside a class you should indent it properly simply you can use it when they are not a docstring an example is given below as 



#this is the first comment
#this is the second comment
#this is the third comment
"""
This is a
multi line comment

"""
"""
    def future_code(self,url):
           here it is not a
           proper code it is for
           example that you should
           indent here properly

"""

Quotations in python

The python uses single('single quotes')  double("double quotes") and triple quotes("""triple quote""" or '''triple quote''' ) to denote string literals as long as the same type of quotes starts and ends the string literals the triple quotes are used for the multiple string lines 
here are some examples 
animals = 'this is animals '
machines = "this is double quotes"
birds = """this is triple quotes
here it is in multiple lines"""

USE SEMICOLON TO ADD MULTIPLE STATEMENTS ON A SINGLE LINE

Can use multiple statement on a single line with the use of semicolons like in the statements given below

if x<y;print('x');print('y')

USE COLONS ON COMPOUND STATEMENTS

A compound statements consists of one or more clauses A clause consists of a header and a suite a clause header of a particular compound statement are all at the same indentation level each clause header begins with a uniquely identifying keyword and ends with colon a suite is a group of statements controlled by the clause a suite can be made with one or more colon separated simple statements on the same line as the header following the headers colon or it can  one or more indented statements on subsequent lines only this indented statements can contain nested compound statements as example given here

if expression:
      suite
elif expression:
     suite
else:
    suite


COMMAND LINE ARGUMENTS
In the command line we can start a program with additional arguments this arguments are passed in to the programs many programs can be run to provide you with information  about how they should be run python enables you to do this with -h- you can program your script in such a way it should accept various options command line arguments is an advanced topic we will come to that later

that's all for this post

THANKS FOR VIEWING MY BLOG HOPE YOU LIKE THE POST IF YOU WANT TO GET LATEST POSTS ON THIS PLEASE FOLLOW BY EMAIL ID AND FEEL FREE TO ASK YOUR DOUBTS AND DON'T FORGET TO SHARE,COMMENT AND FOLLOW 

Saturday, May 12, 2018

Python chap 2 (Basic Syntax:Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section )

                       

   Start with Interactive Mode 

friends we are here to learn the python 3 it is somewhat different from python 2  lets begin. If the commands are read from a tty the interpreter is said to be in interactive mode .Interactive mode is a command line shell which gives immidiate feedback for each statement and while running previously fed statements in active memory The interpreter prints a welcome message stating its version number and a copyright notice before printing the first prompt:
$ python3.6
 Python 3.6 (default, Sep 16 2015, 09:25:04)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>


now type the following code 

>>> print ("HELLO, WORLD!")

This produces the result as
HELLO, WORLD!

Scripting Mode

On Installing python you will get a default python IDE "IDLE" lets write some code now in the Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active. Let us write a simple Python program in a script. Python files have extension .py. Type the following source code in a nads.py file
print("HELLO, WORLD!")
you should have Python interpreter set in PATH variable.to know about how to set python interpreter view my previous posts Now, try to run this program as follows
$ python nads.py
This produces the following result
HELLO, WORLD!

Python Identifiers

Python identifier is a name used to identify a variable, function, class, module or other object(all of this will be explained in the coming lessons).many other programming languages insist on having every identifier used in code have type information declared for it.but python doesn't need so. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).

                          Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Atom and atom are two different identifiers in Python.
 The naming conventions for python are
  • Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
  • Starting an identifier with a single leading underscore indicates that the identifier is private.
  • Starting an identifier with two leading underscores indicates a strongly private identifier.
  • If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.
here is an example of python identifiers:


name_value = "this is a string value "
num_value = 458

RESERVED WORDS

reserved words are keywords those words which can't be used as a variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language. In Python, keywords are case sensitive.


andexecnot
assertfinallyor
breakforpass
classfromprint
continueglobalraise
defifreturn
delimporttry
elifinwhile
elseiswith
exceptlambdayield

LINES AND INDENTATION


A python programme is composed of a sequence of logical lines each made up of one or more physical lines of codes in python end of a physical line marks the end of the statement in other languages like java there is semicolon added at last to end of the statement
                     In python there is no curly brackets {} like in other languages to indicate blocks of code for class and functions definition or flow control . Here in python they uses indentation to indicate the block of code the number of spaces is variable but the different statements within the  code blocks must be at same amount of space like in the code given below
if True:
    print("true") 
else :
    print("false")
 
that's all for this post guys More on this part will be discussed in the next post

 

 

THANKS FOR VIEWING MY POST HOPE YOU LIKE THE POST PLEASE FOLLOW,SHARE AND PUT YOUR COMMENTS IN THE COMMENT SECTION

Friday, May 11, 2018

Python chap 1 (Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section )

First we need to know the basic characters of a python language they are
And now we need to start to install python in our machine first
type python in the command line which can be selected from the start button by typing cmd it will give us the info that if python is installed and which version is installed if it is not installed
you can install it from python official site for that click here you will get the full most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python https://www.python.org/
you can start to install python from that site and if you have any doubt on that please inform me on the comment section
Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python. If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation. Here is a quick overview of installing Python on windows platform −

                              Installing on Windows

To install on windows you need to go to this python download link https://www.python.org/downloads/ and from there download from the windows version some points to remember are
  •  If installing Python 3.6 as a non-privileged user, you may need to escalate to administrator privileges to install an update to your C runtime libraries.
  •  There are now "web-based" installers for Windows platforms; the installer will download the needed software components at installation time.
Then after downloading the file run it Just accept the default settings, wait until the install is finished, and you are done.

                                    Setting up PATH

Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables.

                    The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs.
               The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not).In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path.


                         Setting path at Windows

To add the Python directory to the path for a particular session in Windows −At the command prompt − type path %path%;C:\Python and press Enter. 
Note − C:\Python is the path of the Python directory

                                   THE PYTHON ENVIRONMENT VARIABLES ARE
It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.and the other environment variables are 
  • PYTHONPATH:
    It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.
  •  PYTHONSTARTUP:
    It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH.
  •  PYTHONCASEOK:It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.
  •  PYTHONHOME:It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.

                                      RUN PYTHON

The python codes can be run using three ways
  • Interactive Interpreter

    You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window. 

  • Script from the Command-line

    A Python script can be executed at command line by invoking the interpreter on your application

  • Integrated Development Environment

    You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python.

    • Unix − IDLE is the very first Unix IDE for Python.
    • Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI.
    • Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files.
If you are not able to set up the environment properly, then you can ask in the comment section. Make sure the Python environment is properly set up and working perfectly fine.You can use other IDE like PyCharm,PyDev or Komodo IDE I am using PyCharm

OKAY THANKS FOR VIEWING MY POST . HOPE YOU LIKE THE POST AND DON'T FORGET TO COMMENT,SHARE AND FOLLOW