Python is a cross-platform programming language, meaning, it runs on multiple platforms like Windows, Mac OS X, Linux, Unix and has even been ported to the Java and .NET virtual machines. It is free and open source.
Even though most of today’s Linux and Mac have Python preinstalled in it, the version might be out-of-date. So, it is always a good idea to install the most current version. You can download the latest version of Python and install it.
Starting The Interpreter
After installation, the python interpreter lives in the installed directory.
By default is
/usr/local/bin/pythonX.X in Linux/Unix and C:\PythonXX in Windows, where the 'X' denotes the version number. To invoke it from the shell or the command prompt we need to add this location in the search path.
Search path is a list of directories (locations) where the operating system searches for executables.
For example, in Windows command prompt, we can type
set path=%path%;c:\python33 (python33 means version 3.3, it might be different in your case) to add the location to path for that particular session.
In Mac OS we need not worry about this as the installer takes care about the search path.Now there are various ways to start Python.
1. Immediate mode
Typing
python in the command line will invoke the interpreter in immediate mode. We can directly type in Python expressions and press enter to get the output.>>>
is the Python prompt. It tells us that the interpreter is ready for our input. Try typing in
1 + 1 and press enter. We get 2 as the output. This prompt can be used as a calculator. To exit this mode type exit() or quit() and press enter.2. Script mode
This mode is used to execute Python program written in a file. Such a file is called a script. Scripts can be saved to disk for future use. Python scripts have the extension
.py, meaning that the filename ends with .py.
For example:
helloWorld.py
To execute this file in script mode we simply write
python helloWorld.py at the command prompt.3. Integrated Development Environment (IDE)
We can use any text editing software to write a Python script file.
We just need to save it with the
.py extension. But using an IDE can make our life a lot easier. IDE is a piece of software that provides useful features like code hinting, syntax highlighting and checking, file explorers etc. to the programmer for application development.
Recommended Reading: Best Python IDEs
Using an IDE can get rid of redundant tasks and significantly decrease the time required for application development.
IDLE is a graphical user interface (GUI) that can be installed along with the Python programming language and is available from the official website.
We recommend Thonny IDE for beginners. It is free and open source.
Hello World Example
Now that we have Python up and running, we can continue on to write our first Python program.
Type the following code in any text editor or an IDE and save it as
helloWorld.pyprint("Hello world!")
Now at the command window, go to the location of this file. You can use the
cd command to change directory.
To run the script, type
python helloWorld.py in the command window. We should be able to see the output as follows:Hello world!
If you are using PyScripter, there is a green arrow button on top. Press that button or press
Ctrl+F9 on your keyboard to run the program.
In this program we have used the built-in function
print(), to print out a string to the screen. String is the value inside the quotation marks, i.e. Hello world! . Now try printing out your name by modifying this program.
Congratulations! You just wrote your first program in Python.
As we can see, it was pretty easy. This is the beauty of Python programming language.
Python Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as 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.
There are 33 keywords in Python 3.3. This number can vary slightly in course of time.
All the keywords except
True, False and None are in lowercase and they must be written as it is. The list of all the keywords are given below.| False | class | finally | is | return |
| None | continue | for | lambda | try |
| True | def | from | nonlocal | while |
| and | del | global | not | with |
| as | elif | if | or | yield |
| assert | else | import | pass | |
| break | except | in | raise |
Looking at all the keywords at once and trying to figure out what they mean might be overwhelming.
If you want to have an overview, here is the complete list of all the keywords with examples.
Python Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python. It helps differentiating one entity from another.
Rules for writing identifiers
- Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). Names like
myClass,var_1andprint_this_to_screen, all are valid example. - An identifier cannot start with a digit.
1variableis invalid, butvariable1is perfectly fine. - Keywords cannot be used as identifiers.
>>> global = 1 File "<interactive input>", line 1 global = 1 ^ SyntaxError: invalid syntax - We cannot use special symbols like !, @, #, $, % etc. in our identifier.
>>> a@ = 0 File "<interactive input>", line 1 a@ = 0 ^ SyntaxError: invalid syntax - Identifier can be of any length.
Things to care about
Python is a case-sensitive language. This means,
Variable and variable are not the same. Always name identifiers that make sense.
While
c = 10 is valid. Writing count = 10 would make more sense and it would be easier to figure out what it does even when you look at your code after a long gap.
Multiple words can be separated using an underscore,
this_is_a_long_variable.
We can also use a camel-case style of writing, i.e., capitalize every first letter of the word except the initial word without any spaces. For example:
camelCaseExamplePython Statement, Indentation, and Comments
In this article, you will learn about Python statements, why indentation is important and use of comments in programming.
Python Statement
Instructions that a Python interpreter can execute are called statements. For example,
a = 1is an assignment statement. if statement, for statement, while statement etc. are other kinds of statements that will be discussed later.Multi-line statement
In Python, the end of a statement is marked by a newline character. But we can make a statement extend over multiple lines with the line continuation character (\). For example:
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
This is an explicit line continuation. In Python, line continuation is implied inside parentheses ( ), brackets [ ], and braces { }. For instance, we can implement the above multi-line statement as
a = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case with [ ] and { }. For example:
colors = ['red',
'blue',
'green']
We could also put multiple statements in a single line using semicolons, as follows
a = 1; b = 2; c = 3
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block.
Generally, four whitespaces are used for indentation and is preferred over tabs. Here is an example.
The enforcement of indentation in Python makes the code look neat and clean. This results in Python programs that look similar and consistent.
Indentation can be ignored in line continuation. But it's a good idea to always indent. It makes the code more readable. For example:
if True:
print('Hello')
a = 5
and
if True: print('Hello'); a = 5
both are valid and do the same thing. But the former style is clearer.
Incorrect indentation will result into
Python Comments
Comments are very important while writing a program. It describes what's going on inside a program so that a person looking at the source code does not have a hard time figuring it out. You might forget the key details of the program you just wrote in a month's time. So taking time to explain these concepts in the form of comments is always fruitful.
In Python, we use the hash (#) symbol to start writing a comment.
It extends up to the newline character. Comments are for programmers for a better understanding of a program. Python Interpreter ignores the comment.
#This is a comment
#print out Hello
print('Hello')
Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the beginning of each line. For example:
#This is a long comment
#and it extends
#to multiple lines
Another way of doing this is to use triple quotes, either
''' or """.
These triple quotes are generally used for multi-line strings. But they can be used as multi-line comments as well. Unless they are not docstrings, they do not generate any extra code.
"""This is also a
perfect example of
multi-line comments"""
Docstring in Python
A docstring is short for documentation string.
It is a string that occurs as the first statement in a module, function, class, or method definition. We must write what a function/class does in the docstring.
Triple quotes are used while writing docstrings. For example
The docstring is available to us as the attribute
__doc__ of the function. Issue the following code in the shell once you run the above program.
0 Comments