Introduction to Python
Python is an interpreted programming language. It
was created by Guido Van Rossum, and released in
1991.
It can be used :-
web development (server-side),
software development,
handle big data and complex mathematics
system scripting.
connect to database systems
Why Python
Python works on different platforms
Simple syntax Example: print("Hello, World!")
Similar to the English language.
Python runs on an interpreter system (executes very fast )
It allows Object-oriented Programming
It can be written using Thonny, Pycharm, Netbeans or
Eclipse
How to install Python?
To check if you have python installed
Search in the start bar for Python or
Run in your cmd prompt:
C:\Users\Your Name>python –version
To check in Linux
python –version
It can be written in any text editor
Example:
print(“Hello, Welcome to the world of Python!”)
Save this file as hello.py
Open your cmd line, navigate to the directory where you
saved your file, and run
C:\Users\Your Name>python hello.py
The output : Hello, Welcome to the world of Python!
Python syntax
1. print("Hello, World!")
2. if 5 > 2:
print("Five is greater than two!")
if 5 > 6:
print("Five is less than six!")
Variable in Python
Python has no command for declaring a variable
In Python, variables are created when you assign a value to it:
x=5
y = "Hello, World!"
print(x)
print(y)
Python Variable
How to declare Variable name
Start with a letter or the underscore character
Not with a number
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Variable names are case-sensitive
(age, Age and AGE are three different variables)
Variable: Multiple ways
Camel Case
myVariableName = "Linguistics”
Pascal Case
MyVariableName = " Linguistics”
Snake Case
my_variable_name = “Linguistics"
Assigning multi values to multi Variables
x, y, z = “Phonology", “Phonetics", “Speech Pathology"
print(x)
print(y)
print(z)
Single value to multi Variable
x = y = z = “Phonology"
print(x)
print(y)
print(z)
Outputting Variable
print() function is often used to print the values stored in the variables
x = "Python is awesome"
print(x)
In the print() function, multiple variables are separated by a comma.
+ operator can also be used to print the multiple variables
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Global Variable and Local Variable
Global
x = "awesome"
Syntax
Variable
VariableName = “Statement1” def myfunc():
Local x = "fantastic"
def FunctionName():
VariableName = “Statement2” Variable print("Python is " + x)
print(“Statements” + VariableName) myfunc()
FunctionName()
print(“Statements” + VariableName) print("Python is " + x)
Output:
Python is fantastic
Python is awesome
Python - 2
Comments in Python
Comments is used to explain Python code and make the
code more readable
Comments prevent execution when testing code.
Comments start with a #
x=5
y = "Hello, World!"
print(x) #This is a comment. This will print the value of
x
print(y)
Comments in Python
Lets see this code
#print("Hello, World!")
print("Cheers, Mate!")
What would be the output?
Text Type: Str "Hello World"
Numeric Types: int, float, complex 20, 20.02, 1j
Sequence Types: list, tuple, range ["apple", "banana", "cherry"]
("apple", "banana", "cherry")
range(6)
Mapping Type: Dict {"name" : "John", "age" : 36}
Set Types: set, frozenset {"apple", "banana", "cherry"}
Boolean Type: Bool True
Binary Types: bytes, bytearray, memoryview
None Type: NoneType
If you want to specify the data type of a variable, this can be
done with casting.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
You can get the data type of a variable with the type() function.
x=5
y = “Mohan"
print(type(x))
print(type(y))
One type to another type
x=1
y = 2.8
z = 1j
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
Assigning String to a Variable
Assigning a string to a variable is done with the variable name
followed by an equal to (=) sign and the string:
Example a = “Linguistics"
print(a)
Or a=„Linguistics‟
print(a)
Assign multiline String to a Variable
Use three double quotes for multi line statements
Example
a=“““Linguistics is the scientific study of human language. It
is called a scientific study because it entails a comprehensive,
systematic, objective, and precise analysis of all aspects of
language, particularly its nature and structure.”””
print(a)
Check String
in and not in function in Python
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
Python Collections (Arrays)
There are four collection/special kind of data types in Python.
•List is a collection which is ordered and changeable. Allows
duplicate members.
•Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
•Set is a collection which is unordered, unchangeable*, and
unindexed. No duplicate members.
•Dictionary is a collection which is ordered** and changeable. No
duplicate members.
List data Type: List data type may store any type of data
Syntax Example
list_name = [“str1", “str2", “str3"] list1 =
["apple", "banana", "cherry"]
print(list_name) list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
print(list2)
List items are indexed and you can access them by referring to the
index number:
List1 = [„we‟, „love‟, „India‟]
Indexing starts with zero (0). So, the first item‟s index is 0, the
second item‟s index is 1 and so on.
Example
mylist = [“Linguistics", “Phonology", “Semantics“,
“Pragmatics”, “Computational Linguistics”, “Typology”]
print(mylist[1])
print(mylist[2:5])
A Program to check the type of the list
my_list = ["apple", "banana", "cherry"]
print(type(my_list))
A Program to check the item exists in the list
my_list = ["apple", "banana", "cherry"]
if "apple" in my_list:
print("Yes, 'apple' is in the fruits list")
Insert/Append/Extend Items
To insert a new list item, without replacing any of the existing values, we can use
the insert(). The insert() method inserts an item at the specified index:
To append elements from another list to the current list, use the extend() method.
To add an item to the end of the list, use the append() method:
Example
Insert "watermelon" as the third item:
list1 = [“ABC", “DEF", “JKL"]
list1.insert(2, “GHI")
print(list1)
Arithmetic operators are used with numeric values to
perform common mathematical operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Some program using operators
i = 256*256
print('The value of i is', i)
J= 100+101
Print(„the value of J is‟, J)
Output:
When you run a condition in an if statement, Python
returns True or False:
a = 200
print(10 > 9) b = 33
print(10 == 9) if b > a:
print("b is greater than a")
print(10 < 9) else:
print("b is not greater than a")
Python - 3
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a<b
Less than / equal to: a <= b
Greater than: a>b
Greater than/equal to: a >= b
These conditions can be used in several ways, most commonly in "if
statements" and loops.
An "if statement" is written by using the if keyword.
Syntax or
if expression1:
if expression statement
Statement1 elif expression2:
else Statement2 statement
elif expression3:
statement
else:
statement
a=3
b=3
Syntax if b > a:
print("b is greater than a")
if expression elif a == b:
Statement1 print("a and b are equal")
else Statement2
a = 20
b=3
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Lets consider the given
code/program….and answer.
# this is an exercise program
What is/are variable here ? prime_numbers = [1, 3, 5, 7, 11]
print(prime_numbers)
Write the data type of those variables.
empty_list = [ ]
What is/are the function(s) used here? print(empty_list)
What would be the output of this print(prime_numbers[0])
program?
What is comment in this program?
Prime number using for loop
prime_numbers = [1, 3, 5, 7, 11]
for prime in prime_numbers:
print(prime)
print('Done!')
example
subject = Linguistics
for x in subject:
print(x)
names = [“Ammi", “Ananya", “Aman"]
for x in names:
print(x)
#printing 0 to 99 numbers
for x in range(100):
print(x)
#printing 1 to 100 numbers
for y in range(1,101)
print(y)
# Iterating over a set
print("\n Set Iteration")
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i),
Displaying table in Python using for
# Multiplication table (from 1 to 10) in Python
num = 12
num = int(input("Display multiplication table of? "))
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
Writing table using for
num=15
i=1
while i<= 10:
# Infinite loop using while
print(“num*i”)
i=i+1 while True
print(“Hi dear”)
# Python program to illustrate while loop
x=0
while (x < 3):
x=x+1
print("Hello friend")
Printing number series in Python
Example
# Fibonacci series
a, b = 0, 1
while a < 10
print(a) ... a, b = b, a+b
break()
It control out of the loop. It is used with both the while and the for
loops, especially with nested loops to quit the loop. It terminates
the inner loop and control shifts to the statement in the outer loop.
age = “\n Please enter your age: ”
while True:
age = input
if age >= 18:
break
else:
print (“You‟re not eligible to vote”)
continue()
It is used to continue running the program even after the
program encounters a break during execution.
for letter in ‘Linguistics':
if letter == ' ':
continue
print ('Letters: ', letter))
Pass()
The pass statement is a null operator and is used when the
programmer wants to do nothing when the condition is
satisfied.
for letter in ‘Linguistics':
if letter == ' s':
pass
print ('Letters: ', letter))
Functions in Python
Functions (also called 'procedures' in some programming
languages and 'methods' in most object oriented
programming languages) are a set of instructions bundled
together to achieve a specific outcome.
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function. A
function can return data as a result.
Following are the features of Python Functions:
1.It is used to avoid repetitions of code.
2.Using the function, we can divide a group of code into smaller
modules.
3.It helps to hide the code and create clarity to understand the modules.
4.It allows code to be reusable, thus saving memory.
5.Statements written inside a function can only be executed with a
function name.
6.Python function starts with def and then a colon (:) followed by the
function name.
Defining a function and calling it
def my_function():
print("Hello this is my function")
my_function()
Note: To call a function, use the function name followed by parenthesis:
example
def myIntro(): # define function name
print( “Imran Ali, Research Scholar, Deptt of Linguistics,
Faculty of Arts, Banaras Hindu University” )
myIntro() # call to print the statement
Defining a function and calling it
def my_function(country = “India"):
print("I am from " + country)
my_function("Sweden")
my_function(“America")
my_function()
my_function("Brazil")
Note: To call a function, use the function name followed by parenthesis:
Python - Calculator
Simple Calculator
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x – y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y): return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
# check if user wants another calculation
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
# break the while loop if answer is no
break
else:
print("Invalid Input")
Python Library for Natural language processing
NumPy TensorFLOW
Metaplotbit SciPY
Pandas spiCy / NLTK
Seaborn OpenCV
Scikitlearn Keras
PyTorch
Presented and instructed by
Imran Ali
Research Scholar, Department of Linguistics
Banaras Hindu University, Varanasi (India)