Thursday, June 14, 2018

Flow Control in Python



Flow Control


-> Computer programs are always executed in sequential manner.

->Anticipated possible condition occurring while execution of the program and specify instructions to be executed for each condition.

->Decision statement evaluates logical expression in which produces TRUE or FALSE as outcome.

->Specify statements to execute if outcome is TRUE or FALSE

->non-zero and non-null value as TRUE. Zero or null is assumed FALSE





Program flow can be altered using:-


->Branching or decision making

->Loops or iterations

Under Flow Control we study following Topic:


1. If Statement , If else Statement , Nested if statement

2. For loop, Use of range().

3. While loop, While loop with else.

4. Break and Continue.

5. Pass Statement.

6. Looping Technique.


We Cover All Topic one by one in details:

 
Prev: Namespace InPython
Next: If statement in Python



Tuesday, June 12, 2018

Namespace in Python


What is Namespace?

In general, Namespace is just a containers for mapping name to objects.




A set of independently identifiable expectations
+
A unique (within set) label for each member
Context + Name => Value


Namespace Containers:
->mapping-based hold volatile type of namespace
->attribute-based hold stable type of namespace
->property-based hold static type of namespace


Prev: Operators InPython

Next: Flow Control in Python

Operators in Python




To perform any operations on variables and value we can use Operaters,

There are some operators in python language are as following:

Arithmetic Operators

Comparison (Relational) Operators.

Assignment Operators

Logical Operators

Bit wise Operators

Membership Operators

Identity Operators

Let see one by one



Arithmetic Operators


Operator
Description
Example
+ (Addition) Adds values on either side of the operator. ->x + y
10 + 20 = 30
- (Subtraction) Subtracts right hand operand from left hand operand ->x – y
10 – 20 = 10
* (Multiplication) Multiplies values on either side of operator ->x * y
10 * 20 = 200
/ (Division) Divides left hand operand by right hand operand ->y/x
20/10 = 2
% (Modulus) Divides left hand operand by right hand operand and returns remainder ->y % x
20 % 10 = 0
** (Exponent) Performs exponential (power) calculation on operators ->x **y
10 ** 2 = 100
// Floor Division of operands where the result is the quotient in which the digits after the decimal point are removed ->x//y
20//10 = 2
and
20.0//10.0 = 2.0


Comparison Operators


Operator
Desicription
Example
== If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!= If the values of two operands are equal, then the condition
becomes true.
(a!= b) is true.
> If the value of left operand is greater than the value of right
operand, then condition becomes true.
(a > b) is not true.
< If the value of left operand is less than the value of right
operand, then condition becomes true.
(a < b) is true.
>= If the value of left operand is greater than or equal to the
value of right operand, then condition becomes true.
(a >= b) is not true.
<= If the value of left operand is less than or equal to the value
of right operand, then condition becomes true.
(a <= b) is true.


Assignment Operators:

Operator
Desicription
Example
= Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c
+= Add AND It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a
-= Subtract AND It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a
*= Multiply AND It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a
/= Divide AND It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a
%= Modulus AND It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a
**= Exponent AND Performs exponential (power) calculation on operators and assign value to the left operand C **= a is equivalent to c = c ** a
//= Floor Division It performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a


Bit wise Operators:


