Python Introduction
Python Introduction
1.1.1 Windows
1. Download the graphical Windows installer from
https://www.anaconda.com/products/individual
2. Double-click the downloaded file and click
continue to start the installation.
3. Answer the prompts on the Introduction, Read
Me, and License screens.
4. Click the Install button to install Anaconda in a
specified directory (C:\Anaconda3_Python)
directory given in the installation.
Figure 1.2: Installing Anaconda on Windows.
1. 3+10-6
Output:
7
1. 30-5*8
Output:
-10
1. (30-5*8)/5
Output:
-2
Output:
2.5
The integer numbers, e.g., the number 20 has type int,
whereas 2.5 has type float. To get an integer result
from division by discarding fractional part, we use the
// operator.
1. 20 // 6
Output:
3
Output:
2
1. 3**4
Output:
81
1. type(5 * 4.6)
Output:
float
Output:
(2+7j)
Output:
-4
Output: 1
1. x | y
Output:
11
1. ~x
Output:
-4
Output:
2
1. y >> 2
Output:
2
Output:
12
Output:
160
Output:
NameError: name 'Marks1' is not defined
The following code assigns value 10 to my_var, then
adds value 20 to it. Thus, the result stored in my_var
becomes 30.
1. my_var = 10
2. my_var+=20
3. my_var
Output:
30
1. my_var1 = 10
2. my_var2 = 4
3. my_var1**= my_var2
4. my_var1
Output:
10000
Output:
True
Output:
False
1. x==y
Output:
False
Not equal !=: It checks if both operands x and y are
not equal.
1. x!=y
Output:
True
1. x > y
Output:
True
Output:
False
Output:
True
Output:
False
1.2.6 Membership Operators
These operators are used to find whether a particular
item or set of items are present in a collection or not.
The membership operators are in and not in.
Output:
True
False
Output:
'An example string in single quotes.'
Output:
' A string in double quotes.'
Output:
Mango and apple are fruits
Output:
File "<ipython-input-96-868ddf679a10>", line 1
print(' Why don't we visit the museum?')
^
SyntaxError: invalid syntax
To print such characters, we use backslash \, called the
escape character.
Output:
Why don't we visit the museum?
Output:
Why don't we visit the museum?
Output:
Why don't we visit
the museum?
print(r'c:\new_directory')
Output:
c:\new_directory
Output:
' Computer Vision using Python'
String Indexing
The string elements, individual characters or a
substring, can be accessed in Python using positive as
well as negative indices. Indexing used by Python is
shown in Figure 1.21.
Output:
T
The indices start from 0 in Python. To access last
character of the string, we may write
print(x[-1])
Output:
g
1. print(x[0:7])
Output:
This is
print(x[8:len(x)])
Output:
a test string
The string slice begins from the start of the string even
if we omit the first index: x[:i2] and x[0:i2] give the same
result.
Output:
'hsi e'
Output:
'git stas i'
Output:
'git stas iT'
Output:
'Hello Hello Hello Hello Hello '
Output:
This is a text string
Output:
this is a text string
Output:
THIS IS A TEXT STRING
Output:
I ate a mango
Output:
['Hi mate', ' how do you do?']
1. student_marks = 90
2. if(student_marks > 100):
3. print("Marks exceed 100.")
Note that the input() function gets the input from the
user; it saves the input as a string. We use int(input())
to get an integer from the string. If we execute the
aforementioned program, and input marks greater than
100, we get a warning "Marks exceed 100". If the
entered marks are 100 or less, no warning message is
displayed.
else Statement
The statement 'else' is always accompanied by an
accompanying if statement, i.e., 'if-else'. The syntax
of if-else is given below.
if(condition):
Indented statement(s) when condition is True
else:
Indented statement(s) when condition is False
Nested Decisions
To take decisions under multiple conditions, Python
allows us to perform nested decisions. The 'if-elif-
else' statements are employed to accomplish nested
decisions. Continuing with the example of student
marks, if the marks of a student are greater than 100
or less than 0, a waring should be displayed.
Additionally, if obtained marks are 80 or greater,
Outstanding should be displayed. Otherwise, Not
outstanding should be displayed.
1. print('Enter marks of a student')
2. student_marks = int(input())
3. if(student_marks > 100 or student_marks < 0):
4. print("Invalid marks.")
5. elif(student_marks >= 80):
6. print("Outstanding")
7. else:
8. print("Not outstanding")
Further Readings
More information about conditional statements can
be found at
https://www.techbeamers.com/python-if-else/
1.4.2 For Loop
Iteration statements provided by Python allows us to
perform a task more than once. To iterate a task fixed
number of times, a 'for' loop is used. A 'for' loop has
a definite beginning and end. We provide a sequence
or a variable to the loop as an input that causes the
loop to execute a fixed number of times. The syntax of
a for loop is given as.
Output:
Computer Vision
Machine Learning
Data Science
Artificial Intelligence
In this example, “subjects” is a variable containing 4
items. This is used to decide the number of iterations
of a for loop. The loop runs 4 times because the
number of items in the variable subjects is 4.
1. for k in range(5):
2. print(k)
Output:
0
1
2
3
4
We can also specify a step size other than 1 within the
range () function as follows.
Output:
3
6
9
Output:
Adam
Alice
Emma
Nested Loops
A loop, either 'for' or 'while', can be used inside another
loop. This is known as a nested loop that can be used
when we work with the data in 2-dimensions. The
following program uses two 'for' loops, one nested
inside another, to print all the combinations of two
variables.
1. attributes = ["heavy", "wooden", "fast"]
2. objects = ["chair", "table", "computer"]
3. for j in attributes:
4. for k in objects:
5. print(j, k)
Output:
heavy chair
heavy table
heavy computer
wooden chair
wooden table
wooden computer
fast chair
fast table
fast computer
Further Readings
More information about iteration statements can be
found at
http://www.lastnightstudy.com/Show?id=84/Pytho
n-3-Iteration-Statements
https://www.w3schools.com/python/default.asp
1. def my_function1():
2. print("This is a test function")
Output:
This is a test function
1. def my_function2(str_in):
2. print("This function prints its input that is
" + str_in)
3.
4. my_function2("computer")
5. my_function2("table")
6. my_function2("chair")
Output:
This function prints its input that is computer
This function prints its input that is table
This function prints its input that is chair
1. def my_function3(*myfruits):
2. print(myfruits[2], "is my favorite fruit.")
3. my_function3("Mango", "Apple", "Orange") # 3 inpu
ts.
Output:
Orange is my favorite fruit.
1. my_function3("Mango", "Orange","Apricot","Apple"
) # 4 inputs.
Output:
Apricot is my favorite fruit.
1. def mult_by_10(k):
2. return 10 * k
3. print(mult_by_10(2))
4. print(mult_by_10(-8))
5. print(mult_by_10(100))
Output:
20
-80
1000
Output:
0
-20
10
1.6.1 Lists
A list is a mutable and ordered collection of elements.
Lists are specified using square brackets in Python.
For instance, to create a list named as item_list, type
the following code.
Output:
['backpack', 'laptop', 'ball point', 'sun glasses']
1. print(item_list[2])
Output:
ball point
Output:
laptop
Output:
['laptop', 'ball point']
1. item_list[1] = "computer"
2. print(item_list)
Output:
['backpack', 'computer', 'ball point', 'sun glasses']
3. else:
4. print("sun glasses are not present in the lis
t")
Output:
sun glasses are present in the list
1.6.2 Tuples
A tuple is immutable and ordered collection of items. In
Python, tuples are specified using round brackets ().
The following code creates a tuple.
Output:
('Python', 'for', 'Computer Vision')
1. print(py_cv[2])
Output:
Computer Vision
Output:
0
1
1. print(py_cv2.index('Python'))
2. print(py_cv2.index('Computer'))
Output:
0
ValueError: tuple.index(x): x not in tuple
1.6.3 Sets
A set is an unindexed and unordered collection of
items. Python specifies sets using curly brackets { }.
For example, type the following code.
1. my_animals = {"cat", "dog", "tiger", "fox"}
2. print(my_animals)
Output:
{'dog', 'tiger', 'cat', 'fox'}
Output:
dog
cat
tiger
fox
1. print("tiger" in my_animals)
2. print("lion" in my_animals)
Output:
True
False
Output:
{'lion', 'cat', 'tiger', 'dog', 'fox'}
Output:
{'cat', 'tiger', 'dog', 'goat', 'sheep', 'fox'}
Output:
{'dog', 'cat', 'fox'}
Output:
{4, 5, 6, 'Y', 'X', 'Z'}
Moreover, the method pop( ) removes a random item
from a set. The method clear ( ) empties the set, and
the keyword del before the name of the set deletes the
set completely.
1.6.4 Dictionaries
1. py_cv_dict = {
2. "name": "Python",
3. "purpose": "Computer Vision",
4. "year": 2021
5. }
6. print(py_cv_dict)
Output:
{'name': 'Python', 'purpose': 'Computer Vision', 'year':
2021}
Output:
Python
Computer Vision
A message: None is displayed if we try to access a
non-existent key.
print(py_cv_dict.get('address'))
Output:
None
1. py_cv_dict["year"] = 2020
2. py_cv_dict
Output:
{'name': 'Python', 'purpose': 'Computer Vision', 'year':
2020}
1. for k in py_cv_dict:
2. print(k)
Output:
name
purpose
year
Output:
Python
Computer Vision
2020
1. for k in py_cv_dict.values():
2. print(k)
1. for x, y in py_cv_dict.items():
2. print(x, y)
Output:
name Python
purpose Computer Vision
year 2020
1. if "year" in py_cv_dict:
2. print("'year' is one of the valid keys")
Output:
'year' is one of the valid keys
Output:
{'name': 'Python', 'purpose': 'Computer Vision', 'year':
2020, 'pages': 300}
Output:
{'name': 'Python', 'purpose': 'Data science', 'pages':
300}
The keyword del removes the whole dictionary when
we use del py_cv_dict. The method clear() deletes all
elements of a dictionary.
1. py_cv_dict.clear()
2. py_cv_dict
Output:
{ }
1. py_cv_dict = {
2. "name": "Python",
3. "purpose": "Computer Vision",
4. "year": 2021
5. }
6. print(len(py_cv_dict))
Output:
3
A dictionary cannot be copied by a simple assignment
such as py_cv_dict2 = py_cv_dict. It is because
py_cv_dict2 is just a reference to the original dictionary
py_cv_dict. Whatever changes are made to
py_cv_dict, same are automatically made to
py_cv_dict2 as well. To copy the elements of a
dictionary, we use the method copy() as follows.
1. py_cv_dict2 = py_cv_dict.copy()
2. print(py_cv_dict)
3. print(py_cv_dict2)
Output:
{'name': 'Python', 'purpose': 'Computer Vision', 'year':
2021}
{'name': 'Python', 'purpose': ' Computer Vision',
'year': 2021}
Further Reading