Download as pdf or txt
Download as pdf or txt
You are on page 1of 106

Introduction to Python

Programming

Dr. A. Ajina
Associate Professor
Department of AI &ML
RIT
DEVOTION TO ENLIGHTENMENT

A set of stored instructions that specifies


a computation.
DEVOTION TO ENLIGHTENMENT

Components of Program
• input Get data from the keyboard, a file, or some other
device.
• output Display data on the screen or send data to a file
or other device.
• math Perform basic mathematical operations like
addition and multiplication.
• conditional execution Check for certain conditions and
execute the appropriate sequence of statements.
• repetition Perform some action repeatedly, usually
with some variation.

4
DEVOTION TO ENLIGHTENMENT

What is Programming

The act of writing these instructions down


and getting the instructions to be
correct programming
DEVOTION TO ENLIGHTENMENT

Introduction to Python Programming

• Python is a general-purpose interpreted, interactive, object-


oriented, and high-level programming language.
• It was created by Guido van Rossum during 1985- 1990.
Python is named after a TV Show called ‘Monty Python’s
Flying Circus’ and not after Python- the snake.
DEVOTION TO ENLIGHTENMENT

Features of Python
DEVOTION TO ENLIGHTENMENT

Why is Python best for beginners?

• Simple Elegant Syntax


• Easy Learning
• High Expressiveness
• Good Marketable Skill
DEVOTION TO ENLIGHTENMENT

 https://www.menti.com/alr3yicfgx8p
DEVOTION TO ENLIGHTENMENT

Programming Editors
DEVOTION TO ENLIGHTENMENT

Installation demo
DEVOTION TO ENLIGHTENMENT

The Python programming language


• High-level language.
• The engine that translates and runs Python is called
the
Python Interpreter.
Immediate mode Script mode

1
1
DEVOTION TO ENLIGHTENMENT

What is debugging?
Programming errors are called bugs and the process of tracking them down and
correcting them is called debugging.
• Runtime errors
• Syntax errors • Error does not appear
• Syntax refers to the structure until you run the
of a program and the rules program. These errors
about that structure. are also called
• Python will display an error exceptions because
message and quit, and you will they usually indicate
not be able to run your that something
program. exceptional (and bad)
has happened.
• Semantic errors
• If there is a semantic error in your
program, it will run successfully, in the
sense that the computer will not
generate any error messages, but it will
not do the right thing.
DEVOTION TO ENLIGHTENMENT

The first program

Write a program to say Hello World!

print("Hello, World!")
DEVOTION TO ENLIGHTENMENT

Write a program welcome every one?


