Friday, July 31, 2015

Python Basics - 005 - Variables

Previous chapter: IDEs Next Chapter: Math Operations



Variables in Python

Let's find out about variables in Python:

Creating variables in python doesn't require any data type specification and can be used wherever needed and the variable is created.

Variable name conventions

Variables in python are commonly written in lowercase with an underscore separating multiword variable names[1], however it is upto you to follow any convention that is comfortable. CamelCase is the most commonly used in other languages, you can use fully upper case or any other convention. However it is best to stick to one convention throughout the project to have a consistent style. Because of my familiarity with java, I am going to choose CamelCase styling for naming variables and functions.

Variable cannot start with a number or a special character, however it can contain numbers in any other place of the variable name.

Try and copy the below code into a new python file in PyCharm and execute it.


exampleVariable = 5  # CamelCase convention which I am going to use.
print('exampleVariable=', exampleVariable)

# a variable can be quickly assigned as a result of an operation
exampleVariable1 = 5+2
print('exampleVariable1=', exampleVariable1)

# a variable can be assigned as a return value of a function
exampleVariable2 = print("Hello World!")
print('exampleVariable2=', exampleVariable2)

x, y = (1, 2)  # feature called packing, assigning variables in bulk.
print('x=', x)
print('y=', y)

Packing is a feature in python where by you can assign multiple variables' values in a single line. It can be used in cases of co-ordinates as demonstrated by the above example.

You can create a variable as a return value of a function or a resultant value of an operation. This is similar to Java

As expected the output will be


exampleVariable= 5
exampleVariable1= 7
Hello World!
exampleVariable2= None
x= 1
y= 2

None is the value of exampleVariable2 because the print() function does not return any value, it is equal to null in Java.


P.S: all the code used in this tutorial is available in github


Reference:
  1. http://legacy.python.org/dev/peps/pep-0008/



Previous chapter: IDEs Next Chapter: Math Operations

Python Basics - 004 - PyCharm and other IDEs

Previous chapter: Data Types Next Chapter: Variables



004 - PyCharm and other IDEs

Using notepad and then fumbling around the command line are all necessary skills to call yourself a programmer, however once you know how to do them, you don't have to always do it the same way. We can move on to IDEs which will make our life a lot easier.

Python has a lot of IDEs[1][2] and one of my favourites is PyCharm.

For beginners PyCharm I feel is the easiest of all IDEs and you can get you code running in a very short time.

Downloads are available here: https://www.jetbrains.com/pycharm/download/ and community edition is free and open source. The professional edition is not needed in this early stage. The professional edition license is also free if you're a student or operating a open source project.

It is a pretty straightforward installation and the installer is available for windows, mac and linux operating systems.

Here's the quick start guide[3] for anything you might need to configure PyCharm.

You can also get a lot of demos and videos in PyCharm website[4].

Working with PyCharm:

You can open a project or create just a Python file using File -> new.

Once created, you can go ahead and type the same sample code we discussed in the previous post.

Use the play button to run the script.

The output will be displayed in the bottom console window area.

That's pretty much all you need to start coding in PyCharm.


References:

  1. https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
  2. http://pedrokroger.net/choosing-best-python-ide/
  3. https://www.jetbrains.com/pycharm/quickstart/
  4. https://www.jetbrains.com/pycharm/documentation/



Previous chapter: Data Types Next Chapter: Variables

Python Basics - 003 - Print function and Hello World!

Previous chapter: Setting up Python Next Chapter: Data Types



Let's begin with a simple program:

Create a text file and save it as firstProgram.py, put in the following code

print("Hello World!")

save the file and then open the command line and navigate to the folder where the firstProgram.py file is and execute the command


>>>python3 firstProgram.py
Hello World!

Our first program is complete, you may note that the syntax for a function is function name with braces, similar to Java. print() is a built-in function and built-in functions don't need any import statements, they are part of the core python.

Edit the file again and let's add some more code to showcase how strings act.


# First Program
print("Hello World!")
print('We\'re coming home!')
print('Hi '+'there!')
print('Hi', 'buddy')
print('Hi', 5)

Execute the above statements in the file and the output will be


Hello World!
We're coming home
Hi there!
Hi buddy
Hi 5

