1. Introducing Python
What Is Python?
- Interpreted high-level object-oriented dynamically-typed scripting language.
- As a result, run time errors are usually encountered.
Why Python?
- Python is the most popular language due to the fact that it’s easier to code and understand it.
- Python is an object-oriented programming language and can be used to write functional code too.
- It is a suitable language that bridges the gaps between business and developers.
- Subsequently, it takes less time to bring a Python program to market compared to other languages such as C#/Java.
- Additionally, there are a large number of python machine learning and analytical packages.
- A large number of communities and books are available to support Python developers.
- Nearly all types of applications, ranging from forecasting analytical to UI, can be implemented in Python.
- There is no need to declare variable types. Thus it is quicker to implement a Python application.
Python has a set of keywords that are reserved words that cannot be used as variable names, function names, or any other identifiers:
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate 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 likemyClass
,var_1
andprint_this_to_screen
, all are valid example. - An identifier cannot start with a digit.
1variable
is invalid, butvariable1
is a valid name. - Keywords cannot be used as identifiers.
global = 1
- Output
- File “<interactive input>”, line 1 global = 1 ^ SyntaxError: invalid syntax
- We cannot use special symbols like !, @, #, $, % etc. in our identifier.
a@ = 0
- Output
- File “<interactive input>”, line 1 a@ = 0 ^ SyntaxError: invalid syntax
- An identifier can be of any length.
Things to Remember
Python is a case-sensitive language. This means, Variable
and variable
are not the same.
Always give the identifiers a name that makes sense. While c = 10
is a valid name, writing count = 10
would make more sense, and it would be easier to figure out what it represents when you look at your code after a long gap.
Multiple words can be separated using an underscore, like this_is_a_long_variable
.
Statements
Instructions written in the source code for execution are called statements. There are different types of statements in the Python programming language like Assignment statement, Conditional statement, Looping statements etc. These all help the user to get the required output. For example, n = 50 is an assignment statement.
Multi-Line Statements: Statements in Python can be extended to one or more lines using parentheses (), braces {}, square brackets [], semi-colon (;), continuation character slash (\). When the programmer needs to do long calculations and cannot fit his statements into one line, one can make use of these characters.
Example :
Declared using Continuation Character (\):
s = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9Declared using parentheses () :
n = (1 * 2 * 3 + 7 + 8 + 9)Declared using square brackets [] :
footballer = ['MESSI',
'NEYMAR',
'SUAREZ']Declared using braces {} :
x = {1 + 2 + 3 + 4 + 5 + 6 +
7 + 8 + 9}Declared using semicolons(;) :
flag = 2; ropes = 3; pole = 4
Comments
Python developers often make use of the comment system as, without the use of it, things can get real confusing, real fast. Comments are the useful information that the developers provide to make the reader understand the source code. It explains the logic or a part of it used in the code. Comments are usually helpful to someone maintaining or enhancing your code when you are no longer around to answer questions about it. These are often cited as a useful programming convention that does not take part in the output of the program but improves the readability of the whole program. There are two types of comment in Python:
Single line comments : Python single line comment starts with hashtag symbol with no white spaces (#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag 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. See the following code snippet demonstrating single line comment:
Code 1:
# This is a comment
# Print “hk !” to console
print("hk")
Code 2:
a, b =
1, 3
# Declaring two integers
sum
=
a +
b # adding two integers
print(sum) # displaying the output
Multi-line string as comment : Python multi-line comment is a piece of text enclosed in a delimiter (""")
on each end of the comment. Again there should be no white space between delimiter (""")
. They are useful when the comment text does not fit into one line; therefore needs to span across lines. Multi-line comments or paragraphs serve as documentation for others reading your code. See the following code snippet demonstrating multi-line comment:
Code 1:
"""
This would be a multiline comment in Python that
spans several lines and describes hk.
A Computer Science portal for geeks. It contains
well written, well thought
and well-explained computer science
and programming articles,
quizzes and more.
…
"""
print("hk")
Code 2:
'''This article on hk gives you a
perfect example of
multi-line comments'''
print("hk")
Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.
Following are the standard or built-in data type of Python:
PYTHON I/O :
Printing to the Screen
The simplest way to produce output is using the print statement where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string and writes the result to standard output as follows −
#!/usr/bin/pythonprint "Python is really a great language,", "isn't it?"
This produces the following result on your standard screen −
Python is really a great language, isn't it?
Reading Keyboard Input
Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are −
- raw_input
- input
The raw_input Function
The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline).
#!/usr/bin/pythonstr = raw_input("Enter your input: ")
print "Received input is : ", str
This prompts you to enter any string and it would display same string on the screen. When I typed “Hello Python!”, its output is like this −
Enter your input: Hello Python
Received input is : Hello Python
The input Function
The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you.
#!/usr/bin/pythonstr = input("Enter your input: ")
print "Received input is : ", str
This would produce the following result against the entered input −
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]
Types of Operator
Python language supports the following types of operators.
- Arithmetic Operators
- Comparison (Relational) Operators
- Assignment Operators
- Logical Operators
- Bitwise Operators
- Membership Operators
- Identity Operators
Arithmetic Operators
Addition: Sum of two operands +operator.add(a,b)
>>> x = 5; y = 6
>>> x + y
11
>>> import operator
>>> operator.add(5,6)
11
Subtraction: Left operand minus right operand-operator.sub(a,b)
>>> x = 10; y = 5
>>> x - y
5
>>> import operator
>>> operator.sub(10, 5)
5
Assignment Operators
=
>>> x = 5;
>>> x
5
+=operator.iadd(a,b)
>>> x = 5
>>> x += 5
10
>>> import operator
>>> x = operator.iadd(5, 5)
10
What is namespace:
A namespace is a system that has a unique name for each and every object in Python. An object might be a variable or a method. Python itself maintains a namespace in the form of a Python dictionary
Types of namespaces :
When Python interpreter runs solely without any user-defined modules, methods, classes, etc. Some functions like print(), id() are always present, these are built-in namespaces. When a user creates a module, a global namespace gets created, later the creation of local functions creates the local namespace. The built-in namespace encompasses the global namespace and the global namespace encompasses the local namespace.
What is a function in Python?
In Python, a function is a group of related statements that performs a specific task.
Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition that consists of the following components.
- Keyword
def
that marks the start of the function header. - A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.
- Parameters (arguments) through which we pass values to a function. They are optional.
- A colon (:) to mark the end of the function header.
- Optional documentation string (docstring) to describe what the function does.
- One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
- An optional
return
statement to return a value from the function.
Example of a function
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
What is for loop in Python?
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.
Syntax of for Loop
for val in sequence:
Body of for
Here, val
is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.
Flowchart of for Loop
The range() function
We can generate a sequence of numbers using range()
function. range(10)
will generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start, stop,step_size)
. step_size defaults to 1 if not provided.
The range
object is "lazy" in a sense because it doesn't generate every number that it "contains" when we create it. However, it is not an iterator since it supports in
, len
and __getitem__
operations.
This function does not store all the values in memory; it would be inefficient. So it remembers the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function list()
.
The following example will clarify this.
print(range(10))print(list(range(10)))print(list(range(2, 8)))print(list(range(2, 20, 3)))
Output
range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]
We can use the range()
function in for
loops to iterate through a sequence of numbers. It can be combined with the len()
function to iterate through a sequence using indexing. Here is an example.
# Program to iterate through a list using indexinggenre = ['pop', 'rock', 'jazz']# iterate over the list using index
for i in range(len(genre)):
print("I like", genre[i])
Output
I like pop
I like rock
I like jazz
CONDITIONS IN PYTHON :
What is if…else statement in Python?
Decision making is required when we want to execute a code only if a certain condition is satisfied.
The if…elif…else
statement is used in Python for decision making.
Python if Statement Syntax
if test expression:
statement(s)
Here, the program evaluates the test expression
and will execute statement(s) only if the test expression is True
.
If the test expression is False
, the statement(s) is not executed.
Python if…else Statement
Syntax of if…else
if test expression:
Body of if
else:
Body of else
The if..else
statement evaluates test expression
and will execute the body of if
only when the test condition is True
.
If the condition is False
, the body of else
is executed. Indentation is used to separate the blocks.
Python if…elif…else Statement
Syntax of if…elif…else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
The elif
is short for else if. It allows us to check for multiple expressions.
If the condition for if
is False
, it checks the condition of the next elif
block and so on.
If all the conditions are False
, the body of else is executed.
Only one block among the several if...elif...else
blocks is executed according to the condition.
The if
block can have only one else
block. But it can have multiple elif
blocks.
DATA TYPES IN PYTHON :
Python List
List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the items in a list do not need to be of the same type.
Declaring a list is pretty straight forward. Items separated by commas are enclosed within brackets [ ]
.
a = [1, 2.2, 'python']
We can use the slicing operator [ ]
to extract an item or a range of items from a list. The index starts from 0 in Python.
a = [5,10,15,20,25,30,35,40]# a[2] = 15
print("a[2] = ", a[2])# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])# a[5:] = [30, 35, 40]
print("a[5:] = ", a[5:])
Output
a[2] = 15
a[0:3] = [5, 10, 15]
a[5:] = [30, 35, 40]
Lists are mutable, meaning, the value of elements of a list can be altered.
a = [1, 2, 3]
a[2] = 4
print(a)
Output
[1, 2, 4]
Python Tuple
Tuple is an ordered sequence of items same as a list. The only difference is that tuples are immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than lists as they cannot change dynamically.
It is defined within parentheses ()
where items are separated by commas.
t = (5,'program', 1+3j)
We can use the slicing operator []
to extract items but we cannot change its value.
t = (5,'program', 1+3j)# t[1] = 'program'
print("t[1] = ", t[1])# t[0:3] = (5, 'program', (1+3j))
print("t[0:3] = ", t[0:3])# Generates error
# Tuples are immutable
t[0] = 10
Output
t[1] = program
t[0:3] = (5, 'program', (1+3j))
Traceback (most recent call last):
File "test.py", line 11, in <module>
t[0] = 10
TypeError: 'tuple' object does not support item assignment
Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings. Multi-line strings can be denoted using triple quotes, '''
or """
.
s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)
Output
This is a string
A multiline
string
Just like a list and tuple, the slicing operator [ ]
can be used with strings. Strings, however, are immutable.
s = 'Hello world!'# s[4] = 'o'
print("s[4] = ", s[4])# s[6:11] = 'world'
print("s[6:11] = ", s[6:11])# Generates error
# Strings are immutable in Python
s[5] ='d'
Output
s[4] = o
s[6:11] = world
Traceback (most recent call last):
File "<string>", line 11, in <module>
TypeError: 'str' object does not support item assignmen
Python Dictionary
Dictionary is an unordered collection of key-value pairs.
It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value.
In Python, dictionaries are defined within braces {}
with each item being a pair in the form key:value
. Key and value can be of any type.
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
We use key to retrieve the respective value. But not the other way around.
d = {1:'value','key':2}
print(type(d))print("d[1] = ", d[1])print("d['key'] = ", d['key'])# Generates error
print("d[2] = ", d[2])
Output
<class 'dict'>
d[1] = value
d['key'] = 2
Traceback (most recent call last):
File "<string>", line 9, in <module>
KeyError: 2