print(“ Welcome Every one")
Write a Program welcome a particular Student ?
print(“Welcome john")
VARIABLES, EXPRESSIONS AND STATEMENTS

1
5
DEVOTION TO ENLIGHTENMENT

Variables

Variables are reserved memory location to store values


 num = 5
 print(num)
# Output: 5
 my_name = “ajina"
 print(my_name)
# Output: ajina
 my_message = "Hello, " + "World!"
 print(my_message) # Output: Hello, world!
DEVOTION TO ENLIGHTENMENT

Variables

• A variable is a name that is


associated with a value.
• The assignment operator ‘=‘ is used to
assign values to variables.
DEVOTION TO ENLIGHTENMENT

Rules for writing Variable names

1. Variable names can be a combination of letters in lowercase (a to z)


or uppercase (A to Z) or digits (0 to 9) or an underscore (_).
2. Variable names cannot start with a digit.
3. Keywords cannot be used as Variable names .
4. We cannot use special symbols like !, @, #, $, % etc. in Variable
names .
5. Variable names can be of any length.
DEVOTION TO ENLIGHTENMENT

Keywords and Statements


• A statement is an instruction that the
Python interpreter can execute.
• Keywords: if, else, import
DEVOTION TO ENLIGHTENMENT

 https://www.menti.com/alrk6zi4t2b5
DEVOTION TO ENLIGHTENMENT

Illegal Variable names

 >>> 76trombones = 'big parade'


Syntax Error: invalid syntax
 >>> more@ = 1000000
Syntax Error: invalid syntax
 >>> class = 'Advanced Theoretical Zymurgy'
Syntax Error: invalid syntax
DEVOTION TO ENLIGHTENMENT

 https://www.menti.com/alv91wc7mxik
DEVOTION TO ENLIGHTENMENT

Values and data types


• A value is one of the fundamental
things— like a letter or a number—that a
program manipulates.
• Values are classified into different
classes or data types: 4 is an integer,
and "Hello, World!" is a string,
• Python has a function called type
which can tell you.
DEVOTION TO ENLIGHTENMENT

What are the different Data Types?

1. Numbers: Number data types store numeric values. Number objects are created
when you assign a value to them.
2. Strings: Strings in Python are identified as a contiguous set of characters
represented in the quotation marks. Python allows either pair of single or double
quotes.
3. Lists: Lists are the most versatile of Python's compound data types. A list
contains items separated by commas and enclosed within square brackets ([ ]).
4. Tuples: A tuple is another sequence data type that is similar to the list. A tuple
consists of a number of values separated by commas. Unlike lists, however,
tuples are enclosed within parenthesis.
5. Dictionary: Python's dictionaries are kind of hash-table type. They work like
associative arrays or hashes found in Perl and consist of key- value pairs. A
dictionary key can be almost any Python type, but are usually numbers or
strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed within curly braces.
DEVOTION TO ENLIGHTENMENT

Data types
DEVOTION TO ENLIGHTENMENT

String
 A string represents a sequence of characters or
alphabets. It can be used to store text-based
information. The string is like a collection of letters,
words, or sentences.
 # create a string using double quotes
 string1 = "Python programming"
 # create a string using single quotes
 string2 = 'Python programming'
 name = "Rahul"
 print(name)
DEVOTION TO ENLIGHTENMENT

Example

Write a program to greet your friend name


“John”
DEVOTION TO ENLIGHTENMENT

Example

 Write a program to greet your friend name “John”


 greet = "Hello, Good Afternoon"
 name = "John"
 # using + operator
 result = greet + name
 print(result)
 # Output: Hello, Good Afternoon John
DEVOTION TO ENLIGHTENMENT

Program to access the elements


from the String
 greet = 'hello'
 # access 1st index element
 print(greet[1]) # "e“
 # access 4th last element
 print(greet[-4]) # "e“
 # access character from 1st index to 3rd index
 print(greet[1:4]) # "ell"
DEVOTION TO ENLIGHTENMENT

Integer

 An integer represents whole numbers without


decimals.
 age = 10
 print(age)
DEVOTION TO ENLIGHTENMENT

Add Two Integers in Python


 # To add two numbers
 num1 = 15
 num2 = 12
 # Adding two nos
 sum = num1 + num2
 # printing values
 print("Sum of", num1, "and", num2 , "is", sum)
DEVOTION TO ENLIGHTENMENT

Float

 A float represents numbers with decimal points. It


represents a number with a decimal or fraction. It can
be used to represent measurements.
 height = 5.5
 print(height)
DEVOTION TO ENLIGHTENMENT

Program

 Write a Python program that calculates the area of


a circle based on the radius value is 5.3.

pie = 3.14
Radius = 5 .3
area_of_the_circle = pie * Radius * Radius
print (" The area of the given circle is: ", area_of_
the_circle)
DEVOTION TO ENLIGHTENMENT

Boolean

 A Boolean (bool) represents two possible values: True or


False. It deals with only true or false.
 is_Delhi_Capital_of_india = True
 print(is_Delhi_Capital_of_india)
DEVOTION TO ENLIGHTENMENT

Boolean values and expressions


• A Boolean expression is an expression
that evaluates to produce a result
which is a Boolean value.
DEVOTION TO ENLIGHTENMENT

List

 A list is an ordered collection of items. It can be


used to store multiple values of different data
types. A list is like a collection of items in a
basket. It can contain different things, such as
numbers, words, or even other lists.
 []
 list()
Example
 fruits = ["apple", "banana", "orange"]
 print(fruits)
DEVOTION TO ENLIGHTENMENT

Example

 list1=["hello",1,4,8,"good"]
 print(list1)
 # assigning values ("hello" is replaced with "morning")
 list1[0]="morning"
 print(list1)
 print(list1[4])
 print(list1[-1])
 # list also allow negative indexing
 print(list1[1:4]) # slicing
 list2=["apple","mango","banana"]
 print(list1+list2) # list concatenation
DEVOTION TO ENLIGHTENMENT

Program

Write a Python program to create a list.


DEVOTION TO ENLIGHTENMENT

Program

Write a Python program to create a list.


x = []
print(x)
#Create an empty tuple with tuple() function built-
in Python
list1 = list()
print(list1)
DEVOTION TO ENLIGHTENMENT

Tuple

 A tuple is similar to a list but is immutable,


meaning its elements cannot be changed
once defined. It is like a fixed sequence of
items. Once it’s set, the items cannot be
changed. It’s like having a locked box with
things inside.
 ()
 tuple()
Example:
 coordinates = (3, 4)
 print(coordinates)
DEVOTION TO ENLIGHTENMENT

Program

 Write a Python program to create a tuple.


DEVOTION TO ENLIGHTENMENT

Program

Write a Python program to create a tuple.


#Create an empty tuple
x = ()
print(x)
#Create an empty tuple with tuple() function built-in
Python
tuplex = tuple()
print(tuplex)
DEVOTION TO ENLIGHTENMENT

Program

 Write a Python program to create a tuple with different data types.


DEVOTION TO ENLIGHTENMENT

Program

 Write a Python program to create a tuple with different data types.


 #Create a tuple with different data types
 tuplex = ("tuple", False, 3.2, 1)
 print(tuplex)
DEVOTION TO ENLIGHTENMENT

Program

 Write a Python program to get the 4th element from the last element of a
tuple.
DEVOTION TO ENLIGHTENMENT

Program

 Write a Python program to get the 4th element from the last element of a
tuple.
 #Get an item of the tuple
 tuplex = ("w", 3, "r", "e", "s","c", "e")
 print(tuplex)
 #Get item (4th element)of the tuple by index
 item = tuplex[3]
 print(item)
DEVOTION TO ENLIGHTENMENT

Dictionary

 A dictionary is an unordered collection of key-value pairs. It is useful for


storing and retrieving data using specific keys. A dictionary is like a book
with definitions. It has words (keys) and their meanings (values). Each
word has a unique meaning.
 person = {"name": "Bob", "age": 12, "country": "USA"}
 print(person)
DEVOTION TO ENLIGHTENMENT

Set
 A set is an unordered collection of unique elements. It is a
data type that allows storing multiple values but
automatically eliminates duplicates.
 # create a set named student_id
 student_id = {112, 114, 116, 118, 115}
 # display student_id elements
 print(student_id)
 # display type of student_id
 print(type(student_id))
DEVOTION TO ENLIGHTENMENT

Values and data types examples


>>> type("Hello, >>>
World!") type("17") >>>
<class ’str’> <class ’str’> type(3.2)
>>> type(17) >>> <class
<class ’int’> type("3.2") ’float’>
<class ’str’>
>>> type(’This is a string.’)
<class ’str’>
>>> type("And so is
this.")
<class ’str’>
>>> type("""and
this.""")
<class ’str’>
>>> type(’’’and even 4
this...’’’) 9
<class ’str’>
DEVOTION TO ENLIGHTENMENT

Type converter functions

• >>> int(3.14)
•3
• >>> float(17)
• 17.0
• >>>
float("123.45")
• 123.45
• >>> str(17)
• ’17’
• >>> str(123.45) 16

• ’123.45’
DEVOTION TO ENLIGHTENMENT

Quiz

 What is the output of the following code?


temp=“python”
print(type(temp))
temp=20
print(type(temp))

a)<class ‘int’><class ‘str’>


b)<class ‘str’><class ‘int’>
c)None
d)Error
DEVOTION TO ENLIGHTENMENT

