Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

The Guide to DeepLearning with Tensorflow and Keras - The Beginning


Learn how to build a neural network and how to train, evaluate and optimize it with TensorFlow.


This is a part-by-part course which we will cover from basics to implementing models in productions.


Today’s TensorFlow tutorial for beginners will introduce you to performing deep learning in an interactive way:



You’ll first learn more about tensors;


Then, the tutorial you’ll briefly go over some of the ways that you can install TensorFlow on your system so that you’re able to get started and load data in your workspace;


After this, you’ll go over some of the TensorFlow basics: you’ll see how you can easily get started with simple computations.





What is TensorFlow?


TensorFlow is a popular open source library that's used for implementing machine learning and deep learning.


It was initially built at Google for internal consumption and was released publicly on November 9, 2015.


Since then, TensorFlow has been extensively used to develop machine learning and deep learning models in several business domains.




To use TensorFlow in our projects, we need to learn how to program using the TensorFlow API. 



TensorFlow has multiple APIs that can be used to interact with the library. The TensorFlow APIs are divided into two levels:




Low-level API: The API known as TensorFlow core provides fine-grained lower level functionality. Because of this, this low-level API offers complete control while being used on models. We will cover TensorFlow core in this post.




High-level API: These APIs provide high-level functionalities that have been built on TensorFlow core and are comparatively easier to learn and implement. Some high-level APIs include Estimators, Keras, TFLearn, TFSlim, and Sonnet.



The TensorFlow core


The TensorFlow core is the lower-level API on which the higher-level TensorFlow modules are built. In this section, 



We will go over a quick overview of TensorFlow core and learn about the basic elements of TensorFlow.



Here we go! Let’s begin the fundamentals of Tensorflow.🙏🙏



Setting up Tensorflow.

TensorFlow is tested and supported on the following 64-bit systems:




  • Ubuntu 16.04 or later
  • Windows 7 or later
  • macOS 10.12.6 (Sierra) or later (no GPU support)
  • Raspbian 9.0 or later


##### Current release for CPU-only
pip install tensorflow

##### Nightly build for CPU-only (unstable)
pip install tf-nightly

##### GPU package for CUDA-enabled GPU cards
pip install tensorflow-gpu

##### Nightly build with GPU support (unstable)
pip install tf-nightly-gpu

Lets Spice things with Hello World! Example!


import tensorflow as tf
hello = tf.constant("hello wold")
sess = tf.Session()
print(sess.run(hello))
print('--------------')
--------------------
b'hello wold'
--------------

We will check line by line what we have written and how we implemented out Hello World! example

Tensorflow fundamentals.


First, we’re going to take a look at the tensor object type. Then we’ll have a graphical understanding of TensorFlow to define computations. Finally,


we’ll run the graphs with sessions, showing how to substitute intermediate values.



Tensors



Tensors are the basic components in TensorFlow. A tensor is a multidimensional collection of data elements.




It is generally identified by shape, type, and rank. Rank refers to the number of dimensions of a tensor, while shape refers to the size of each dimension.




You may have seen several examples of tensors before, such as in a zero-dimensional collection (also known as a scalar), a one-dimensional collection (also known as a vector), and a two-dimensional collection (also known as a matrix).






A scalar value is a tensor of rank 0 and shape []. A vector, or a one-dimensional array, is a tensor of rank 1 and shape [number_of_columns] or [number_of_rows]


Let's create some constants with the following code:




const1=tf.constant(34,name='x1')
const2=tf.constant(59.0,name='y1')
const3=tf.constant(32.0,dtype=tf.float16,name='z1')

print('const1 (x): ',const1)
print('const2 (y): ',const2)
print('const3 (z): ',const3)




Let's take a look at the preceding code in detail:




  • The first line of code defines a constant tensor, const1, stores a value of 34, and names it x1.
  • The second line of code defines a constant tensor, const2, stores a value of 59.0, and names it y1.
  • The third line of code defines the data type as tf.float16 for const3. Use the dtype parameter or place the data type as the second argument to denote the data type. 

