Programming
with Python
Dr. Amar Singh
Associate Professor, Department of Computer Applications
Lovely Professional University
1
Part – 1 (Python Basics)
2
Agenda
Introduction to Python
Python variables
Data Types
Strings
Strings methods and operations
Print and Input Functions
3
Introduction to Python
Created by Guido van Rossum in 1989.
Implemented in C Language.
Python is interpreter based High Level Language.
It supports both procedure oriented and Object
Oriented.
Easy to Learn.
Best of the organizations uses python
Youtube
Dropbox
Google
BitTorrent
Raspberry-PI
NASA
NSA
Features
Simple and Easy to Learn
Free and Open Source
High Level Language
Portable
Supports both objects oriented and procedural oriented
programming.
Extensible
Loosly Typed Language (No need to declare the data
type of a variable)
No Need to declare the variables before to use it.
Language Elements : Constants
Fixed values such as numbers, letters, and strings are
called “constants” - because their value does not change
Numeric constants are as you expect
String constants use single-quotes (') or double-quotes (")
>>> print(123)
123
>>> print(98.6)
98.6
>>> print('Hello world‘)
Hello world
Variables
variable: A named piece of memory that can store a value.
Usage:
Compute an expression's result,
store that result into a variable,
and use that variable later in the program.
assignment statement: Stores a value into a variable.
Syntax:
name = value
Examples: x = 5
gpa = 3.14
x 5 gpa 3.14
A variable that has been given a value can be used in expressions.
x + 4 is 9
8
Python Variable Name Rules
• Must start with a letter or underscore _
• Must consist of letters and numbers and underscores
• Case Sensitive
• Good: spam eggs spam23 _speed
• Bad: 23spam #sign var.12
• Different: spam Spam SPAM
Reserved Words
• You can not use reserved words as variable names /
identifiers
Assignment Statements
We assign a value to a variable using the assignment
statement (=)
An assignment statement consists of an expression on
the right hand side and a variable to store the result
x = 3.9 * x * ( 1 - x )
print
print : Produces text output on the console.
Syntax:
print("Message“)
print(Expression)
Prints the given text message or expression value on the console, and
moves the cursor down to the next line.
print(Item1, Item2, ..., ItemN)
Prints several messages and/or expressions on the same line.
Examples:
print("Hello, world!“)
age = 45
print("Your age is", age)
Output:
Hello, world!
Your age is 45
12
First Program in python
X = 10
Print(x)
Print(“Welcome to Python-”)
13
Comments
All code must contain comments that describe what it
does
In Python, lines beginning with a # sign are comment
lines
# this is a single comment
’’’
this is multiline comment
’’’
14
Data Types
Numbers
Integer, float.
Strings
Boolean
Tuples
Lists
Dictionaries
Numeric Expressions
Addition = 10 + 14
Subraction = 10 – 2
Division = 8 / 4
Multiplication = 6 * 5
power = 3 ** 3
Floordiv = 16 // 3 #floordiv = 5
Modulo = 4 % 3 # modulo = 1
16
Logic
Many logical expressions use relational operators:
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True
Logical expressions can be combined with logical operators:
Operator Example Result
and 9 != 6 and 2 < 3 True
or 2 == 3 or -1 < 5 True
not not 7 > 0 False
17
Numbers
x = 90
y = -10
z = 5
Z = x + z
Boolean
x = True
y = False
Exercise 1
Create a variable and assign it a integer value.
Create a variable and assign it a float value.
Create a variable and assign it a boolean value.
Use print() to display the values of all created integer,
float and boolean variables.
20
Print and input Functions
Print function is used to print the data.
Input function is used to take the input from keyboard.
Variable = input(any string)
code:
y = input(“Enter the name of the book”)
z = input(“Enter the author of the book”)
Print(“The book name is %s and author name is %s” %(y,z))
Exercise 2
WAP to prompt the user to enter his name through
keyboard and assign the entered name to a variable.
Use %s to print the name concatenated with the string
“your name is”
22
Example
Exercise: Write a program to make the addition of two float
numbers.
num1 = 1.5
num2 = 6.3
# Add two numbers
sum = num1 + num2
# Display the sum
print(sum)
23
Strings
string: A sequence of text characters in a program.
Strings start and end with quotation mark " or apostrophe ' characters.
Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"
A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."
A string can represent characters by preceding them with a backslash.
\t tab character
\n new line character
\" quotation mark character
\\ backslash character
Example: "Hello\tthere\nHow are you?"
24
Strings
Strings are sequence of characters.
str1 = “this is a string”
str2 = “783”
str3 = “ ”
Str4 = “34%^%#323”
Indexes
Characters in a string are numbered with indexes starting at 0:
Example:
name = “Lovely Professional University"
index 0 1 2 3 4 5 6 7
character L O v e L y P
Accessing an individual character of a string:
variableName [ index ]
Example:
print(name[0])
Output:
L
26
Escape Sequences
Str1= “The “Python Complete reference” Writen
by Martin C. Brown” # Results an error
Str1 = “The \“Python Complete reference\”
Writen by Martin C. Brown” # No error
Access Characters by Index
X = “books”
Print(x[1]) # prints o
Print(x[4]) # prints s
Print(x[:3]) #prints boo
Print(x[4:]) #prints s
Print(x[2:4] #prints ok
String Methods
Length of a string
X = “books”
Y = len(x) # prints 5
Convert a string to lower case or upper case
x = “BOOKS”
Y = “books”
Print(x.lower()) # prints books
Print(y.upper()) # prints BOOKS
String Operations
String concatenation
x = “my ” + “book”
print(x) # prints my book
Repetion
x = “book ”*2
Print(x) # prints book book
String Slicing
Indexing
Example 3
Print a string ‘LPU’ surrounded by single quotes.
Print a string “LPU” surrounded by double quotes
Let us create a variable X and assign it the string
“Lovely Professional University”.
print “v” from the above created string.
Print “University” from above created variable contents.
Print “Professional” from above created string.
Print “Lovely” from above created string.
Print the length of the string “University”
31
Program Control Flow : if Statement
if statement: Executes a group of statements only if a certain
condition is true. Otherwise, the statements are skipped.
Syntax:
if condition:
statements
Example:
gpa = 3.4
if gpa > 2.0:
print "Your application is accepted."
32
if/else
if/else statement: Executes one block of statements if a certain
condition is True, and a second block of statements if it is False.
Syntax:
if condition:
statements
else:
statements
Example:
percentage = int(input(“Enter Your percentage”)) if percentage > 2.0:
if(percentage > 60):
print “You are eligible for admission!"
else:
print “Sorry Your application is denied."
33
Multiple conditions can be chained with elif ("else if"):
if condition:
statements
elif condition:
statements
else:
statements
34
if /else Example
Syntax Code
If (condition) Marks = 80
….. If (marks > 70):
Elif(condition) print(“First Division)
…. elif(marks > 50) and (marks <= 70):
Else print(“second Division”)
….. elif(marks > 40) and marks <= 50):
print(“Third Division”)
Else:
print(“fail”)
Example 2
# program to check if the input number is odd or even.
# A number is even if division by 2 give a remainder of 0.
# If remainder is 1, it is odd number.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("%d is Even" %(num))
else:
print("%d is Odd" %(num))
36
Exercise 4
Use input function to get the user name from keyboard.
Assign the length of username to a variable.
Create a set of statements that prints “your name is less than 4
characters”, if the name is less than 4 characters, “your name is
greater than 4 characters and less than 10 characters”, if the name
between 4 and 10 characters and prints “your name is very long” if
the user’s name does not trigger the other
37
Exercise
1. Write a python program to get your name and age from
keyboard and then print it.
2. Write a python program to prompt user to input two numbers,
add the numbers and then print the result on screen.
3. Write a Python Program to Swap the value of two Variables
4. Python Program to Check if a Number is Positive, Negative or 0
5. Write a python program to enter your marks from keyboard and
then compute your division.
6. Write a Python Program to calculate the square root of a number
38
Part -2
39
Lists
A list is a collection of different element types.
Lists are created by using square brackets:
A list assigns the collection of values to a single
variable.
Variable = [value 1, value 2, value 3 …]
X = [4, 1.8, 2, “amar”]
Print(X[2]) # print 2
40
Lists
Reassign a value to an index of List
x[2] = 10
.append() method is used to add an element to the end
of list.
x.append(89)
.insert() is used to insert the elements anywhere in the
list.
x.insert(1, “LPU”)
.remove() method is used to remove the elements from
the lists.
x.remove(89)
41
List
.pop() method is used to remove an element from
list using index.
x.pop(2)
42
Tuples are like lists
Tuples are another kind of sequence that function
much like a list - they have elements which are
indexed starting at 0
>>> >>> for iter in y:
x = ('Glenn', 'Sally', 'Joseph')
>>> print x[2] Joseph ... print iter
>>> y = ( 1, 9, 2 ) ...
>>> print(y) 1
(1, 9, 2) 9
>>> print max(y) 2
9 >>>
Tuples
Unchanging Sequences of Data
Enclosed in parentheses:
tuple1 = (“This”, “is”, “a”, “tuple”)
print(tuple1)
This prints the tuple exactly as shown
Print(tuple1[1])
Prints “is” (without the quotes)
44
Tuples : Example
Let us create a tuple variable X and assign 4 integers to it.
Access 2nd variable of the tuple and assign it to another variable.
Print a slice comprised of first two variables of the tuple.
Use the for loop which iterates through the created tuple and print
all the values of tuples in different lines.
45
The for loop
for loop: Repeats a set of statements over a group of values.
Syntax:
for variableName in groupOfValues:
statements
We indent the statements to be repeated with tabs or spaces.
variableName gives a name to each value, so you can refer to it in the statements.
groupOfValues can be a range of integers, specified with the range function.
Example:
for x in range(1, 6):
print x, "squared is", x * x
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
46
range
The range function specifies a range of integers:
range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
It can also accept a third value specifying the change between values.
range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step
Example:
for x in range(5, 0, -1):
print x
print "Blastoff!"
Output:
5
4
3
2
1
Blastoff!
47
For loop
X = [4, “amar”, 8, 1, 10]
For elements in x
Print(elements)
48
List Example
49
Matrix Manipulation with NumPy
Addition of two matrices :
Code :
import numpy as np
x = np.array([3,2])
y = np.array([4,4])
Z=x+y
Print(z)
50
Exercise
Create a variable and assign it a tuple of 4 integers.
Access the second variable from the above created tuple and print
it.
Print a slice comprised of first two integers from the created tuple.
Print a slice comprised of middle two integers from the created
tuple.
Print a slice comprised of last two integers from the created tuple.
Use a for loop to iterate though the tuple and print each element of
the tuple
51
while
while loop: Executes a group of statements as long as a condition is True.
good for indefinite loops (repeat an unknown number of times)
Syntax:
while(condition):
statements
Example:
number = 1
while number < 200:
print number,
number = number * 2
Output:
1 2 4 8 16 32 64 128
52
Lab Exercise
Write a python program for matrix subtraction using for loop.
Python program to find the multiplication table (from 1 to 10)
Program to display the Fibonacci sequence up to n-th term where n
is provided by the user.
Fibonacci series: 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34
Write a python program to insert and delete elements in a list.
Write a program using lists to implement linear search.
Using a while loop print list of odd numbers.
53
Dictionaries
Dictionaries stores the data in key values.
Example:
d = {1:’amar’, 2:’ygi’, 3:10}
print(d.keys())
d.update({8:"ygi"})
Print(d[8])
54
Python Functions
• There are two kinds of functions in Python.
• Built-in functions that are provided as part of Python -
input(), float(), int() ...
• Functions that we define ourselves and then use
Stored (and reused) Steps
def hello(): Program:
print 'Hello'
def thing(): Output:
print 'Fun' print 'Hello’
print 'Fun’
Hello
hello()
thing()
Fun
print 'Zip’ Zip
print “Zip” thing() Hello
Fun
hello()
We call these reusable pieces of code “functions”.
Function Definition
• In Python a function is some reusable code that takes
arguments(s) as input does some computation and
then returns a result or results
• We define a function using the def reserved word
• We call/invoke the function by using the function
name, parenthesis and arguments in an expression
Functions
Function definition:
def funct():
print("My first function program")
Call a Function:
funct()
58
Defining and Calling a function with Multiple
parameter
Function definition:
def funct(a, b, c):
d=a*b
print(c + d)
Call a Function:
funct(8, 4, 5 )
59
Built in Functions
Abs() # returns a non-negative value
x = abs(-3) # x is assigned the value 3
Type() # returns the type of a parameter in the function
Type(3) # returns int
max()
X = max(4, 1, 1.6, 8) # returns 8 to x
min()
X = min(4, 1, 1.6, 8) # returns 1 to x
60
Function : Example
#Write a Python program to sum all the items in a list
def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))
61
Functions : Example
def add(x, y):
return x + y
def subtract(x, y):
return x – y
print("Select operation.")
print("1.Add")
print("2.Subtract")
choice = input("Enter choice(1/2):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
else:
print("Invalid input")
62
Exercise : Functions
Create a function that prints “this is function 1”.
Create second function that take a ineger parameter returns the
integer multiplied by 2.
63
Sqrt(18) # produced an error
Generic Import
Import math
Math.sqrt(18) # it works
Function import
From math import sqrt
Sqrt(18)
64
Importing Modules
import os
print(os.getcwd()) #prints current path
print(os.mkdir("test_amar"))
print(os.rename("test_amar","testing"))
print(os.rmdir("testing"))
65
Excercise
Write a Program to make a simple calculator that can add, subtract,
multiply and divide using functions.
66