0% found this document useful (0 votes)
15 views80 pages

Py 02

The document provides an overview of Python programming, covering essential topics such as data types, variables, and methods for writing code in both interactive and script modes. It emphasizes the ease of learning Python and its applications in various fields like web development, machine learning, and data analysis. Additionally, it explains the significance of comments, expressions, and the identity of objects in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views80 pages

Py 02

The document provides an overview of Python programming, covering essential topics such as data types, variables, and methods for writing code in both interactive and script modes. It emphasizes the ease of learning Python and its applications in various fields like web development, machine learning, and data analysis. Additionally, it explains the significance of comments, expressions, and the identity of objects in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Problem Solving using Python

(ITFC0101)
Variables and Data Type
Contents
• Data Types
• Numeric
• Sequence Type
• Boolean
• Set
• Dictionary
• Comments
• Expression
Why should we learn Python?
•Python is easy to pick-up, even if you come from a non-programming
background.
•You can look at the code and tell what’s going on.
•Build a website
•Develop a game
•Perform Computer Vision (Facilities like face-detection and color-detection)
•Do Machine Learning (Giving a computer the ability to learn)
•Enable Robotics
•Perform Web Scraping (Harvesting data from websites)
•Perform Data Analysis
•Automate a web browser
•Perform Scripting
•Perform Scientific Computing
•Build Artificial Intelligence
Ways to write python code

Two ways of writing python code

• Interactive mode
• Script mode
Python Prompt
Interactive Mode

• Simply type the Python statement on >>> prompt (python shell prompt)
• As we type and press enter:
• See the output in the very next line
Python Prompt
Interactive Mode

# Python program to take input from user


# Taking input from user
a = int(input())
# Taking input from user
b = int(input())
# Multiplying and storing result
c=a*b
# Printing the result
print(c)
Python Prompt
Interactive Mode

Disadvantages

• Not suitable for large programs


• Doesn’t save the statements
• Make a program it is for that time itself
• Cannot use it in the future
• For future use, retype all the code
• Editing the code is difficult
• Need to revisit all our previous commands
Python Script
Script Mode

• Writing a program in a file 🡪


• use the interpreter to execute the contents of the file.
• Such a file is called a script

• Scripts have the advantage that they can be saved to disk, printed, and so on
• Using script needs text editor and interpreter
Python Script
Run python code in script mode

• Step 1: Make a file using a text editor. You can use any text editor of your choice
(e.g., notepad, vscode etc.)

• Step 2: Save the file using “.py” extension


• Step 3: Open the command prompt
• Step 4: Command directory to the one where your file is stored
• Step 5: Type python “fi[Link]” and press enter
• Step 6: See the output on your command prompt
Python Script
Run python code in script mode
Data Types

• Classification or categorization of data items


• Represents the kind of value
• Tells what operations can be performed on a particular data

• Everything is an object in Python


• Data types are actually classes
• Variables are instances (object) of these classes
Data Types
Following are standard or built-in data types in Python:

• Numeric / numbers
• Sequence Type
• Boolean
• Set
• Dictionary
Data Types
Data Types
None type (non existence value)
Numeric Data Type
Represents the data that has a numeric value
• Integers – Value is represented by int class
• Contains positive or negative whole numbers (without fractions or decimals)
• E.g. 100, -334, 976676576787998796764321323456767789889987898987
• In Python, there is no limit to how long an integer value can be
• Python prioritizes usability over memory constraints
>>> type(17)
<class 'int’>

>>> type(3.2)
<class 'float’>
Numeric Data Type
Represents the data that has a numeric value
• Float – Value is represented by float class
• A real number with floating-point representation
• Specified by a decimal point
• (9.54, -7667.6545, 4E+2,
667575676787877897878.76)

• Optionally, the character e or E followed


by a positive or negative integer may be

appended to specify scientific notation


Numeric Data Type
Complex data type

• Python focused on scientific computing


• Complex Numbers – Complex number is represented by a complex class
• It is specified as (real part) + (imaginary part)j. For example – 2+3j
Numeric Data Type
Complex data type

• Extract real and imaginary parts

• Python does not support ‘i’ letter with imaginary part


• E.g., 4 + 5i // Not supported in python as Complex Numbers
Numeric Data Type
Complex data type

Representations:
Numeric Data Type
Complex arithmetic operations

Representations:
Sequence Data Type
Ordered collection of similar or different data types

• Sequences allow storing of multiple values in an organized and efficient fashion