Asking the user for input


In order to get the input from the user through
the keyboard Python provides a built- in
function called input. When this function is
called, the program stops and waits for the user
to type something. When the user presses
Return or Enter, the program resumes and
input returns what the user typed as a string.
DEVOTION TO ENLIGHTENMENT

Input

• There is a built-in function in Python


for getting input from the user:
• n = input("Please enter your name: ")
DEVOTION TO ENLIGHTENMENT

How to take integer input in Python?


DEVOTION TO ENLIGHTENMENT

How to take integer input in Python?


Example:
 # take input from user
 num = input()
 # print data type
 print(type(num))
 # type cast into integer
 num = int(num)
 # print data type
 print(type(num))
DEVOTION TO ENLIGHTENMENT

Program to add two numbers


DEVOTION TO ENLIGHTENMENT

Program to add two numbers

 number1 = input("First number: ")


 number2 = input("Second number: ")

 sum = int(number1) + int(number2)

 print("The sum of two is" , sum)


DEVOTION TO ENLIGHTENMENT

Example

 Write a program to greet your friend whom you have seen.


DEVOTION TO ENLIGHTENMENT

Example

 Write a program to greet your friend whom you have seen.


 greet = "Hello, Good Afternoon"
 name = input(“Enter your friend name”)

 # using + operator
 result = greet + name
 print(result)

 # Output: Hello, Good Afternoon Rani


