Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 51

CGB1121-PYTHON PROGRAMMING

Presented By

S.SENTHIL
AP/CSE
K.RAMAKRISHNAN COLLEGE OF TECHNOLOGY
COURSE OUTCOMES
CO1- Apply the Python fundamentals to solve elementary problems.
CO2-Demonstrate the use of Control Statements and Functions for efficient
program flow and modularity.
CO3-Perform various operations in strings, list and tuple.
CO4- Demonstrate the different methods in Dictionary, Set and Regular
Expression.
CO5-Integrate the knowledge of Python syntax, libraries, and frameworks in
building applications
Text Book:
 Anurag Gupta, IPS Jharkhand, GP Biswass, “ Python
Programming, Problem Solving, Packages and
Libraries”,McGraw Hill Education(India) Private Limited, 2019
ISBN-13:978-93-5316-800-1
 “Python Programming: Using Problem Solving Approach “ by
Reema Theraja, Oxford Higher Education,2017.
 Gowrishankar S, Veena A, “Introduction to Python
Programming”, 1st Edition, CRC Press/Taylor & Francis, 2018.
ISBN-13: 978-0815394372
Module-1
Python Basics, Data Types, Expressions and
Operators
 Python Basic Concepts: Interactive Mode and Script Mode -

Comments - Statements and Indentation-Keywords -

Identifiers and Variables - Data Types: int, float, boolean, string

and Sequence data types - Type Casting - Operators.


1.1 Python Basic Concepts: Interactive
Mode and Script Mode
Interactive Mode:

Interactive Mode in Python provides a dynamic environment for


developers to interactively write and execute Python statements line by line.

It offers a way to experiment, test code snippets, and receive immediate


feedback for each command entered.
Script mode
Script Mode is writing/executing Python scripts or programs
1.Creating a Script:
To use Script Mode, you create a new text file using a code or plain text editor. You write your
Python code within this file, including imports, functions, and other statements.

2.Saving the Script:


After writing your code, you save the file with a .py extension. This indicates to the Python
interpreter that the file contains Python code.

3.Executing the Script: To run the script, you open a terminal or command prompt, navigate
to the directory where the script is saved, and use the python command followed by the
script's filename. The Python interpreter reads and executes the script from top to bottom.
1.2 Comments
 Comments are just short descriptions along with the code.

 Comments are used to increase the readability of a code.

 Comments are just meant for the developers to understand a

piece of code.

 Comments are ignored completely by Python interpreter.


Type of comments
Single-Line Comments in Python

 The single-line comments in Python are denoted by the hash symbol “#” and
include no white spaces.
Multi-Line Comments in Python

 Python does not have multi-line comments, but there are two ways we can
achieve this
 #Welcome
 #to
 #Scaler
Advantages of Using Comments in
Python
 Readability- Python comments greatly enhance the readability of the code.

 Blocking out certain code- Blocking out code for execution is another avenue

where comments are widely used.


"""
If you do not want to type # every time for
every line, you can make use of
delimiters!
"""
Docstring Comments in Python
Docstring is an in-built feature in Python and is usually associated with
documentation in Python.