Following sequence types in Python –

• Python String
• Python List
• Python Tuple
String Data Type
A collection of one or more characters put in a single, double, or triple quote

• Arrays of bytes representing Unicode characters


• In python: No character data type, a character is a string of length one
• Represented by str class
String Data Type
• String with Single Quote:

• Single quoted strings can


have double quotes inside

them, as in

'The knights who say "Ni!"'


String Data Type

String with Double Quote:

• Double quoted strings can


have Single quotes inside

them, as in

“I’m the best”


String Data Type
String with Triple Quote:

• Strings enclosed with three


occurrences of either quote symbol

• They can contain either


single or double quotes:

1. Using ''' '''

2. Using """ """


String Data Type
String with Triple Quote:

• Strings with multiple lines


Using triple quotes

1. Using ''' '''

2. Using """ """


String Data Type

>>> type("Hello, World!")


<class 'str’>
>>> type("17")
<class 'str’>
>>> type("3.2")
<class 'str’>
>>> 'This is a string.'
'This is a string.'
>>> """And so is this."""
'And so is this.’
String Data Type
>>> type('This is a string.')
<class 'str’>
>>> type("And so is this.")
<class 'str’>
>>> type("""and this.""")
<class 'str'>
>>> type('''and even this...''')
<class 'str’>
>>> print('''"Oh no", she exclaimed, "Ben's bike is broken!"''')
"Oh no", she exclaimed, "Ben's bike is broken!"
String Data Type
Triple quoted strings can even span multiple lines:

>>> message = """This message will


... span several
... lines."""
>>> print(message)
This message will
span several
lines.
>>>
String Data Type
• Python doesn’t care whether you use single or double quotes or the
three-of-a-kind quotes to surround strings

• Once it has parsed the text of your program or command


• The way it stores the value is identical in all cases

• Surrounding quotes are not part of value


• When the interpreter wants to display a string
String Data Type
Accessing List Elements

• Individual characters of a String can be accessed by using Indexing


• Negative Indexing allows to access characters from the back of the String
• E.g. -1 refers to the last character
• -2 refers to the second last character, and so on.
Importance of comma

>>> 42000

42000

>>> 42,000 // Forming a tuple

(42, 0)
List Data Types
An ordered collection of data

• Just like arrays, declared in other languages


• Heterogeneous: A list do not need to be all elements of the same data type
• Mutable: data items may be updated / deleted after creation of list

Creating a List

• Lists in Python can be created by just


• placing the sequence inside the square brackets[ ]
List Data Types

• Creating an empty list:

• Creating a list with multiple


string values:
List Data Types
Multi-dimensional List

• 2D List
List Data Types
Multi-dimensional List
• 3D List
List Data Types
List with Duplicate elements
• List may have duplicate items
List Data Types
List with mixed type values (heterogeneous data elements)
• List supports heterogeneous data items
List Data Types
Accessing list with negative index
• In Python, negative sequence indexes represent positions from the end
• Negative indexing means beginning from the end, -1 refers to the last item, -2
refers to the second-last item, etc.

• Offset List[len(List)-2] == List[-2]


• len(list): Number of elements in list
List Data Types
len() function in multidimensional list
Tuple Data Types

• Similar to list, a tuple is also an ordered collection of Python objects


• Represent using data items enclosed in parentheses ( ) E.g., (2, 3.2, ‘asd’)
• Simple comma separated values also treated as tuple. e.g., 12,00,000 🡪 (12,0,0)
• Difference: tuples are immutable
• Tuples cannot be modified after creation

• Represented by a tuple class


• Support mixed data elements
Tuple Data Types
Difference between tuple and string for single item in tuple
Boolean Data Type

• Data type with one of the two built-in values: True or False
• Non-Boolean objects can be evaluated in a Boolean context as well
• Determined to be true or false

• Denoted by the class bool


Boolean Data Type
Variables
Variables
Assignment Statement

>>> message = "What's up, Doc?"


>>> n = 17
>>> pi = 3.14159
The assignment token, =, should not be confused with equals, which uses the
token ==
>>> 17 = n // Error Message
File "<interactive input>", line 1
SyntaxError: can't assign to literal
Variables
Rules

• Must start with a letter or the underscore character


• Variable name cannot start with a number
• Only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Case-sensitive (name, Name, and NAME are three different variables)
• Reserved words(keywords) cannot be used to name the variable
Variables

>>> day = "Thursday"