Now from the above lines we can observe that

  • Anything followed by a # will be ignored and # acts as a single line comment, multiline comments: ''' ending with '''
  • Strings can be enclosed in both single and double quotes, just like javascript and the escape character is backslash "\"
  • String concatenation works pretty much as expected with a + sign in-between,
  • however the print function accepts many strings and other data types which can be appended if given comma separated but the print function not only appends the string but also adds a space between them.
  • The print function also adds a newline after the string is printed.

Whole list of inbuilt functions like print() are listed in the documentation here: https://docs.python.org/3.5/library/functions.html but we will rarely use most of them.


Previous chapter: Setting up Python Next Chapter: Data Types

Python Basics - 002 - Setting up Python

Previous chapter: Introduction Next Chapter: Hello World!



Setting up Python

Before moving any further let's install and setup Python in our system.

Python comes in two flavours, 2.x and 3.x. The original 2.x series was re-written and 3.x was born. Python 3 was the first release which not backward compatible and forced a lot of syntax changes and refactoring on the existing users, so most of the features in 3.x was ported back to 2.x series and they're almost indistinguishable except for some syntax differences. 2.x is still more popular than 3.x series, however to stay ahead of the times, we'll go for learning Python 3.

As of now the latest version of Python 3 is 3.4. To install Python 3.4, go to https://www.python.org/downloads/

Installation instructions are also available in the same page and it is pretty straightforward. Python comes preinstalled with most operating systems but it is usually 2.7, So we'll go ahead and install Python 3.4.

Go to your terminal/Command prompt and type: python and press enter to see if Python is installed and is in path. Since we're installing Python 3, we have to use python3 as the command in the terminal.


$ python3
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

Executing python3 will launch the python interpreter and you can interactively type python commands and get output printed on the console.

Unlike java or C, the Python interpreter doesn't require you to create a file, compile and execute it. You can straight away start typing and get your results in the command window.

The interpreter interface is just for debugging and some initial or standalone function or module which you may want to incorporate into a codebase or a program. The interpreter is what runs the Python script so it is needed. However we will write the code in *.py files and execute them using the interpreter command, which is python3



References:

  1. https://www.youtube.com/watch?v=oVp1vrfL_w4
  2. https://wiki.python.org/moin/Python2orPython3
  3. https://docs.python.org/3/whatsnew/3.0.html
  4. https://www.python.org/downloads/



Previous chapter: Introduction Next Chapter: Hello World!

Wednesday, July 29, 2015

Python Basics - 001: Introduction to python and why we might wanna learn it.

Previous chapter: Index Next Chapter: Setting up Python


I really need a hobby and I've been trying to decide on something and I got to thinking: How about learning a new language? I tried Spanish first but that didn't happen. We'll skip that cause that's not a happy story. I work with Java everyday and I'd like to do something different when I'm free.

For reasons I don't remember I've heard people say that Python is a lot simpler and a whole lot powerful than Java and that I should take a look at it for my new projects. So let's evaluate it and see how good it really is! The goal is to learn basics and write some tangible program that you can use in reality, we'll figure out what it is as we learn

Okay, let's start with the basics.

What is Python?

Python is a high level interpreted programming language which supports almost all programming methods such as Object oriented, functional, structured, aspect-oriented, etc., I read the wikipedia page of Python and couldn't find a clear area where Python excels. Then realised that is Python's strength. It is a jack of all trades and if the programmer is good enough it can be a master of them all.

What I know is Java and JavaScript and about databases. I know a little C from when I took a programming paper in college, So I'll approach Python by comparing the concepts from Python to what I already know to make it a little simpler. Python as I understand it is very simple to write and has to be easy to read than most other languages.

About Python Syntax

  • It uses indentation for code grouping, no more curly braces
  • There is no semi-colons at the end of every statement, finally!
  • It's dynamically typed, no declaration of variables. You can directly assign values to variable names and the type is derived from that much like JavaScript.
  • It's a strongly typed language like Java, so we have to manually cast items and adjust behaviour, it wouldn't automatically convert or cast.
  • It's also is based on duck-typing, which means objects from different classes can be interchanged if they have the desired method in both.
  • Python is also very extensible, like Java, there are many libraries which can be used to extend the capabilities of Python's core.

The code written in python should be easily readable without much clutter. So it will be a lot better to understand old code unlike languages like Objective-C or C++.

Let's discuss more about Python after I've learnt how to install it and run some basic stuff.




Previous chapter: Index Next Chapter: Setting up Python