0% found this document useful (0 votes)
3 views56 pages

Resource 20250120143018 Python Intro(Datatype,Operator,Variable)

The document provides an overview of algorithms, flowcharts, and programming concepts, particularly focusing on Python as a high-level programming language. It covers essential topics such as data types, variables, operators, and methods for manipulating lists, along with examples and explanations of Python syntax. Additionally, it discusses the importance of comments, keywords, and the structure of Python programs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views56 pages

Resource 20250120143018 Python Intro(Datatype,Operator,Variable)

The document provides an overview of algorithms, flowcharts, and programming concepts, particularly focusing on Python as a high-level programming language. It covers essential topics such as data types, variables, operators, and methods for manipulating lists, along with examples and explanations of Python syntax. Additionally, it discusses the importance of comments, keywords, and the structure of Python programs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 56

WHAT IS AN ALGORITHM?

• To write a logical step-by-step method to solve the identified problem is called


algorithm.
• In other words, an algorithm is a procedure for solving problems.
• In order to solve a mathematical or computer problem, this is the first step of
the procedure.
• An algorithm includes calculations, reasoning and data processing.
• Algorithms can be presented by natural languages, pseudocode and flowcharts,
etc.
WHAT IS A FLOWCHART?
• A flowchart is the graphical or pictorial representation of an algorithm with the
help of different symbols, shapes and arrows in order to demonstrate a process
or a program.
• While computers work with numbers at ease, humans need visual
representations to understand the information well and communicate it
effectively.
• Thus, flowcharts are used to break a process into smaller parts and elaborate it
using visual representations.
• Several standard graphics are applied in a flowchart:
EXAMPLE
Algorithm to Print 1 to 20:
Step 1: Initialize X as 0
Step 2: Increment X by 1
Step 3: Print X
Step 4: If X is less than 20
then go back to step 2.
WHAT IS A PROGRAM?
• A computer program is a collection of instructions that perform a specific
task when executed by a computer.
• It is usually written in a programming language.
• A programming language is a vocabulary and set of grammatical rules for
instructing a computer to perform specific tasks. There are many different
programming languages such as BASIC, Pascal, C, C++, Java, Haskell, Ruby,
Python, etc.
WHAT IS PYTHON?
• Python is a High-Level
Multipurpose
Interpreted
Programming language
that is becoming
popular day by day.
• Python is a cross-
platform programming
language, meaning, it
runs on multiple
platforms like Windows,
MacOS, Linux and has
even been ported to
the Java and .NET
virtual machines.
WHY PYTHON FOR AI?
APPLICATIONS OF PYTHON
PYTHON-KNOW MORE
• Python shell can be used in two ways, viz., interactive mode and script mode.
• Where Interactive Mode, as the name suggests, allows us to interact with OS;
script mode lets us create and edit Python source file.
• When we install Python, an IDE named IDLE is also installed. We can use it to
run Python on our computer.
• IDLE (GUI integrated) is the standard, most popular Python development
environment.
• IDLE is an acronym of Integrated Development Environment. It lets one edit,
run, browse and debug Python Programs from a single interface.
• This environment makes it easy to write programs.
• Python treats every value or data item whether numeric, string, or other type
as an object in the sense that it can be assigned to some variable or can be
passed to a function as an argument.
PYTHON STATEMENTS
• Instructions written in the source code for execution are called statements.
• There are different types of statements in the Python programming language
like Assignment statement, Conditional statement, Looping statements etc.
• These help the user to get the required output.
• For example, n = 50 is an assignment statement.
Multi-line statement
• In Python, end of a statement is marked by
a newline character.
• However, Statements in Python can be
extended to one or more lines using
parentheses (), braces {}, square brackets [],
semi-colon (;), continuation character slash
(\). When we need to do long calculations
and cannot fit these statements into one
line, we can make use of these characters.
PYTHON COMMENTS
• A comment is text that
doesn't affect the
outcome of a code, it is
just a piece of text to let
someone know what you
have done in a program or
what is being done in a
block of code.
• In Python, we use the
hash (#) symbol to start
writing a comment.
PYTHON KEYWORDS

Keywords are the


reserved words in
Python used by Python
interpreter to
recognize the structure
of the program.
PYTHON IDENTIFIERS

• Always name identifiers


that make sense.
• While, c = 10 is valid.
Writing count = 10 would
make more sense
• Multiple words can be separated
using an underscore, for example
this_is_a_long_variable
PYTHON VARIABLES
• A variable is a named location
used to store data in the
memory.
• It is helpful to think of variables
as a container that holds data
which can be changed later
throughout programming.
• For example, x=10, y=45
• Python is a case-sensitive
language. This means, Variable
and variable are not the same.
• Assignment operator (=) is used in
Python to assign values to
variables.
PYTHON VARIABLES
• Constants:A constant is a type of variable
whose value cannot be changed.
• Think of constants as containers that hold
information which cannot be changed later.
• 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 the main file.
• Inside the module, constants are written in
all capital letters and underscores separating
the words.
PYTHON VARIABLES
PYTHON VARIABLES

Write a program to display Write a Python program to find the area


values of variables in Python. of a rectangle given that its length is 10
units and breadth is 20 units.
#To display values of variables
message = "Keep Smiling" #To find the area of a rectangle
print(message) length = 10
userNo = 101 breadth = 20
print('User Number is', userNo) area = length * breadth
Output: print(area)
Keep Smiling Output:
User Number is 101 200
PYTHON DATATYPES

• 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.
PYTHON DATATYPES
1. Number data type stores Numerical Values.
• These are of three different types:
a) Integer
• Range of an integer in Python can be from -2147483648 to 2147483647.
• Integers are the whole numbers consisting of + or – values like 100000, -99.
b) Long Integer- long integer has unlimited range subject to available memory.
c) Float / floating point
• Numbers with fractions or decimal point are called floating point numbers.
• A floating-point number will consist of sign (+,-) sequence of decimals digits
and a dot such as 0.0, -21.9, 0.98333328, 15.2963
2. None -This is special data type with single value.
It is used to signify the absence of value/false in a situation.
It is represented by None.
PYTHON DATATYPES
3. Sequence
• A sequence is an ordered collection of items that can be indexed using square
brackets to access items by their position.
• Three types of sequence data type available in Python are:
a) Strings - String String is an ordered sequence of letters/characters. They are
enclosed in single quotes (‘ ‘) or double (“ “). The quotes are not part of string.
They only tell the computer where the string constant begins and ends. They can
have any character or sign, including space in them.
For example, >>> str1 = 'Hello Friend‘ >>> str2 = "452“
• Strings can be concatenated(joined) or replicated by concatenation
operator(+) and replication operator(*).
• For example, str1 = 'Hello Friend’ str2 = "452”
print(str1+str2) ; Output= Hello Friend452
print(str1*3) ; Output= Hello FriendHello FriendHello Friend
PYTHON DATATYPES
b) Lists - List is also a sequence of values of any type. Values in the list are called
elements / items. These are indexed/ordered. List is enclosed in square brackets.
Example: dob = [19,"January",1990]
#To create a list >>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of list1 >>> print(list1)
output : [5, 3.4, 'New Delhi', '20C', 45]
c) Tuple is a sequence of items separated by commas and items are enclosed in
parenthesis ( ). This is unlike list, where values are enclosed in brackets [ ]. Once
created, we cannot change the tuple.
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
PYTHON DATATYPES
4. Set is an unordered collection of items separated by commas and the items
are enclosed in curly brackets { }. A set is similar to list, except that it cannot
have duplicate entries. Once created, elements of a set cannot be changed.
Example #create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(set1)
Output : {10, 20, 3.14, "New Delhi"}
#duplicate elements are not included in set
>>> set2 = {1,2,1,3}
>>> print(set2)
{1, 2, 3}
PYTHON DATATYPES
5. Mapping is an unordered data type in Python. Currently, there is only one
standard mapping data type in Python called dictionary.
• Dictionary in Python holds data items in key-value pairs. Items in a dictionary
are enclosed in curly brackets { }.
• Dictionaries permit faster access to data. Every key is separated from its value
using a colon (:) sign.
• The keys are usually strings and their values can be any data type.
• In order to access any value in the dictionary, we have to specify its key in
square brackets [ ]. Example #create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
>>> print(dict1['Price(kg)'])
120
MUTABLE AND IMMUTABLE DATA TYPES
• Sometimes we may require to change or update the values of certain variables.
However,for certain data types, Python does not allow us to change the values
once a variable of that type has been created and assigned values.
• Variables whose values can be changed after they are created and assigned are
called mutable.
• Variables whose values cannot be changed after they are created and assigned
are called immutable.
PYTHON OPERATORS
• An operator is used to perform specific mathematical or logical operation on
values. The values that the operators work on are called operands.
• For example, in the expression 10 + num, the value 10, and the variable num
are operands and the + (plus) sign is an operator.
• Python supports several kinds of operators
1. Arithmetic Operators -are used to perform arithmetic operations .
2. Relational Operators- compares the values of the operands on its either side
and determines the relationship among them.
3. Assignment Operators –used to assigns or changes the value of the variable
on its left.
4. Logical Operators-There are three logical operators in Python. These
operators (and, or, not) are to be written in lower case only. The logical
operator evaluates to either True or False based on the logical operands on
either side. By default, all values are True except None.
PYTHON OPERATORS
5. Identity Operators- are used to determine whether the value of a variable is of
a certain type or not. Identity operators can also be used to determine whether
two variables are referring to the same object or not. There are two identity
operators –is, is not
6. Membership Operators: are used to check if a value is a member of the given
sequence or not. There are two membership operators – in , not in
ARITHMETIC OPERATORS
ARITHMETIC OPERATORS
RELATIONAL OPERATORS
ASSIGNMENT OPERATORS
ASSIGNMENT OPERATORS
ASSIGNMENT OPERATORS
LOGICAL OPERATORS
IDENTITY OPERATORS
MEMBERSHIP OPERATORS
OPERATORS PRECEDENCE AND EXPRESSION
• An expression is defined as a combination of constants, variables, and
operators. An expression always evaluates to a value.
Precedence of Operators- Evaluation of the expression is based on precedence of
operators. When an expression contains different kinds of operators, precedence
determines which operator
should be applied first.
• Higher precedence
operator is evaluated
before the lower
precedence operator.
•The unary operators need
only one operand, and they
have a higher precedence
than the binary operators
PYTHON INPUT /OUTPUT AND TYPE
• The input() function prompts the user to enter data. It accepts all user input
as string. The user may enter a number or a string but the input() function
treats them as strings only.