Operator
Desicription
Example
& Binary AND Operator copies a bit to the result, if it exists in both operands (a & b) (means 0000 1100)
| Binary OR It copies a bit, if it exists in either operand. (a | b) = 61 (means 0011 1101)
^ Binary XOR It copies the bit, if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)
~ Binary Ones Complement It is unary and has the effect of 'flipping' bits. (~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.
<< Binary Left Shift The left operand’s value is moved left by the number of bits specified by the right operand. a << = 240 (means 1111 0000)
>> Binary Right Shift The left operand’s value is moved right by the number of bits specified by the right operand. a >> = 15 (means 0000 1111)



Logical Operators:


Operator
Description
Example
and Logical AND If both the operands are true then condition becomes true. (a and b) is False.
or Logical OR If any of the two operands are non-zero then condition becomes true. (a or b) is True.
not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is True.



Membership Operators:


Operator
Desicription
Example
in Evaluates to true, if it finds a variable in the specified sequence and false otherwise. x in y, here in results in a 1 if x is a member of sequence y.
not in Evaluates to true, if it does not find a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y.



Identity Operators:


Operator
Desicription
Example
is Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. x is y, here is results in 1 if id(x) equals id(y).
is not Evaluates to false if the variables on either side of the operator point to the same object and true otherwise. x is not y, here is not results in 1 if id(x) is not equal to id(y).



Operators Precedence:


The following table lists all the operators from highest precedence to the lowest.

Operator
Desicription
** Exponentiation (raise to the power)
~+ - complement, unary plus and minus (method names for
the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right and left bit wise shift
& Bitwise 'AND'
^| Bit wise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators



Prev: Input,Output and Import InPython

References: tutorial point, Wikipedia

Input and Output Function in Python



Input() Function


Python has many built-in function in which one is input function.

Input function which lets you ask a user for enter some input.

The program will once resume once the user presses the ENTER Key.

Python 2.x using raw_input() .

Now Python 3.x use input().

Example:

name = input(“what is your name?”) # Out: What is your name? _



The function takes a string argument, which displays it as a prompt and returns a string. 

The above code provides a prompt, waiting for the user input.

If the user types “john” and hits enter, the variable name will be assign to the string “john” 

name = input("What is your name? ") # Out: What is your name? john

print(name) # Out: john

Note that the input is always of type str , which is important if you want the user to enter numbers. Therefore, you need to convert the str before trying to use it as a number:

x = input("Write a number:") # Out: Write a number: 10

x / 2 #ERROR!!! Out: TypeError: unsupported operand type(s) for /: 'str' and 'int' 


float(x) / 2 # Out: 5.0

print() Function

To Output data to the standard output device we use print function.

Example: print(‘Hello World!’) # Output: Hello World!

Using variables in print function

a = ‘Hello World!’

print(a)# Output: Hello World!

print(“The first program on any language is”, a) # The first program on any language is Hello World! 


X = 10

Y = 20

print(“value of x is {} and y is {}”, format(X,Y)) # Output: value of x is 10 and y is 20”.

Formatting using indexing


print(“value of x is {0} and y is {1}”, format(10,20)) # Output: value of x is 10 and y is 20”. 


print(“value of x is {1} and y is {0}”, format(10,20)) # Output: value of x is 20 and y is 10”. 


Keyword arguments print('Hello {name}, {message}'.format(message = 'Good morning', name = 'John'))


#Output: Hello John, Good morning 





Prev: Type Conversion In Python

Next: Operators in Python

Type Conversion in Python



Converting the datatypes of value to another datatype .

Python has two types of type conversion



1. Implicit Type Conversion


Here, python automatically converts datatype or set datatype .

Example:

myInteger = 789

myFloat = 1.34

myResult = myInteger + myFloat

print(“Datatype is: ”, type(myInteger)) #Output: <class ‘int’>

print(“Datatype is: ”,type(myFloat)) #Output: <class ‘float’>

print(“Datatype is: ”, type(myResult)) #Output: <class ‘float’>

Here myResult automatically Convert datatype:



2. Explicit Type Conversion


Here, we can convert the values datatypes manullay.

Example:

myInteger = 789

myString = “248”

print(“Datatype is: ”, type(myInteger)) #Output: <class ‘int’>
print(“Datatype is: ”,type(myString)) #Output: <class ‘str’>

newInteger = int(mystring)

print(myInteger + myString) # Output ERRROR!!!!!!!!!!!!!!
print(myInteger + newInteger) # Output: 1037



Several Built-in Functions


Function Description
int(x, [,base]) Converts x to an integer. The base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
Complex(real [,imag]) Create 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) Convert s to list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. D must be a sequence of (key, value) tuples.
frozenset(s) Convert s to a frozen set
chr(x) Converts an integer to a character.
Unichr(x) Convert an integer to a Unicode Character
ord(x) Converts a single character to its integer value.
hex(x) Coverts an integer to a hexadecemal string.
oct(x) Coverts an integer to an octal string.



Prev: Dictionaries In Python

Next: Input, Output Functions in Python

Dictionaries in Python



What is Dictionaries? 


Unordered collection of key-values Pairs.

It allows you to store and retrieve elements bye referencing a key.

Dictionaries are referenced by key , they have very fast lookup .

Dictionaries are primarily used for referencing items by key.

Dictionaries are not sorted

Examples:

myDis = {

“Mango” : ”yellow”,

“Apple” : “red”,

“chilly” : “green”

}

print(myDis) # Output { “Mango” : ”yellow”, “Apple” : “red”, “chilly” : “green” } 



Add a item:


myDis = {

“Mango” : ”yellow”,

“Apple” : “red”,

“chilly” : “green”

}

myDis[“orange”] = “orange”

print(myDis) # Output:{ “Mango” : ”yellow”, “Apple” : “red”, “chilly” : “green”, “orange”: “orange” }




In-built function: dict()


To create a dictionary

mydis = dict( “Mango” : ”yellow”, “Apple” : “red”, “chilly” : “green” )

print(myDis) # Output { “Mango” : ”yellow”, “Apple” : “red”, “chilly” : “green” } 



In-built function: del()


delete a dicitonry items:

myDis = {

“Mango” : ”yellow”,

“Apple” : “red”,

“chilly” : “green”

}

del(myDis[“chilly”] )

print(myDis) # Output:{ “Mango” : ”yellow”, “Apple” : “red” } 




In-built function: len()


myDis = {

“Mango” : ”yellow”,

“Apple” : “red”,

“chilly” : “green”

}

print(len(myDis)) # Output: 3





Prev: Sets In Python

Next: Type Conversion in Python

Sets in Python



What is Set?


Set is an unindexed and unordered collection of unique item.

Set are written with curly brackets.

Many operations perform on sets

intersection

union

difference

symmetric_difference

issuperset

issubset

isdisjoint


we learn all operation of set later chapter now we learn simple set. Because of it a very complicated once you can learn python basic then we jump on advance part of this course . 


Creating sets:


mySet = {5, 4, 6, 8, 9, 1}

print(myset) # output: {5, 4, 6, 8, 9, 1} 




Check Type :


print(type(mySet)) # Output:<class 'set'> 




In-built Function: set() 



Use Set() function to create set:

mySet = set((5, 4, 6, 8, 9, 1))

print(mySet) # Output:{5, 4, 6, 8, 9, 1} 




In-built Function: len()


To get the length of set

mySet = {5, 4, 6, 8, 9, 1}

print(len(mySet)) #Output: 6 




In-built Function: add()


use to add item into the set

mySet = {5, 4, 6, 8, 9, 1}

mySet.add(7)

print(mysSet) # Output: {7, 5, 4, 6, 8, 9, 1} 




In-built Function: remove()


mySet = {5, 4, 6, 8, 9, 1}

mySet.remove(1)

print(mySet) # Output: {5, 4, 6, 8, 9}





Prev: Tuples In Python

Next Dictionaries in Python

Tuple in Python



What is Tuple?


Tuple is an immutable list of value .

Tuple is Sequence data type .

It’s separated by commas.


Enclosed within parenthesis.

Tuple cannot updated value remain constant you cannot modified it. 

Tuple are used to write-protect data.


Examples:



Create a Tuple:


myTuple = (‘Sam’, ‘Bob’, ‘Cherry’, ‘john’)

print(myTuple) #Output: (‘Sam’, ‘Bob’, ‘Cherry’, ‘john’)



Access the Tuple Items:


myTuple = (‘Sam’, ‘Bob’, ‘Cherry’, ‘john’)

print(myTuple[0]) #Output: Sam 


In-Built Function: tuple()


Use to cnstructor the tuple

myTuple = tuple((‘Sam’, ‘Bob’, ‘Cherry’, ‘john’))

print(myTuple) #Output: (‘Sam’, ‘Bob’, ‘Cherry’, ‘john’) 


In-Built Funtcion: len()


To get length of tuple

myTuple = (‘Sam’, ‘Bob’, ‘Cherry’, ‘john’)

print(len(myTuple)) # Output 4



Don’t Do with Tuple:


myTuple = (‘Sam’, ‘Bob’, ‘Cherry’, ‘john’)

myTuple[1] = “Archu” # Output: ERROR!!!!!!!!!!

Later We learn Advance in Tuple





Prev: Lists In Python

Next Sets in Python

List in Python


What is List?


List is a general data structure widely used in python program. 


In other language referred to as dynamic arrays.



They are both mutable and sequence data type that allows them to be indexed and sliced. 


List contains items separated bye commas(,) and enclosed within square brackets([]). 

Like string list can be accessed using the slice operator([] and [:])



And Indexes starting at ) form beginning of the list and accessing the end using -1. 