>>> day

'Thursday'

>>> day = "Friday"

>>> day

'Friday'

>>> day = 21

>>> day

21
Variable names and keywords
Contain both letters and digits, but they have to begin with a letter or an underscore

>>> 76trombones = "big parade"

SyntaxError: invalid syntax

>>> more$ = 1000000

SyntaxError: invalid syntax

>>> class = "Computer Science 101"

SyntaxError: invalid syntax


Python reserve keywords
• Total 35 reserve keywords (at present)
• May increase or decrease

awai
t
Variables
Valid Variable Names
Updating Variables
Important logics

• Before update a variable


• Iinitialize it to some starting value
• Incrementing/ decrementing a variable
Statements and Expressions
Statements
Executable line of code

• Unit of Execution
• An executable instruction (Executable code)
• Different types of statements in Python
• Assignment statements
• Conditional statements
• Looping statements, etc.
Statements
Different Type of Statements

• Single line statements


• Multi-Line Statements
• Conditional and Loop Statements: (If-else, for loop, while loop, try-except, with)
• Expression statements:
• pass, del, return, import, continue, break
• Mathematical operations, relational operations
Statements
Single Line Statements

• Where single statement completed after ending the line


• Example:
• a = 10
• b = 20
• c=a+b
• Print(c)
Statements
Multi-Line Statements

• Where execution of single statement completes after executing the multiple lines

a = “Hello\

First year\

students"

print(a)
Statements
Multi-Line Statements
• Explicit line continuation
• Using “\” operator: To explicitly split a statement into multiple lines
• Implicit line continuation
• parenthesis ( )
• brackets [ ]
• curli braces { }
• ‘:’ operator
for control statements, functions
Statements
Multi-Line Statements (Implicit line continuation)
parenthesis ( )
Statements
Multi-Line Statements (Implicit line continuation)
Square brackets [ ]

curli braces { }
Statements
Multi-Line Statements (Implicit line continuation)
‘:’ colon operator for control statements, functions, classes
Expression
Subset of statement

• Unit of Evaluation
• Associated with numerical values
• Combination of literals, operators and identifiers
Examples:

a = 10 b = 10 + 20

c=a*b d = len([2, 5, “aa”, 7.3])


Statement Vs Expression
Expression Subset of statement

• Expression is part of statement


• Keyword used to distinguish
• Statement 🡪 Execute
• Expression 🡪 Evaluate
Statements
Executable line of code

Evaluating expressions
>>> 1 + 1

>>> len("hello")

5
Statements
Evaluating expressions

>>> 17
17
>>> y = 3.14
>>> x = len("hello")
>>> x
5
>>> y
3.14
Comments
Comments in Python
Lines in the code that are ignored by the interpreter during the execution

Why Comments: Types of comments in Python:


• Enhance the readability of the code • Single line Comments
• Help the programmers to understand the code • Multiline Comments
very carefully
• Docstring Comments
• Restrict code execution
• Provide an overview of the program or project
metadata

• To add resources to the code


Comments in Python
Single line Comment using hashtag (#) Symbol

• Starts with the hashtag symbol (#)


• Lasts till the end of the line
• If the comment exceeds one
line then put a hashtag on the

next line
Comments in Python
Single line Comment using string literals

• String literals that are not assigned to a variable


• Starts and ends with either single quotes (' ')
or double quotes (" ")

• Lasts till the end of the line


Comments in Python
Multi line Comments (using string literals with triple quotes)

• String literals that are not assigned to a variable


• Starts and ends with the triple quotes
• Works till the end of the triple quotes
• Covers multiple lines
Comments in Python
Using docstring
• Python docstring is the string literals with triple quotes
• Appeared right after the function name
Comments in Python
Using docstring

• Used to associate documentation written with modules, functions, classes, and methods
• Added right below the functions, modules, or classes to describe the desired functionality
• Docstring is made available via __doc__ attribute
Identity of an object
Identity of an object
Id: object to memory address
• Id identifies each object such as variable, list, tuple, function, module, class
• Id is constant specific in python
• Syntax: id(object)

a = 10

b = 10

print(id(a))

print(id(b))
Identity of an object
Id of constant remain same
throughout the system at time T1
Identity of an object
Id of list, string
Identity of an object
Reversal of Id: memory address to object
Syntax: [Link](memory_address,ctypes.py_object).value
Identity of an object
Id of constant may change at time T2
Try it after restarting the system
Thank You!

You might also like