DEVOTION TO ENLIGHTENMENT

Self -test

• How many lines of screen output is


displayed by the following,
print('apple\nbanana\ncherry\npeach')
(a) 1 (b) 2 (c) 3 (d) 4

• Which of the following are valid string


literals in Python.
• (a) "Hello" (b) 'hello' (c) "Hello' (d)
'Hello there' (e) ''
DEVOTION TO ENLIGHTENMENT

Evaluating expressions

• An expression is a combination of values,


variables, operators, and calls to
functions.

>>> 1 + 1
2
>>>
len("hello")
5
DEVOTION TO ENLIGHTENMENT

Program to find the simple Interest


DEVOTION TO ENLIGHTENMENT

 Program to find the simple Interest


DEVOTION TO ENLIGHTENMENT

Operators and operands

• Operators are special tokens that represent


computations like addition, multiplication
and division.
• The values the operator uses are called
operands.
• The tokens +, -, and *, and the use of
parenthesis for grouping, mean in Python
what they mean in mathematics. The asterisk
(*) is the token for multiplication, and ** is
the token for exponentiation.
DEVOTION TO ENLIGHTENMENT

Operators
DEVOTION TO ENLIGHTENMENT

Operations on strings

• Interestingly, the ‘+’ operator does work with


strings, but for strings, the + operator
represents concatenation, not addition.
• The ‘*’ operator also works on strings; it
performs repetition.
fruit = "banana" ’Fun’*3 is
baked_good = " nut bread" ’FunFunFun’.
print(fruit + baked_good)

The output of this program is banana nut bread.


DEVOTION TO ENLIGHTENMENT

Order of operations
 When more than one operator appears in an expression, the
order of evaluation depends on the rules of precedence.
 PEMDAS order of operation is followed in Python :
 Parentheses have the highest precedence and can be used to
force an expression to evaluate in the order you want.
 Exponentiation has the next highest precedence,
 Multiplication and Division have the same precedence,
which is higher than
 Addition and Subtraction, which also have the same
precedence.
 Operators with the same precedence are evaluated from left
to right.
DEVOTION TO ENLIGHTENMENT

Quiz

 In the Python statement x = a + 5 - b:


a and b are ________
a + 5 - b is ________
1. Term, a group
2. Operands, an expression
3. Operands, an equation
4. Operators, a statement
DEVOTION TO ENLIGHTENMENT

Quiz

 What is the value of the expression 1 + 2 ** 3 * 4?