• Python uses the


print() function to
output data to
standard output
device — the
screen.
PYTHON INPUT /OUTPUT AND TYPE
• Type Conversion-The process of converting the value of one data type (integer,
string, float, etc.) to another data type is called type conversion.
• Python has two types of type conversion.
1. Implicit Type Conversion - Python automatically
converts one data type to another data type. This
process doesn't need any user involvement.
2. Explicit Type Conversion: users convert the data
type of an object to required data type by using
predefined functions like int(), float(), str(),
PRACTICE QUESTIONS
PRACTICE QUESTIONS
PRACTICE QUESTIONS
MORE ABOUT LISTS
• List is a sequence of values of any type. Example:
• Values in the list are called elements / items. a = [1,2.3,"Hello"]
• List is enclosed in square brackets
Example:
How to create a list ? #empty list
• A list is created by placing all the empty_list = []
items (elements) inside a square
bracket [ ], separated by commas. #list of integers
age = [15,12,18]
• It can have any number of items
and they may be of different types #list with mixed data types
(integer, float, string etc.). student_height_weight = ["Ansh",5.7,60]
• A list can also have another list as # nested list student marks =
an item. This is called nested lists. ["Aditya", "10-A", [ "english",75]]
HOW TO ACCESS ELEMENTS OF A LIST ?
There are two ways to access
an individual element of a list:
1) List Index- It is the position at
which any element is present in
the list. Index in the list starts
from 0, so if a list has 5
elements the index will start
from 0 and go on till 4. In order
to access an element in a list we
need to use index operator [].
2) Negative Indexing-The index
of -1 refers to the last item, -2 to
the second last item and so on.
HOW TO ACCESS ELEMENTS OF A LIST ?
fruits = ["apple", "banana", "cherry", "date"]
# Accessing elements by index
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: cherry