def intro():
"""
This function prints Welcome to Scaler
Statement

The instructions written in Python are called statements

Single line statement

print(‘i’)

multi-line statement

result = 2 + 3 * 5 - 5 + 6 - 3 + 4

print(result)
Indentation

 Before we discuss this,

 what is a block?

 A block is a set of statements instructions.

 programming languages like C, C++, Java, etc.., uses {} to define a block.

 Python uses indentation to define a block.

 There is nothing more than a tab.


Ex.
def find_me():
…sample = 4
…return sample
find_me()
keyword
 Python-reserved words have specific meanings.
 Keyword cannot be used as identifiers or variable names
Ex
numbers = [1, 2, 3, 4, 5]
if 3 in numbers:
print("3 is in the list.")
Identifiers
 Identifiers are names used to identify a variable, function,

class, module, or other object.

 Identifiers are essentially user-defined names to represent

these entities in a program.

 Identifiers is to make the code readable and meaningful.


Rules for Naming Python Identifiers
 Start with Letters or Underscore- (A-Z, a-z) or an underscore
(_).
 Case Sensitive-myVar, MyVar, and myvar
 Contain Alphanumeric Characters and Underscores-After the
first letter or underscore, identifiers can contain letters, digits
(0-9), and underscores.
 No Special Characters
 Avoid Keywords
 Length: There is no length limit for Python identifiers.
 Conventions
Ex:
• Variables: height, max_value, _data

• Functions: calculate_area(), get_info()

• Classes: User, StockPrice

• Constants: MAX_LIMIT, PI
Variables
 A variable in Python is a reserved memory location to store
values.
Rules for naming a variable
 Variable should either begin with an Uppercase(A to Z) or Lowercase(a
to z) character or an underscore(_).
 Variable should always to use a meaningful name in Python. For
example – no_of_chocolates makes more sense than noc.
 Which brings us to the next point. If a variable has multiple words, it is
advised to separate them with an underscore.
 One should ensure that a variable name should not be similar to
keywords of the programming language.
 One should also remember that even variable names are case-sensitive.
 A variable should not begin with a digit or contain any white spaces or
special characters such as #,@,&.
 Example of good variable names – my_name, my_dob.
Data Types: int, float, boolean, string and
Sequence data types
 Numeric Data types

Integers

Integers are numbers without any fractional part.

Integers can be 0, positive, or negative.

Integer does not have a limit to how long it can be.

Integer represented by int class.


num = 5

print("number =", num)


Floating Point
Floats are real numbers with floating point
representation

Float is represented by the float class.


num = 5.55

print("number =", num)


Complex numbers
Complex numbers in Python are specified as
(real part) + (imaginary part)j.

Complex is represented by the complex


class.
num = 5 + 5j

print("number =", num)


Boolean
 Boolean has one of two possible values, True or False
 Boolean is used in creating the control flow of a program using
conditional statements.

a = True
print("a =", a)
print("Data type of 'True':", type(a))
Sequence Data types
 Strings:

• Strings represent sequences of Unicode characters enclosed


in single or double quotes.
• They are immutable, meaning once defined, their content
cannot be changed.
name = "Python"

print(name)
list
• Lists are mutable storage units that hold multiple data items
together.
• They can contain strings, numbers, other lists, tuples,
dictionaries, and more.
list_1 = ["Python", "Sequences"] # All string list

list_2 = list() # Empty list

list_3 = [2021, ['hello', 2020], 2.0] # Integer, list, float

list_4 = [{'language': 'Python'}, (1, 2)] # Dictionary, tuple


Tuples:
• Similar to lists, tuples store multiple data items of different
types.
• tuples are immutable and are enclosed in parentheses.
my_tuple = (1, 2, 3) # Immutable tuple
Bytes and Byte arrays:
 A bytes object represents an immutable sequence of small
integers in the range 0 <= x < 256.
 When displayed, it prints as ASCII characters.
 Bytes literals can be constructed using the constructor bytes()
 my_bytes = bytes([65, 66, 67]) # Creates a bytes object
with values 65, 66, 67 (ASCII for 'A', 'B', 'C')
Bytearray
 A byte array object represents a mutable sequence of integers
in the same range (0 <= x < 256).
 Byte array has most of the usual methods of mutable
sequences.
 Byte arrays can be modified after creation.
 To construct byte arrays, use the bytearray()
 my_bytearray = bytearray([97, 98, 99]) # Creates a bytearray
with values 97, 98, 99 (ASCII for 'a', 'b', 'c')
 my_bytearray[1] = 100 # Modify the second element to 100
(ASCII for 'd')
Range Objects:

 The range objects are an immutable sequence of numbers.

 Range objects are used for iteration or for looping over a

specific number of times.


 #1 – range (start, stop, step)

 #2 -range (start, stop)

 #3- range (max_limit)


my_range = range(5) # Represents 0, 1, 2, 3, 4
Typecasting
 Type Casting is the method to convert the Python variable
datatype into a certain data type
• Python Implicit Type Conversion
• It automatically converts one data type to another data type
without any user's need

• Python Explicit Type Conversion


• The conversion of one data type into another, manually

 number = int("value")
Operators.
 Operators are special symbols that carry arithmetic or logical
operations.
 The value that the operator operates on is called the operand.
Arithmetic operators
Assignment operators
Comparison operators
logical operators
Identity operators
Membership operators
Boolean operators
Operator precedence
 operators have different levels of precedence, which
determine the order in which they are evaluated.
 When multiple operators are present in an expression, the
ones with higher precedence are evaluated first.
 If the same precedence, their associativity comes into play,
determining the order of evaluation.
Operator precedence
Precedence Operators Description Associativity

1 () Parentheses Left to right

2 x[index], x[index:index] Subscription, slicing Left to right

3 await x Await expression N/A

4 ** Exponentiation Right to left

Positive, negative, bitwise


5 +x, -x, ~x Right to left
NOT
Multiplication, matrix,
6 *, @, /, //, % division, floor division, Left to right
remainder

7 +, – Addition and subtraction Left to right

8 <<, >> Shifts Left to right

9 & Bitwise AND Left to right

10 ^ Bitwise XOR Left to right


11 | Bitwise OR Left to right

in, not in, is, is Comparisons, membership


12 Left to Right
not, <, <=, >, >=, !=, == tests, identity tests

13 not x Boolean NOT Right to left

14 and Boolean AND Left to right

15 or Boolean OR Left to right

16 if-else Conditional expression Right to left

17 lambda Lambda expression N/A

Assignment expression
18 := Right to left
(walrus operator)
Ex:
a+b**c/d-(e-f)
a:·4
b:·1
c:·2
d:·4
e:·2
f:·3
a+(b**c)/d-(e-f): 5.25
Thank You……..

You might also like