Example:


hello = tf.constant("Hello ")
world = tf.constant("World")
type(hello)
print(hello)


with tf.Session() as sess:
result = sess.run(hello+world)


print(result)

--------------------
tensorflow.python.framework.ops.Tensor
Tensor("Const_1:0", shape=(), dtype=string)
b'Hello World'


Constants


The constant valued tensors are created using the tf.constant() function, and has the following definition:


Syntax:





tf.constant(
value,
dtype=None,
shape=None,
name='const_name',
verify_shape=False
)


Let's create some constants with the following code:





a = tf.constant(10)
b = tf.constant(20)

const1=tf.constant(34,name='x1')
const2=tf.constant(59.0,name='y1')
const3=tf.constant(32.0,dtype=tf.float16,name='z1')

print(a)
print(b)
print('const1 (x): ',const1)
print('const2 (y): ',const2)
print('const3 (z): ',const3)
------------------------------
Tensor("Const_1:0", shape=(), dtype=int32)
Tensor("Const_2:0", shape=(), dtype=int32)
const1 (x): Tensor("x:0", shape=(), dtype=int32)
const2 (y): Tensor("y:0", shape=(), dtype=float32)
const3 (z): Tensor("z:0", shape=(), dtype=float16)



Operations


How can we do addition/multiplication in tensorflow ?.




The TensorFlow library contains several built-in operations that can be applied on tensors. 




An operation node can be defined by passing input values and saving the output in another tensor. To understand this better, let's define two operations.



a = tf.constant(10)
b = tf.constant(20)
type(a)

with tf.Session() as sess:
result = sess.run(a+b)
mul = sess.run(tf.multiply(a,b))

print(result)
print(mul)
------------------
30
200





Some of the built-in operations of TensorFlow include arithmetic operations, math functions, and complex number operations.




Working with Matrices in Tensorflow.



We can easily create n*n matrices in tensorflow using the in-built functions. We' ll dicrectly dive into the example to understand the code.




const = tf.constant(10)



## Building a 4*4 Matix with all element as 10
## We are going to use fill() to fill the matrix with default value
## fill((row,col),def_value) can be used to fill values.
fill_mat = tf.fill((4,4),10)


## Creating a zero 4*4 Matrix
## Default tr.zeros() to create a zero matrix
myzeros = tf.zeros((4,4))


## Creating one matrices
## Using tf.one() method to create one matrix

myones = tf.ones((4,4))

## Creating a random normalized matrix.
## Using random_normal Outputs random values from a normal distribution.
## mean: A 0-D Tensor or Python value of type dtype. stddev: A 0-D Tensor or Python value of type dtype.

myrand = tf.random_normal((4,4),mean =0,stddev =1.0)

myrandu = tf.random_uniform((4,4),minval=0,maxval=1)

my_ops = [const,fill_mat,myzeros,myones,myrand,myrandu]

sess = tf.InteractiveSession()


for op in my_ops:
print(sess.run(op))
print("\n")

--------------------------------------------------
10


[[10 10 10 10]
[10 10 10 10]
[10 10 10 10]
[10 10 10 10]]


[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]


[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]


[[-1.1485276 0.6817215 1.6923033 1.0417686 ]
[ 0.75727195 -0.6906906 1.382049 0.26310864]
[-1.3289255 -2.0204604 0.9086128 -1.6753776 ]
[ 0.83860254 0.8221855 -0.01571688 0.33962643]]


[[0.4758848 0.02705026 0.45411873 0.9472964 ]
[0.03372979 0.04275322 0.51311064 0.1727488 ]
[0.38706803 0.29606903 0.17789984 0.97908235]
[0.2033397 0.9660599 0.6367506 0.9244758 ]]



Placeholders


While constants store the value at the time of defining the tensor, placeholders allow you to create empty tensors so that the values can be provided at runtime. 




The TensorFlow library provides the tf.placeholder() function with the following signature to create placeholders:


Syntax:




tf.placeholder(
  dtype,
  shape=None,
  name=None
  )