# Accessing the last element with negative indexing


print(fruits[-1]) # Output: date
print(fruits[-2]) # Output: cherry

# Accessing Value in a nested list


n_list=[“Happy”,[2,0,1,5]]
print(n_list[0][1]) # Output: A
print(n_list[1][3]) # Output: 5
ADDING ELEMENT TO A LIST
We can add an element
to any list using two
methods :

1) Using append()
method - append()
method only works for
addition of elements at
the end of the List.
ADDING ELEMENT TO A LIST
2) Using insert() method – Used for addition of element at the desired position.

• Unlike append()
which takes only
one argument,
insert() method
requires two
arguments
(position, value).
ADDING ELEMENT TO A LIST
3) Using extend() method- this method is used to add multiple elements at the
same time at the end of the list.
REMOVING ELEMENTS FROM A LIST
Elements from a list can removed using two methods :
1) remove() method -Elements can be removed from the List by using built-in
remove() function but an
Error arises if element
doesn't exist in the set.
• It only removes one
element at a time, to
remove range of
elements, iterator is
used.
• Remove method in List
will only remove the
first occurrence of the
searched element
REMOVING ELEMENTS FROM A LIST
2) Using pop() method - Pop() function can also be used to remove and return
an element from the set, but by default it removes only the last element of the
set.
• To remove an
element from a
specific position of
the list, index of the
element is passed as
an argument to the
pop() method.
SLICING OF A LIST
In Python List, there are multiple ways to print the whole List with all the
elements, but to print a specific range of elements from the list, we use Slice
operation. Slice operation is performed on Lists with the use of colon(:)
SLICING OF A LIST
• To print elements from beginning to a range use [:index]
• To print elements from end use [:-index],
• To print elements from specific index till the end use [index:],
• To print elements within a range, use [start index: end index]
• To print whole list with the use of slicing operation, use [:].
• To print whole list in reverse order, use [::-1].
• To print elements of list from rear end, use negative indexes.
# Creating a List Output
List= ['G','O','O','D','M','O', 'R','N','I','N','G'] Initial List: ['G','O','O','D','M', 'O',
print("Initial List: ") 'R','N','I','N','G']
print(List)
# using Slice operation Slicing elements in a range 3-8: ['D', 'M',
Sliced_List = List[3:8] 'O', 'R', 'N']
print("\nSlicing elements in a range 3-8: ")
print(Sliced_List)
SLICING OF A LIST
# Print elements from a Elements sliced from 5th element
# pre-defined point to end till the end: ['M', 'O', 'R', 'N', 'I', 'N', 'G']
Sliced_List = List[5:] print("Elements sliced from
5th element till the end: ")
print(Sliced_List)
# Printing elements from # beginning till end Printing all elements using slice
Sliced_List = List[:] print("\nPrinting all elements operation:
using slice operation: ") print(Sliced_List) ['G','O','O','D','M', 'O', 'R','N','I','N','G']
# Print elements from beginning # to a pre Elements sliced till 6th element from
defined point using Slice last: ['G','O','O','D','M', 'O']
Sliced_List = List[:-6]
print("\nElements sliced till 6th element from last:
")
print(Sliced_List)
SLICING OF A LIST

# Print elements of a range # using negative index Elements sliced from index -6 to -1
List slicing ['R', 'N', 'I', 'N', 'G']
Sliced_List = List[-6:-1]
print("\nElements sliced from index -6 to -1")
print(Sliced_List)
# Printing elements in reverse Printing List in reverse:
# using Slice operation ['G','N','I','N','R', 'O', 'M','D','O','O','G']
Sliced_List = List[::-1]
print("\nPrinting List in reverse: ")
print(Sliced_List)
RECAP
Write a python program to implement list operations (add, append, extend &delete)
Write a python program to implement list operations (Nested List, Length,
Concatenation, Membership, Iteration, Indexing and Slicing)?
my_list= ['p', 'r','b', 'e']
print (my_list[0])
print ("Length", my_list, ":",len (my_list))
print (my_list [2])
print (my_list [3])
n_list=[[1,3,5,7],[2,4,6,8,10]]
print (n_list[0][1])
print (n_list[1][3])
n_list2 = ["Happy", [2,0,1,5]]
print (n_list2 [0][1])
print (n_list2 [1][3])
concat1=[1,3,5]
concat2=[7,8,9]
print ("Concatenation: ", concat1,concat2, ":",
concat1+concat2)
repetion_string="Hello"
print ("Repetition: ", repetion_string * 4)

You might also like