Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Wednesday, August 31, 2016

Major difference between Python 2 and Python 3



1. Print is now became function

The print statement has been replaced with a print() function. Example :


Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

2.Unicode and Strings


In Python 2, you had to mark every single Unicode string with a u at the beginning, like u'Hello'. So, with Python 3, they fixed it. All strings are now Unicode by default and you have to mark byte sequences with b. Using Unicode is a much more common scenario so it has reduced development time for everyone that does Python 3.

If you have or want to support both, you can still mark strings with u in Python 3, though.

3. Division With Integers


One of Python’s core values is to never do anything implicitly. You shouldn’t turn a number into a string unless the programmer tells you to, for example. But Python 2 took this a bit too far. Consider this problem:

5 / 2 

For most of us, our immediate answer is 2.5, which is, of course, the right answer. But Python 2 said "oh, you only gave me integers so you must want an integer back" and happily returned 2. Well, yes, I did give you integers, but I’d rather have a correct answer than an answer that matches my data types.

Again, Python 3 fixed this. Python 3 will give 2.5 as the answer to that question. In fact, it gives a float (a number with a decimal in it) to every division operation. But, if you are expecting an integer (round value), then probably you can use double division operator (//) , which will return integer value:

5//2  will print 2


4. input() is Now Safe to Use


In Python 2, there was a raw_input() function and an input() function. raw_input() was the one you always wanted to use. input() was a great way to have your code do things you didn’t want it to. The reason for this is that input() evaluated whatever came in. So good users would send in 123 and Python, trying to be helpful, would make that into an integer instead of a string. Bad users would send in little, or not so little, bits of Python which would then be evaluated, or run. Cue your software doing things you didn’t ask it to do.

In Python 3, raw_input() is replaced with input(), which no longer evaluates the data it receives. You always get back a string.

5. Performance


The net result of the 3.0 generalizations is that Python 3.0 runs the pystone benchmark around 10% slower than Python 2.5. Most likely the biggest cause is the removal of special-casing for small integers. There’s room for improvement, but it will happen after 3.0 is released!


Saturday, August 27, 2016

Running Python script on Unix



So far we have learned about basics of Python including how to print anything in Python and its major data types. We have also seen different types of loop and function declarations. In this article, we will write small function and save it to a file (.py) and then we will execute it from terminal

Writing first Python script  

We will write a function, which will accept user input and validate, if user has entered incorrect input. It will keep on prompting for user input until it gets correct input.


def getFloatFromUser(prompt):
    while True:
        number = raw_input(prompt)
        try:
            number = float(number)
        except:
            print 'That is not a float, please try again.'
            continue
        # everything OK
        return number

myFloat = getFloatFromUser('Please enter a float: ')
print myFloat


We have saved above code to my_first_python_script.py file.


Running Python script  

We have saved our python file to our tutorial folder. Now, we will open the terminal and run this file, but before that, we need to change file to executable.
 $chmod +x /Desktop/MyTutorial/Python/my_first_python_script.py
Once, you have changed file to executable , you need to type following command to execute your python script :
 $python /Desktop/MyTutorial/Python/my_first_python_script.py

The script will start executing and expects valid input, please refer below snippet : 


$ python /Desktop/MyTutorial/Python/my_first_python_script.py
Please enter a float: tt
That is not a float, please try again.
Please enter a float: las
That is not a float, please try again.
Please enter a float: sdf
That is not a float, please try again.
Please enter a float: 90
90.0

Until user enters valid input, it will keep on prompting for valid input. Once, user enters valid input, it will display it to screen and come out from the loop. 

That's it !!

Tuesday, August 16, 2016

Mutable & Immutable data types in Python



In my previous article, I have already explained :

  1. Installation of Python
  2. Python Syntax
  3. Printing “Hello Python”
  4. Different data types and their declarations
  5. Function, Loop and Conditional Controls 

I have also mentioned that, String Number and Tuple are Immutable whereas List and Dictionary are Mutable in nature. But, can we prove it ? Yes, of course, Python has a function id(), which returns the memory id of a variable. This we can use to understand Python data types and their memory allocations.


Now, we will declare a variable for each below mentioned data types and then we will change it’s value to something else and validate its object id.

String (Immutable)


>>> name="AppTech Solution"
>>> print name
AppTech Solution
>>> id(name)
4503631496        #object id
>>> name="Welcome to AppTech Solution"
>>> print name
Welcome to AppTech Solution
>>> id(name)
4503615728        #object id changed
>>> 

Number (Immutable)


>>> emp_id=12
>>> print emp_id
12
>>> id(emp_id)
140410018119968      #object id
>>> emp_id=20
>>> print emp_id
20
>>> id(emp_id)
140410018119776      #object id changed
>>> 

List (Mutable)

The values of List are enclosed with curly bracket []. We expects object id should remain same, even we manipulate its content.


>>> var_list=[3,5,"Ram"]
>>> print var_list
[3, 5, 'Ram']
>>> id(var_list)
4503638456           #object id
>>> var_list[0]=30   #changing value for existing index
>>> print var_list
[30, 5, 'Ram']
>>> id(var_list)
4503638456           # object id remains same
>>>

Tuple (Immutable)

Similar to List, but values are enclosed with small bracket (). We expects object id should change whenever value gets changed



>>> var_tup=("alpha",34,"beta")
>>> print var_tup
('alpha', 34, 'beta')
>>> id(var_tup)
4503411760                                #object id
>>> var_tup=(“alpha",34,"beta","gamma")   #assigning new value
>>> print var_tup
('alpha', 34, 'beta', 'gamma')
>>> id(var_tup)
4503316888                                #object id changed
>>> 

Dictionary (Mutable)

They are similar to hash-map and values are enclosed with curly bracket {}. We expects object id should remain same, even we manipulate its content.


>>> laptop={}
>>> laptop["hp"]=30000
>>> laptop["dell"]=35000
>>> print laptop
{'hp': 30000, 'dell': 35000}
>>> id(laptop)
4503636800                       #object id
>>> laptop[“dell"]=45000         #changing value for existing key
>>>print laptop
{'hp': 30000, 'dell': 45000}
>>> id(laptop)
4503636800                       #object id remains same
>>> laptop[“acer"]=15000         #adding new value
>>> print laptop
{'acer': 15000, 'hp': 30000, 'dell': 45000}
>>> id(laptop)
4503636800                       #object id remains same
>>>



You could see that, for String, Number and Tuple object id gets changed when we changes its value, but this wasn’t the case for List and Dictionary. This means every time, when we change values for String, Number and Tuple, then its actually creating a new object for it and assigning value to it.



Friday, August 12, 2016

Python Basics for absolute Beginners




1. What is Python Programming

It is a widely used high-level, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and allows programmers to express concepts in fewer lines of code when comparing other languages such as C++ or Java.

2. How to Use it

Download latest version of Python bundle from https://www.python.org/. Installation steps are pretty simple, you need to follow the steps while installation with the default settings.

Type “python”  on your terminal, to verify your python installation. This will print Python version along with your machine details.

Python 2.7.10 (default, Oct 23 2015, 19:19:21) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

Now, you can start your python coding

3. Python Syntax 

To start any block, use : instead of { and indented with same number of space to indicate code for the same block. You will see, when we go through function declaration.

4. Say Hello to Python

To print anything on terminal you need to type “print” and space and your message. Example: 
print “Hello Python”

>>> print "Hello Python”   
Hello Python
>>> 

print became function in Python version 3.x. So, you need to use 

>>> print(“Hello Python”)   
Hello Python
>>>


5. Data Types in Python

  1. String
  2. Number
  3. List
  4. Tuple
  5. Dictionary


6. Variable Declaration and Naming Conventions

A valid variable declaration would be lowercase with underscore(_) between the words and shouldn’t start with number.Example :

my_var = 4  <— valid
8my_var = 5  <— invalid

6.1. How to declare String (Immutable)

name =“AppTech Solution”
str_with_quote=“AppTech Solution’s Tutorial”
str_multi_line=“”” AppTech Solution
Welcomes You”””

6.2. How to declare Number (Immutable)

my_var = 4

6.3. How to declare List (Mutable)

It holds sequences and values are enclosed with square bracket [].

>>> a=[3,5,"Ram"]
>>> print a
[3, 5, 'Ram']
>>> 

6.4. How to declare Tuple (Immutable)

Similar to List, but values are enclosed with small bracket ().

>>> a=("alpha",34,"beta")
>>> print a
('alpha', 34, 'beta')
>>> 

6.5. How to declare Dictionary (Mutable)

Are similar to hash-map and values are enclosed with curly bracket {}.

>>> laptop={}
>>> laptop["hp"]=30000
>>> laptop["dell"]=20000
>>> laptop["acer"]=25000
>>> print laptop["dell"]
20000
>>> print laptop
{'acer': 25000, 'hp': 30000, 'dell': 20000}
>>> 


7. Functions

Function name should not start with numbers and use underscore(_) between the words. Basic syntax is

def function_name(arg):
    body with indentation
    more code here
    some more line
    return    

Example:

def addition(num):
    return num+2

my_num= addition(5)


8. Loops and Condition Controls

The syntax of a while loop in Python programming language is 

while expression :
      statement(s)

Example:

>>> a=5
>>> while(a>1): 
...    print a
...    a-=1
... 
5
4
3
2
>>>

The syntax of a for loop in Python programming language is 

for iter in sequence :
          statement(s)

Example:

>>> for letter in 'Python':     # First Example
...    print 'Current Letter :', letter
... 
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n