Lets see with an example




p1 = tf.placeholder(tf.float32)
p2 = tf.placeholder(tf.float32)
print('p1 : ', p1)
print('p2 : ', p2)

--------------------
p1 :  Tensor("Placeholder:0", dtype=float32)
p2 :  Tensor("Placeholder_1:0", dtype=float32)


Computation graph/Tensorflow Graph


A computation graph is the basic unit of computation in TensorFlow. A computation graph consists of nodes and edges. Each node represents an instance of tf.Operation,


while each edge represents an instance of tf.Tensor that gets transferred between the nodes.


A model in TensorFlow contains a computation graph. First, you must create the graph with the nodes representing variables, constants, placeholders, and operations, and then provide the graph to the TensorFlow execution engine.




 The TensorFlow execution engine finds the first set of nodes that it can execute. The execution of these nodes starts the execution of the nodes that follow the sequence of the computation graph.


Thus, TensorFlow-based programs are made up of performing two types of activities on computation graphs:



  • Defining the computation graph
  • Executing the computation graph



A TensorFlow program starts execution with a default graph. Unless another graph is explicitly specified, a new node gets implicitly added to the default graph. Explicit access to the default graph can be obtained using the following command:




graph = tf.get_default_graph()




n1 = tf.constant(1)
n2 = tf.constant(2)
n3 =n1+n2
with tf.Session() as sess:
    result = sess.run(n3)

result
print(tf.get_default_graph())
g =tf.Graph()
print(g)
graph_one = tf.get_default_graph()
print(graph_one)
graph_two = tf.Graph()
with graph_two.as_default():
    print(graph_two is tf.get_default_graph())
--------------------------------------

<tensorflow.python.framework.ops.Graph object at 0x0000022C46285CF8>
<tensorflow.python.framework.ops.Graph object at 0x0000022C47F8D390>
<tensorflow.python.framework.ops.Graph object at 0x0000022C46285CF8>