Plus(+) sign is the list concatenation operator.

Asterisk(*) is the repetition operators.

Examples:



Creating a list:


myList = [‘abcd’, 9590, 894.78, ‘Justseeker’, True]

# Here myList contain various data type like float, int, bool

print(myList) # Output: [‘abcd’, 9590, 894.78, ‘Justseeker’, True]



Access item from the list


myList = [‘John’, ‘Cherry’, ‘Bob’, ‘Sam’]

# Accessing first item from the list

print(myList[0]) #Output: John

# Accessing List Item from the list

print(myList[-1]) #Output: Sam

# Accessing 1 to 3 items form list

print(myList[1:3]) # Output : [‘Cheery’, ‘Bob]

# Accessing 3 to last


print(myList[3: ]) # Output: ['Sam'] 



In-built function: list()


list() constructor to make a list

myList =list((‘john’, ‘Cherry’, ‘Bob’, ‘Sam’))

print(myList) #Output:['john', 'Cherry', 'Bob', 'Sam'] 


In-built function: append()


Append an item at the of the list

myList =[‘john’, ‘Cherry’, ‘Bob’, ‘Sam’]

myList.append(‘Ruby’)

print(‘myList) #Output:['john', 'Cherry', 'Bob', 'Sam', ‘Ruby’] 


