PYTHON 3 BASICS
HELLO, PYTHON!
HISTORY OF PYTHON
Python is an Object-Oriented, high-level programming language used for general-purpose programming. It was created by Guido van Rossum and released on February 20, 1991. Python is a case-sensitive, interpreted and widely used programming language.
FEATURES OF PYTHON PROGRAMMING
a) Easy to code
b) Free and open source
c) Object-Oriented Language
d) GUI Programming Support
e) High-Level
f) Extensible
g) Portable
h) Integrated and Interpreted
APPLICATIONS OF PYTHON
a) Machine Learning
b) Artificial Intelligence
c) Web Development
d) Game Development
e) Data Analysis
f) Scientific Research
g) Automation
Python is used by many companies such as Google, Facebook, Netflix, etc. It is also used by thousands of small companies as well.
REASONS TO CHOOSE PYTHON AS THE FIRST LANGUAGE
Python is one of the easiest languages to learn because of its easy-to-use syntax. The simplicity of python syntax allows us to focus on the logic rather than focusing on syntax. Another reason to learn python is because of its growing popularity and applications.
As python is a cross-platform programming language, it can run on multiple platforms such as Windows, Linux, and macOS.
EASIEST WAY TO RUN PYTHON
The easiest way to run python is by using Google Colab. Google Colaboratory or ‘Colab’ for short is a web IDE for python. Colab allows anybody to write and execute python code through a browser and is especially well suited for Machine Learning, Data Analysis work with storage on the cloud. Google also provides the use of free GPU and TPU for your Colab notebooks.
To start working with Colab, you first need to log in to your Google account, then go to this link. On opening the website you can create a new Jupyter Notebook by clicking New Notebook at the bottom right corner. This will create a new Jupyter Notebook with the title Untitled0.ipynb and saves it to your Google Drive in a folder named Colab Notebooks. You can further rename the file name according to your preference.
Other than Google Colab Notebooks, you can also install Python separately and run Python either in Immediate Mode or in Integrated Development Environment (IDE or IDLE). You can also install Anaconda and use Jupyter Notebooks by installing them (offline mode).
HELLO, WORLD!
Now, let’s create a very simple python program which is Hello World. It simply outputs Hello World on the screen.
print(“Hello, World!”)
Hello, World!
SYNTAX AND SEMANTICS
Programming languages have syntax and semantics. For python, Syntax is the rules for how each instruction is written. Semantics is the effect the instructions have.
PYTHON KEYWORDS
Keywords are the reserved words that are used to construct instructions. Keywords cannot be used as a variable name, function name, or any other identifier.
Python Keywords are case-sensitive and used to define the syntax and structure of the programming language.
Total Keywords in Python3.7 is 35 till now and this number can vary with time.
All the keywords are in lowercase except True, False and None. The list of all the keywords in python programming is given below:
The above keywords may get altered over the course of time as some extra might get added or some might be removed in different versions of python. We can also get the list of keywords by typing the following command:
import keyword
print(keyword.kwlist)
[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]
PYTHON IDENTIFIERS
A Python Identifier is a name given to identify entities like class, functions, variables, modules or other objects. It helps to differentiate entities from one another.
RULES FOR WRITING IDENTIFIERS
a) An Identifier is always written as a combination of characters, digits and underscores. It always starts with letters in lowercase (a-z) or uppercase (A-Z) or underscore (_) followed by digits (0–9). Some examples of valid identifiers are obj1, _obj1, obj_1, _1_obj.
b) An identifier should start with a character or underscore and then use a digit. It cannot start with a digit. Obj1 is a valid name but 1obj is invalid.
c) Punctuation characters or special symbols (!, @, #, $, %) are not allowed within identifiers. Names like !obj, 1_obj, obj#1 all are examples of invalid python identifiers.
d) We cannot use keywords as identifiers.
global = 1File "<python example>", line 1
global = 1
^
SyntaxError: invalid syntax
Above is an example of an invalid identifier.
e) An identifier can be of any length. As Python is a case-sensitive programming language, so variable and Variable are two different identifiers. Always name identifiers that make sense. For example, c = 10 is a valid name but count = 10 gives more sense.
Also, underscores can be used to separate multiple words like my_class_variable.
THINGS TO REMEMBER
- All other identifiers can start with a lowercase letter except class names, which should start with an uppercase letter.
- If an identifier starts with a single leading underscore, it indicates that the identifier is private.
- If an identifier starts with two leading underscores, it indicates a strongly private identifier.
- An identifier is a language-defined special name if it starts and ends with two trailing underscores.
PYTHON STATEMENTS & INDENTATION
STATEMENTS
Instructions executed by a python interpreter are called Statements. Different types of python statements are Assignment Statement like var = 1, Conditional Statements like if-else statements, Looping Statements like for statement, while statement etc. These statements help in getting the required output.
MULTI-LINE STATEMENTS
Usually, python statements are written in a single line but if the statement is long, we can divide it into multiple lines with the line continuation character (\). Multi-line continuation in python is implied inside parentheses ( ), brackets [ ] and braces { }. Semi-colons (;) are used to write multi-line comments in a single line.
Example using Continuation Character (\):
s = 1 + 2 + 3 + \4 + 5 + 6 + \7 + 8 + 9
Example using parentheses ():
n = (1 * 2 * 3 + 7 + 8 + 9)
Example using square brackets []:
colors = [‘red’,‘blue’,‘green’]
Example using braces {}:
x = {1 + 2 + 3 + 4 + 5 + 6 +7 + 8 + 9}
Example using semicolons (;):
a = 2; b = 3; c = 4
INDENTATION
Indentation refers to the spaces at the beginning of a code line. In the Python programming language, a block of code is defined using indentation. A code block is a body of a function or a loop that starts with indentation and ends with the first unindented line. The amount of indentation is generally four whitespaces and is preferred over tabs, but it must be consistent throughout that block. For example,
if 1 < 4:
print(“Four is less than 1”)
Indentation helps in making the code look neat and clean. It makes the code more readable.
In some cases, the indentation can be ignored like in inline continuation. For example,
if False:
print('False')
a = 5
and
if False: print(“False”); a=5
both are valid examples but the former style is more preferred.
For incorrect indentation, python will result in IndentationError.
PYTHON COMMENTS
While writing a program in python, it’s always a good idea to write comments to better understand a program. Comments are inline explanations provided by the developers for the readers to make them understand the source code. It explains the logic used in the code. Comments are ignored by the python interpreter. There are two types of comments in Python:
a) Single Line Comments: The hash (#) symbol is used to write a single line comment which extends up to the newline character. If the comment exceeds one line then put a hash (#) on the next line and continue the comment. Python’s single-line comments are proved useful for supplying short explanations for variables, function declarations, and expressions.
# This is a comment
b) Multi-Line Comments: Comments that are extended up to multiple lines can be written using triple quotes, either ‘ ‘ ‘ or “ “ “.We can also write a multi-line comment using (#) at the beginning of each line. For example,
"""This is aperfect example ofmulti-line comments"""
and
#This is a#multi-line comment
both are valid multi-line comments.
DOCSTRINGS
Python docstrings are the documentation strings or string literals that appear right after the definition of a function, method, class or module. Docstrings are written using triple quotes. These are different from multi-line comments. Example:
def double (num): """Function to double the value""" return 2*num
Thanks for reading this article! Leave a comment below if you have any questions. I’ll be posting more about Python soon.
You can also follow me here and on my other social media handles as well :):)