• 4097

• 33

• 108

• 36
DEVOTION TO ENLIGHTENMENT

Arithmetic operators

 x = 15
 y=3
 a=2
 b=3
 print(x + y) #addition
 print(x - y) #substraction
 print(x * y)#Multiplication
 print(x /y)#division
 print(x %y)#modulus
 print(a ** b)#Exponentiation
 print(x //y)#Floor
DEVOTION TO ENLIGHTENMENT

Quiz

 What is the value of the expression 100 / 25?

4
 4.0
DEVOTION TO ENLIGHTENMENT

Assignment operators

 Assignment operators are used to assign values to variables


 x=5
 x += 3
 print(x)
 x -= 3
 print(x)
 x *= 3
 print(x)
 x /= 3
 print(x)
DEVOTION TO ENLIGHTENMENT

 x %= 3
print(x)
 x //= 3
print(x)
 x **= 3
print(x)
 x &= 3
print(x)
 x>>= 3
print(x)
x <<= 3
print(x)
DEVOTION TO ENLIGHTENMENT

Comparison operators

 Comparison operators are used to compare two values


 x=5
 y=3
 print(x ==y)
 print(x =! y)
 print(x <= y)
 print(x >= y)
 print(x < y)
 print(x > y)
DEVOTION TO ENLIGHTENMENT

Logical operators

 Logical operators are used to combine conditional statements


 x=5

 print(x > 3 and x < 10)


 print(x < 5 or x < 4)
 print(not(x < 5 and x < 10))
DEVOTION TO ENLIGHTENMENT

Identity operators
 Identity operators are used to compare the objects, not if they
are equal, but if they are actually the same object, with the
same memory location
 x = ["apple", "banana"]
 y = ["apple", "banana"]
 z=x
 print(x is z)
 # returns True because z is the same object as x
 print(x is y)
 # returns False because x is not the same object as y, even if
they have the same content
 print(x == y)
 # to demonstrate the difference betweeen "is" and "==": this
comparison returns True because x is equal to y
DEVOTION TO ENLIGHTENMENT

 print(x is not z)
 # returns False because z is the same object as x
 print(x is not y)
 # returns True because x is not the same object as y, even if they have the
same content
 print(x != y)
 # to demonstrate the difference betweeen "is not" and "!=": this comparison
returns False because x is equal to
DEVOTION TO ENLIGHTENMENT

Membership operators
 Membership operators are used to test if a sequence is
presented in an object
 x = ["apple", "banana"]
 print("banana" in x)
 # returns True because a sequence with the value
"banana" is in the list
 print("pineapple" not in x)

 # returns True because a sequence with the value


"pineapple" is not in the list
DEVOTION TO ENLIGHTENMENT

Bitwise operators

 Bitwise operators are used to compare (binary) numbers


AND
 print(6 & 3)
 2
 The & operator compares each bit and set it to 1 if both are 1, otherwise it is
set to 0:
 6 = 0000000000000110
 3 = 0000000000000011
 --------------------
 2 = 0000000000000010
 ====================
DEVOTION TO ENLIGHTENMENT

OR

 print(6 | 3)
 7
 The | operator compares each bit and set it to 1 if one or both is 1,
otherwise it is set to 0:
 6 = 0000000000000110
 3 = 0000000000000011
 --------------------
 7 = 0000000000000111
 ====================
DEVOTION TO ENLIGHTENMENT

XOR

 print(6 ^ 3)
 5
 The ^ operator compares each bit and set it to 1 if only one is 1, otherwise
(if both are 1 or both are 0) it is set to 0:

 6 = 0000000000000110
 3 = 0000000000000011
 --------------------
 5 = 0000000000000101
 ====================
DEVOTION TO ENLIGHTENMENT

NOT

 print(~3)
 The ~ operator inverts each bit (0 becomes 1 and 1 becomes 0).
 Inverted 3 becomes -4:
 3 = 0000000000000011
 -4 = 1111111111111100
DEVOTION TO ENLIGHTENMENT

Flow Control Statement

SELECTION ITERATION
DEVOTION TO ENLIGHTENMENT

CONDITIONAL STATEMENT– if else

: Colon Must
if first condition:
first body
elif second condition:
second body
elif third condition:
third body
else:
fourth body
DEVOTION TO ENLIGHTENMENT
DEVOTION TO ENLIGHTENMENT

EXAMPLES – if STATEMENT

else is missing,
it is an optional
statement

OUT PUT
DEVOTION TO ENLIGHTENMENT

EXAMPLE –if else STATEMENT

: Colon Must

else is
used

OUT PUT
DEVOTION TO ENLIGHTENMENT

EXAMPLE

 Write a PYTHON program to find a largest of two numbers.


DEVOTION TO ENLIGHTENMENT

EXAMPLE

 Write a PYTHON program to find a largest of two numbers.

 number1 = input("First number: ")


 number2 = input("Second number: ")
 if number1>number2:
 print(“ The largest no is: ”,number1)
 else:
 print(“ The largest no is: ”,number1)
DEVOTION TO ENLIGHTENMENT

Program

 Write a python program for simple calculator


DEVOTION TO ENLIGHTENMENT

number_1 = int(input('Enter your first number: '))


number_2 = int(input('Enter your second number: ‘))
Operator=input(“Enter valid operator such as +,-,*,/”)
if operator == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operator == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operator == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operator == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
else:
print('You have not typed a valid operator, please run the program again.')
DEVOTION TO ENLIGHTENMENT

3. ITERATION OR LOOPING

Python provides two kinds of


loops & they are,

while loop

for loop
DEVOTION TO ENLIGHTENMENT

while loop

A while loop allows general repetition


based upon the repeated testing of a
Boolean condition
The syntax for a while loop in Python is as
follows:
while condition: : Colon Must
body
Where, loop body contain the single
statement or set of statements
(compound statement) or an empty
statement.
DEVOTION TO ENLIGHTENMENT

while loop

The loop iterates while the expression evaluates


to true, when expression becomes false the loop
terminates.

FLOW CHART

while loop
DEVOTION TO ENLIGHTENMENT

while loop – Programming example


DEVOTION TO ENLIGHTENMENT

while loop - programs


# Natural Numbers generation

OUTPUT
DEVOTION TO ENLIGHTENMENT

while loop - programs


# Calculating Sum of Natural Numbers

OUTPUT
DEVOTION TO ENLIGHTENMENT

Program

 Write a PYTHON program to print odd or even numbers up to n


DEVOTION TO ENLIGHTENMENT

Program

 Write a PYTHON program to print odd or even numbers up to n


 number=int(input("Enter an number"))
 i=1
 while i<=number:
 if i%2==0:
 print("Even no",i)
 else:
 print("Odd no",i)
 i=i+1
DEVOTION TO ENLIGHTENMENT

for LOOP

Python’s for-loop syntax is a more convenient


alternative to a while loop when iterating through a
series of elements. The for-loop syntax can be used
on any type of iterable structure, such as a list,
tuple str, set, dict, or file
Syntax or general format of for loop is,

for element in iterable:


body
DEVOTION TO ENLIGHTENMENT

for LOOP

Till the list


exhaust for loop
will continue to
execute.

OUTPUT
DEVOTION TO ENLIGHTENMENT

for LOOP - range KEYWORD

The range() function returns a sequence of numbers,


starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.

range(start, stop, step)

x = range(3, 6)
for n in range(3,6):
OR for n in x:
print(n)
print(n)
DEVOTION TO ENLIGHTENMENT

for LOOP - range KEYWORD

#Generating series of numbers

OUTPUT
DEVOTION TO ENLIGHTENMENT

for LOOP - range KEYWORD


#Generating even numbers

OUTPUT
DEVOTION TO ENLIGHTENMENT

 https://www.menti.com/almkaea6w7og
DEVOTION TO ENLIGHTENMENT

Thank You
Happy Learning

You might also like