In-bulit function:remove()


Remove item from the list

myList =[‘john’, ‘Cherry’, ‘Bob’, ‘Sam’]

myList.remove("Ruby")

print(mylist) #Output: [‘john’, ‘Cherry’, ‘Bob’, ‘Sam’]


In-built function: len()


myList =[‘john’, ‘Cherry’, ‘Bob’, ‘Sam’]

To get the length of list

print(len(myList)) # Output: 4



In-built function: clear()


Remove all element from the list

myList =[‘john’, ‘Cherry’, ‘Bob’, ‘Sam’]

print(mylist.clear()) # list is Empty 


In-built function: copy()


myList =[‘john’, ‘Cherry’, ‘Bob’, ‘Sam’]

copylist = myList.copy()

print(copyList) # Output: [‘john’, ‘Cherry’, ‘Bob’, ‘Sam’] 


In-built function: count()


Count that how many type item repeated

myList =[‘john’, ‘Cherry’, ‘Bob’, ‘Sam’, ‘Bob’]

countItem = myList.count(Bob)

print(countItem) # Output: 2 


In-built function: extend()


Extend or append all the item of list one into list second

myList =[‘john’, ‘Cherry’, ‘Bob’, ‘Sam’]

secondList = [‘Apple’, ‘Mango’, ‘Banana’]

myList.extend(secondList)

print(myList) #Output[‘john’, ‘Cherry’, ‘Bob’, ‘Sam’,‘Apple’, ‘Mango’, ‘Banana’]



In-built function: index()


To get index position

myList =[‘john’, ‘Cherry’, ‘Bob’, ‘Sam’]

indexItem = myList.index(‘Cherry’)

print(indexItem) # Output 1 


In-built function: insert()


Adds an element at the specified position

myList =[‘john’, ‘Cherry’, ‘Bob’, ‘Sam’]

myList.insert(1, ‘Ruby’)

print(myList) # Output: [‘Ruby’, ‘john’, ‘Cherry’, ‘Bob’, ‘Sam’]


In-built function: pop()


Removes the element at the specified position

myList =[‘john’, ‘Cherry’, ‘Bob’, ‘Sam’]

value = myList.pop(0)

print(value) # Output: john 


In-built function: reverse()


Reverses the order of the list

myList =[‘john’, ‘Cherry’, ‘Bob’, ‘Sam’]

reverseList = myList.reverse()

print(reverseList) # Output: [‘Sam’, ‘Bob’, ‘Cherry’, ‘john’] 


In-built function: sort()


Sort the list item

myList =[‘john’, ‘Cherry’, ‘Bob’, ‘Sam’]

sortList = myList.sort()

print(sortList) # Output: [‘Bob’, ‘Cherry’, ‘john’, 'Sam']





Prev: Strings in Python

Next: Tuple in Python

Google+ Followers