True
`


Here are the advantages of organizing the computations as a graph,




  • Parallelism. By using explicit edges to represent dependencies between operations, it is easy for the system to identify operations that can execute in parallel.
  • Distributed execution. By using explicit edges to represent the values that flow between operations, it is possible for TensorFlow to partition your program across multiple devices (CPUs, GPUs, and TPUs) attached to different machines.
  • TensorFlow inserts the necessary communication and coordination between devices.
  • Compilation. TensorFlow’s XLA compiler can use the information in your dataflow graph to generate faster code, for example, by fusing together adjacent operations.


Session


We have seen in all the earlier example of running our tensorflow graph into a tensorflow session.



TensorFlow uses tf.Session class to represent a connection between the client program---typically a Python program, although a similar interface is available in other languages---and the C++ runtime. 



A tf.Session object provides access to devices in the local machine, and remote devices using the distributed TensorFlow runtime. It also caches information about your tf.Graph so that you can efficiently run the same computation multiple times.


Syntax:


# Creating a tf.Session
If you are using the low-level TensorFlow API, you can create a tf.Session for the current default graph as follows:

# Create a default in-process session.
with tf.Session() as sess:
  # ...

# Create a remote session.
with tf.Session("grpc://example.org:2222"):
  # ...


Since a tf.Session owns physical resources (such as GPUs and network connections), it is typically used as a context manager (in a with block) that automatically closes the session 



when you exit the block. It is also possible to create a session without using a with a block, but you should explicitly call tf.Session.close when you are finished with it to free the resources.


That's all for the starting I hope you can start practicing Tensorflow along with me and we can deep dive and start exploring more about it soon.



We’ll be back with more exciting discussions not just on building Deep learning models but also on building a robust infrastructure to store, consume and process data at scale.


 Till then, happy coding!💓💓

Loops in Python 3 - A Definitive Guide For Beginners

In the previous post, we got started with the python lesson which gave some basic idea about the syntax on Conditional Statements mostly If..else. We got started by declaring variables and then we proceeded to check various datatypes with Conditional Statements. In this lesson, we are going to continue with understanding conditional statements with loops(for loop and while loop) in python. This lesson is again a beginner course to help you understand the basic concept. This post will cover different types of Loops in python and its usage in details.



Prerequisite for this course

  1.  A beginner 
  2.  python installed System (IDE/Interpreter). 
  3.  Knowledge of Variables.
  4.  Knowledge of Conditional Statements(If..Else).
  5. A notepad to take notes.

Why do we use Loop?


In order to know why we use looping in programming, we will first, be aware that different programming languages have different for loops. In Python, for instance, you can iterate through all the items in a list by writing loops.

Loops are used in programming as a test to know if the arguments in a clause are true or false and then determine to do an action that may involve skipping the clause and going to the next one. There are many different types of looping. If your loop only needs a test to decide if it should keep looping or not, then a do-while fits that. If you code a do-while loop and then graft on extra statements to initialize the loop counter and to increment the loop counter, then your program would likely be clearer if you'd just written a C-style loop in the first place.




The For Loop:

In Python, you can use the “for” loop in the following manner.

for <iter> in <sequence>:
    <statements(iter)>

The “iter” represents the iterating variable. It gets assigned with the successive values from the input sequence.


The “sequence” may refer to any of the following Python objects such as a list, a tuple or a string.
Let's take a look into a simple example to understand the syntax.

a =[10,20,30,40,50,60,70,80,90,100] ### Creating List to iterate
for i in a: ### Interating the list a
    print(i) ## Printing the elements in the list a
--------------
10
20
30
40
50
60
70
80
90
100
Here’s what’s happening in this example:

  1. a is initially a list with 10 elements from 1...100. Now we need to iterate/traverse the list using for loop.
  2. We use For Statement with expr variable i which points to each value present in a.
  3. The loop keep executing until all the elements is traversed and keeps printing all the value present on the list.
  4. This continues until i becomes i>length of list. At that point, when the expression is tested, it is false, and the loop terminates. Execution would resume at the first statement following the loop body, but there isn’t one in this case.
Do we have better way if we dont want to loop the whole list?

Yes, the range () function.

it generates a list of numbers, which is generally used to iterate over with for loops. There's many use cases. Often you will want to use this when you want to perform an action X number of times, where you may or may not care about the index. Other times you may want to iterate over a list (or another iterable object), while being able to have the index available.


Range() Syntax:
range(stop) ## Takes on arguments
range(start, stop) ## Takes two arguments
range(start, stop, step) ## Takes three arguments

range(stop)
When you call range() with one argument, you will get a series of numbers that starts at 0 and includes every whole number up to, but not including, the number you have provided as the stop.

Example:

for i in range(2): ###Range(stop)
    print(i)
----------------
0

1

How does this example works:

  1. We are passing the stop variable to the range function.
  2. The loop will start from 0 and iterate till the stop variable i.e(2)
  3. The loop exits once it matches the stop arguments passed.


range(start, stop)

When you call range() with two arguments, you get to decide not only where the series of numbers stops but also where it starts, so you don’t have to start at 0 all the time. You can use range() to generate a series of numbers from A to B using a range(A, B). Let’s find out how to generate a range starting at 1.

Example:

### range is equal to 1 to n(exclusive)
for i in range(1,5):
print(i)
------------------
1
2
3
4

How does this example works:

  1. The loop start from 1 instead of the default 0 , Since we provided with the start arguments.
  2. The loop iterates till it reaches the stop arguments 5(exclusive) from the start arguments.
  3. The loop terminates on it matches the stop arguments.


range(start,stop,step)

When you call range() with three arguments, you can choose not only where the series of numbers will start and stop but also how big the difference will be between one number and the next. If you don’t provide a step, then range() will automatically behave as if the step is 1.

Example:

for i in range(3, 16, 4):
print(i)
-------------------
3
7
11
15

How does this example works:

  1. The loop start from 3 instead of the default 0 , Since we provided with the start arguments.
  2. The loop iterates till it reaches the stop arguments 16 from the start arguments.
  3. The loop terminates on it matches the stop argument.
  4. Here we have passed the step arguments which takes the step added while iterating as in this cases by 4

Can the steps in range() in python be negative or Zero ?

Yes , I Will give this as exercise for practice ,but we can have negative as steps which will be used in decrement while iterating.
But for 0 its not possible It will not allow to run the loops.You will face with "ValueError: range() arg 3 must not be zero".

You can try both the example as practice.

Practice Example to understand the earlier discussed topics.

Example 1: Checking if the range of number is divisible by 3.

## Checking if num is divisible by 3

## range 100 includes 0..100
## It will check for all number in the range and if its reminder == 0 prints the number
for i in range(20):
    if i%3==0:
        print(i)
------------------------
0
3
6
9
12
15
18

Example 2 : A little bit tricky example of printing patterns.

## Printing list in pattern
# 10 is the total number to print
for num in range(10):
for i in range(num):
print (num, end=" ") #print number
# new line after each row to display pattern correctly
print("\n")
--------------------------------------
1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

6 6 6 6 6 6

7 7 7 7 7 7 7

8 8 8 8 8 8 8 8

9 9 9 9 9 9 9 9 9

The next topic which we are going to see is in loops , The While loop.

While Loop


Syntax

while :
<statements>


When a while loop is encountered, is first evaluated in Boolean context. If it is true, the loop body is executed. Then is checked again, and if still true, the body is executed again. This continues until becomes false, at which point program execution proceeds to the first statement beyond the loop body.


Lets take a example to understand the Syntax:

n = 0
while n < 5:
    print(n)
    n += 1
------------
0
1
2
3
4

Here’s what’s happening in this example:

  1. n is initially starts from 0, The loop starts and since n<5 It executes the print statement and increment the n values.
  2. It goes back to Check if the value is greater than 5 after incrementing.
  3. Its goes on until the n is greater than 5 and the expression tested for false and gets terminated.
  4. Note that the controlling expression of the while loop is tested first, before anything else happens. If it’s false to start with, the loop body will never be executed at all.


Bonus Example for better understanding

count = 0
while count < 5:
   print(count, " is  less than 5")
   count = count + 1
else:
   print(count, " is not less than 5")
--------------------------------
0  is  less than 5
1  is  less than 5
2  is  less than 5
3  is  less than 5
4  is  less than 5
5  is not less than 5



Break and Continue statements

In each example you have seen so far, the entire body of the while loop is executed on each iteration. Python provides two keywords that terminate a loop iteration prematurely:

break immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body.

continue immediately terminates the current loop iteration. Execution jumps to the top of the loop, and the controlling expression is re-evaluated to determine whether the loop will execute again or terminate.

We will straight jump into example to understand it better but using For loop.

for val in "NintyZeros":
    if val == "Z":
        break
    print(val)

print("The end")
------------------
N
i
n
t
y
The end

Lets see whats happening in the example:


  1.  The For loops takes each character from String "NintyZeros" into val.
  2.  We are using conditional statements (if) to check if it matches with Character 'Z'.
  3.  It keeps on printing until it matches with the character.
  4.  Once the match is found it executes the break statements and exit the loop.



for val in "NintyZeros":
    if val == "Z":
        continue
    print(val)

print("The end")
-----------------------
N
i
n
t
y
e
r
o
s
The end

Lets see whats happening in the example:

  •  The For loops takes each character from String "NintyZeros" into val.
  •  We are using conditional statements (if) to check if it matches with Character 'Z'.
  •  It keeps on printing until it matches with the character.
  •   Once the match is found it skips the continue statements and continue the loop till it reaches end of String.


The else with While:

Python allows an optional else clause at the end of a while loop. This is a unique feature of Python, not found in most other programming languages. The syntax is shown below:

Syntax:

while <condtion>:
    <statement>
else:
    <additional_statement>

#Example:
 

A = [10,20,30,40]
B= 50

i=0
while i<len(A):
    if A[i] == B:
        print(B,"Found")
        break
    i+=1
else:
    print(B,"Not found")
----------------------
50 Not found

In the above example:

  1.      The while loop start iterating the list A until it reaches the length of A.
  2.      It verifies if the value of variable B matches with any of the element in list A.
  3.      if it matches breaks the loop and prints "Found"
  4.      Once the loop reaches the length of the list it goes to Else statement to print "Not found".

Practice Example:

Check if the number is prime or not.

# Python program to check if the input number is prime or not


num = 520
#num = 37
# take input from the user
# num = int(input("Enter a number: "))

# prime numbers are greater than 1
if num > 1:
   # check for factors
   for i in range(2,num):
       if (num % i) == 0:
           print(num,"is not a prime number")
           break
   else:
       print(num,"is a prime number")
     
# if input number is less than
# or equal to 1, it is not prime
else:
   print(num,"is not a prime number")



A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) since, 2 x 3 = 6.

In this program, variable num is checked if it's prime or not. Numbers less than or equal to 1 are not prime numbers. Hence, we only proceed if the num is greater than 1.

We check if num is exactly divisible by any number from 2 to num - 1. If we find a factor in that range, the number is not prime. Else the number is prime.

We can decrease the range of numbers where we look for factors.

In the above program, our search range is from 2 to num - 1.
We could have used the range, [2, num / 2] or [2, num ** 0.5]. The later range is based on the fact that a composite number must have a factor less than square root of that number; otherwise the number is prime.

That''s the end of  topic on loops in python .Hope it make sense of writing such a deep and long post.

Happy Coding!👍

Variables and Types in Python - A Comprehensive Beginners Guide

In the previous post, we got started with the python lesson which gave some basic idea about the syntax. We got started by writing a simple "Hello World program".In this lesson, we are going to get started with understanding variables in python. This lesson is again a beginner course to help you understand the basic concept. This post will cover different types of variables with syntax and deep dive into various type os variables like global & local variables.



Prerequisite for this course

  1. A beginner
  2. python installed System (IDE/Interpreter).
  3. A notepad to take notes

What are actually variables?

In computer science, a variable is a value in a program that can change. It does not have to be a number — it can be a string (text value), a date, an amount of money, an object such as a picture, or simply null (which means it has no content). The value that is stored in a variable can change what happens when the program is run. Because of this, variables are commonly used to store input and output values.



What are the variables in python?


Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.



Basic Syntax


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.


Example:

count = 10   ### An integer value 10 assigned to count
name = "NintyZeros" ###A String value "NintyZeros" assigned to name
height = 2.8 ## A float type variables assiged
#Printing assigned variables
print("-"*30)
print("count :", count)
print("Name :", name)
print("Height :",height)


Can we do multiple assigment ?
Yes, that's the expected behavior. a, b and c are all set as labels for the same name. If you want three different value, you need to assign them individually.
In python, everything is an object, also "simple" variables types (int, float, etc..).
When you changes a variable value, you actually changes it's pointer, and if you compares between two variables it's compares their pointers. (To be clear, pointer is the address in physical computer memory where a variable is stored).
As a result, when you changes an inner variable value, you changes it's value in the memory and it's affects all the variables that point to this address.
For your example, when you do:
a = b = 5 This means that a and b points to the same address in memory that contains the value 5, but when you do:
a = 6 It's not affect b because a is now points to another memory location that contains 6 and b still points to the memory address that contains 5.
But, when you do:
a = b = [1,2,3] a and b, again, points to the same location but the difference is that if you change the one of the list values:
a[0] = 2 It's changes the value of the memory that a is points on, but a is still points to the same address as b, and as a result, b changes as well.


Example:
a=b=c=1; ###Yes,of course we can bro!
print("a:", a," b :" , b," c : " ,c)
-------------------------------------
a: 1  b : 1  c :  1

Local vs Global Variables in python


Global variables are the one that are defined and declared outside a function and we need to use them inside a function.


Consider the below example:


x = 0 ###Global Scope
def somefunction():
    x=1  ####Local variable
    print(x)
   
somefunction()  ###X will be overwritten with local scope 
print(x) ###Calling the Global scope value

#---------------------------
1 0

If a variable with same name is defined inside the scope of function as well then it will print the value given inside the function only and not the global value.


To make the above program work, we need to use “global” keyword. We only need to use global keyword in a function if we want to do assignments / change them. global is not needed for printing and accessing. Why? Python “assumes” that we want a local variable due to the assignment to s inside of f(), so the first print statement throws this error message("undefined: Error: local variable 'x' referenced before assignment"). Any variable which is changed or created inside of a function is local, if it hasn’t been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword “global”, as can be seen in the following example:



 y = 0
def somefunction():
    global y####global variable ####But not the great way to use it
    y=1
    print(y)
   
somefunction()   

print(y)
-------------------------------
1 1



We have created a reference to global variable what if i want to delete and re-create a new.

How to delete every reference of an object in Python?
You can also delete the reference to a number object by using the del statement.


An object will be deleted as soon as all references to that object get removed. Python keeps a reference count internally - to illustrate :


del x,y
##  Reference gets deleted
print(x)
#print(y)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-47-abdfb9bbb238> in <module>()
1 ## Reference gets deleted
----> 2 print(x)

NameError: name 'x' is not defined



The Python garbage collector will delete the object eventually. There is no guarantee in the CPython standard that the object will be deleted immediately, or at any time before the program ends - it depends how often the GC runs - how quickly your program runs, and whether there are circular references - (if two objects refer to each other, even if neither of the objects can be accessed through any names, the ref count of each object will never reach 0). Don’t rely on the ``__del__`` method to be triggered - it might be, but then again it might not.


Python Data Types

This guide is an overview of Python Data Types.

Overview

Python has five standard Data Types:
  • Numbers(int)
  • String(str)
  • List(list)
  • Tuple(tuple)
  • Dictionary(dict)
Python sets the variable type based on the value that is assigned to it. Unlike more riggers languages, Python will change the variable type if the variable value is set to another value. For example:

Numbers(int)
var1 = 1
var2 = 10
type(var1)

Most of the time Python will do variable conversion automatically. You can also use Python conversion functions (int(), long(), float(), complex()) to convert data from one type to another. In addition, the type function returns information about how your data is stored within a variable.

String(Str)
Create string variables by enclosing characters in quotes. Python uses single quotes ' double quotes " and triple quotes """ to denote literal strings. Only the triple quoted strings """ also will automatically continue across the end of line statement.

var1 = "Hello"
var2= "World"
print(var1+" "+var2)
type(var1)
--------------------------
Hello World
str

List(list)
Lists are a very useful variable type in Python. A list can contain a series of values. List variables are declared by using brackets [ ] following the variable name.

Lists aren’t limited to a single dimension. Although most people can’t comprehend more than three or four dimensions. You can declare multiple dimensions by separating an with commas. In the following example, the MyTable variable is a two-dimensional array :


list = [ 'Ninty', 786 , 2.23, 'Zeros', 70.2 ] ### creating a list with mixed type of datatype
print(list) ###printing the content of the list
print(list[3]) ####Fetching values from index 3
print(list*2)  ###Copying the values by 2
type(list) ###Checking the type of datatype
----------------------
['Ninty', 786, 2.23, 'Zeros', 70.2]
Zeros
['Ninty', 786, 2.23, 'Zeros', 70.2, 'Ninty', 786, 2.23, 'Zeros', 70.2]
Out[19]:
list

Tuple(tuple)
Tuples are a group of values like a list and are manipulated in similar ways. But, tuples are fixed in size once they are assigned. In Python the fixed size is considered immutable as compared to a list that is dynamic and mutable. Tuples are defined by parenthesis ().


tuple = ( 'Ninty', 786 , 2.23, 'Zeros', 70.2 ) ##Creating a tuple
print(tuple)
print(tuple[1])
print(type(tuple))
---------------------
('Ninty', 786, 2.23, 'Zeros', 70.2)
786
<class 'tuple'>

Tuple Vs List



Here are some advantages of tuples over lists:

  1. Elements to a tuple. Tuples have no append or extend method.
  2. Elements cannot be removed from a tuple.
  3. You can find elements in a tuple, since this doesn’t change the tuple.
  4. You can also use the in operator to check if an element exists in the tuple.
  5. Tuples are faster than lists. If you’re defining a constant set of values and all you’re ever going to do with it is iterate through it, use a tuple instead of a list.
  6. It makes your code safer if you “write-protect” data that does not need to be changed.
Cons:

list[2] = 100000 ###updating the index
print(list)
tuple(2) = 100000   ### Tou cannot update the tuple value
--------------------
['Ninty', 786, 100000, 'Zeros', 70.2]
  File "<ipython-input-23-423972f5a01d>", line 3
    tuple(2) = 100000   ### Tou cannot update the tuple value

SyntaxError: can't assign to function call

Dictionary(Dict)

Dictionaries in Python are lists of Key:Value pairs. This is a very powerful datatype to hold a lot of related information that can be associated through keys. The main operation of a dictionary is to extract a value based on the key name. Unlike lists, where index numbers are used, dictionaries allow the use of a key to access its members. Dictionaries can also be used to sort, iterate and compare data.
Dictionaries are created by using braces ({}) with pairs separated by a comma (,) and the key values associated with a colon(:). In Dictionaries the Key must be unique. Here is a quick example on how dictionaries might be used:

dict = {} ### creating a dict
dict['one'] = "This is one" ## Adding data to dict by key as str
dict[2]     = "This is two" ## Adding data to dict by key as int
print(dict) ##printing the dict
type(dict) ##Print the type as dict

print(dict['one']) ##Fetching value based on key
print(dict[2])
print(dict.keys()) ##Printing all the keys
print(dict.values()) ##Printing all the values
-------------------------------
{'one': 'This is one', 2: 'This is two'}
This is one
This is two
dict_keys(['one', 2])
dict_values(['This is one', 'This is two'])

Dictionaries can be more complex to understand, but they are great to store
data that is easy to access.

That’s pretty much it for this tutorial. I hope you enjoyed it!
I hope you can help me with more examples. I would also like to know if you
can share some example with usage in real algorithms with this data structures.
happy Coding !

Python Lesson 1- Hello World to Python!

Python—the popular and highly readable object-oriented language—is both powerful and relatively easy to learn. Whether you're new to programming or an experienced developer, this course can help you get started with Python. We are going to see basic Python syntax, and an example of how to construct and run a simple Python program. Learn to work with dates and times, read and write files, and retrieve and parse HTML, JSON, and XML data from the web.




Topics include:
  1. Parsing and processing HTML
  2. Intro to python(We are going to cover in this lesson)
  3. Working with variables and expressions
  4. Writing loops
  5. Using the date, time, and datetime classes
  6. Reading and writing files
  7. Fetching internet data




Install Python


This Step is covered most of the time on internet. You can find the best resource to install python on your own.



How to check the python version?




## SYS module provides access to some variables used or maintained by the interpreter(To interact with)

import sys
print(sys.version)
3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)]

The above statements prints the build number and build date.


How to print something in python ?




Print "Hello world" ### Oops...Is that correct ?
File "", line 1
Print "Hello world" ### Oops...Is that correct ?
^
SyntaxError: invalid syntax

print("Hello World!") ###Yay!

Hello World!

def main():
print("Hello World!")
main()

Hello World!

if __name__=="__main__": ###This works
main()
Hello World!





What does if name == “main”: do?

When the Python interpreter reads a source file, it executes all of the code found in it. Before executing the code, it will define a few special variables. For example, if the Python interpreter is running that module (the source file) as the main program, it sets the special name variable to have a value "main". If this file is being imported from another module, name will be set to the module's name.





# file test.py
def func():
print("func() is n test.py")

print("I am in test.py")

if __name__ == "__main__":
print("test.py is being run directly")
else:
print("test.py is being imported into another module")