Tutorial 1 Introduction To Python
Tutorial 1 Introduction To Python
Tutorial 1 Introduction To Python
Reference: https://www.programiz.com/python-programming
This tutorial is created using the examples available on above reference website. The website
provides online interactive tutorials.
History of Python
Python is a fairly old language created by Guido Van Rossum. The design began in the late 1980s and
was first released in February 1991.
No. It wasn't named after a dangerous snake. Rossum was fan of a comedy series from
late seventies. The name "Python" was adopted from the same series "Monty Python's
Flying Circus".
Python in Linux
Python versions 2.x and 3.x are usually available in most modern Linux distributions out of the box.
You can enter a Python shell by typing python or python3 in your terminal and exit with quit():
$ which python
$ which python3
$ python -v
$ python3 -v
$ python
>>> quit()
$ python3
>>> quit()
1
Your First Python Program
Create a directory called "python_tutorial" in your home directory. Inside that directory, create a
new file called "addnumbers.py".
# Add two numbers
num1 = 3
num2 = 5
sum = num1+num2
print(sum)
Line 2: num1 = 3
Here, num1 is a variable. You can store a value in a variable. Here, 3 is stored in this variable.
Line 3: num2 = 5
The variables num1 and num2 are added using + operator. The result of addition is then stored in
another variable sum.
Line 5: print(sum)
The print() function prints the output to the screen. In our case, it prints 8 on the screen.
Running Python scripts (for this tutorial, use the method number 2, script mode)
1. Immediate mode: You type the command at the Python console, one by one, and the
answer is immediate.
2. Script mode: On most of the UNIX systems, you can run Python scripts from the command
line in the following manner
$ cd ~/python_tutorial
$ python addnumbers.py
2
3. Integrated Development Environment (IDE)
Using an IDE can get rid of redundant tasks and significantly decrease the time required for
application development.
IDE is a graphical user interface (GUI) that can be installed along with the Python programming
language and is available from the official website.
Possible issues
It is important to remember that Python takes tabs very seriously – so if you are receiving any error
that mentions tabs, correct the tab spacing. Both tabs and spaces are supported, but the standard
indentation requires standard Python code to use four spaces.
Python Keywords
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.
Python Indentation
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.
3
Python Variables
print(website)
website = "Apple.com"
print(website)
print (a)
print (b)
print (c)
print (x)
print (y)
print (z)
In Python, constants are usually declared and assigned on a module. Here, the module means a new
file containing variables, functions etc which is imported to main file. Inside the module, constants
are written in all capital letters and underscores separating the words.
Create a “constant.py”
PI = 3.14
GRAVITY = 9.8
Create a “constant_example.py”
import constant
print(constant.PI)
print(constant.GRAVITY)
In the above program, we create a constant.py module file. Then, we assign the constant value to PI
and GRAVITY. After that, we create a main.py file and import the constant module. Finally, we print
the constant value.
4
Data types in Python
Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes.
There are various data types in Python. Some of the important types are listed below.
1.Python Numbers
Integers, floating point numbers and complex numbers falls under Python numbers category. They
are defined as int, float and complex class in Python.
We can use the type() function to know which class a variable or a value belongs to and the
isinstance() function to check if an object belongs to a particular class.
Create “datatypes_example1.py”.
a = 5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
2.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. Index starts form
0 in Python.
Create “datatypes_example2.py”.
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
3.Python Tuple
Tuple is an ordered sequence of items same as list. The only difference is that tuples are immutable.
Tuples once created cannot be modified.
5
Tuples are used to write-protect data and are usually faster than list as it cannot change dynamically.
We can use the slicing operator [] to extract items but we cannot change its value.
Create “datatypes_example3.py”.
t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])
# Generates error
# Tuples are immutable
t[0] = 10
4.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"
>>> s = '''a multiline
Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable.
Create “datatypes_example4.py”.
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'
5.Python Set
Set is an unordered collection of unique items. Set is defined by values separated by comma inside
braces { }. Items in a set are not ordered.
Create “datatypes_example5.py”.
a = {5,2,3,1,4,4,4}
6
# data type of variable a
print(type(a))
6.Python Dictionary
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.
Create “datatypes_example6.py”.
d = {1:'value','key':2}
print(type(d))
# Generates error
print("d[2] = ", d[2]);
Python Import
When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements. Python modules have a filename
and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter in
Python. We use the import keyword to do this.
For example, we can import the math module by typing in import math.
import math
print(math.pi)
Now all the definitions inside math module are available in our scope. We can also import some
specific attributes and functions only, using the from keyword. For example:
7
While importing a module, Python looks at several places defined in sys.path. It is a list of directory
locations.
> x>y
< x<y
== x == y
!= x != y
>= x >= y
<= x <= y
Create “if_else_example1.py”
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Create “if_else_example2.py”
# In this program,
# we check if the number is positive or
# negative or zero and
# display an appropriate message
num = 3.4
8
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Create “if_else_example2.py”
# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects.
Create “for_loop_example1.py”
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
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.
9
The following example will clarify this.
# Output: range(0, 10)
print(range(10))
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))
# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))
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 though a sequence using indexing. Here is an example.
Create “for_loop_example2.py”
# Program to iterate through a list using indexing
A for loop can have an optional else block as well. The else part is executed if the items in the
sequence used in for loop exhausts.
Create “for_loop_example2.py”
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true.
Create “while_loop_example1.py”
n = 10
10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
Same as that of for loop, we can have an optional else block with while loop as well.
Create “while_loop_example2.py”
# Example to illustrate
# the use of else statement
# with the while loop
counter = 0
The break statement terminates the loop containing it. Control of the program flows to the
statement immediately after the body of the loop.
Create “break_stat_example.py”
print("The end")
The continue statement is used to skip the rest of the code inside a loop for the current iteration
only. Loop does not terminate but continues on with the next iteration.
Create “continue_stat_example.py”
11
# Program to show the use of continue statement inside loops
print("The end")
In Python programming, pass is a null statement. The difference between a comment and pass
statement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored.
However, nothing happens when pass is executed. It results into no operation (NOP).
Create “pass_stat_example.py”
# pass is just a placeholder for
# functionality to be added later.
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
We can create an infinite loop using while statement. If the condition of while loop is always True,
we get an infinite loop.
Create "loop_example1.py".
while True:
num = int(input("Enter an integer: "))
print("The double of",num,"is",2 * num)
Create "loop_example2.py".
12
while i <= n:
sum = sum + i
i = i+1 # update counter
Create "loop_example3.py".
# Program to illustrate a loop with condition in the middle.
# Take input from the user until a vowel is entered
vowels = "aeiouAEIOU"
# infinite loop
while True:
v = input("Enter a vowel: ")
# condition in the middle
if v in vowels:
break
print("That is not a vowel. Try again!")
print("Thank you!")
Create "loop_example4.py".
# Python program to illustrate a loop with condition at the bottom
# Roll a dice until user chooses to exit
while True:
input("Press enter to roll the dice")
# condition
if option == 'n':
break
Python Functions
Once we have defined a function, we can call it from another function, program or even the Python
prompt. To call a function we simply type the function name with appropriate parameters.
Create "function_example1.py".
13
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
# Output: 2
print(absolute_value(2))
# Output: 4
print(absolute_value(-4))
Scope of a variable is the portion of a program where the variable is recognized. Parameters and
variables defined inside a function is not visible from outside. Hence, they have a local scope.
Create "function_example2.py".
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Create "function_example3.py".
def greet(name,msg):
"""This function greets to
the person with the provided message"""
print("Hello",name + ', ' + msg)
greet("Monica","Good morning!")
Create "function_example3.py".
def greet(name, msg = "Good morning!"):
"""
This function greets to
the person with the
provided message.
greet("Kate")
greet("Bruce","How do you do?")
14
Using Global and Local variables in same code
Create "global_local_example.py".
x = "global"
def foo():
global x
y = "local"
x = x * 2
print(x)
print(y)
foo()
NumPy Array
NumPy is a package for scientific computing which has support for a powerful N-dimensional array
object.
NumPy provides multidimensional array of numbers (which is actually an object). Let's take an
example:
Create "numpy_example1.py".
import numpy as np
a = np.array([1, 2, 3])
print(a) # Output: [1, 2, 3]
print(type(a)) # Output: <class 'numpy.ndarray'>
Create "numpy_example1.py".
import numpy as np
15