Unit-I python
Unit-I python
Python Programming
Agenda
No. Topics
1. Features of Python
2. Structure of Python Program
3. Elements of Python
4. Python Interpreter
5. Python Shell
6. Indentation
7. Strongly typed features
8. Basic Datatypes
9. Variables, Expression
10. Flow of Execution
11. Input/output Statements
12. Atoms, Identifiers and Keywords, Literals, String
Operators
13. Arithmetic Operator
14. Relational Operator
15. Logical or Boolean Operator
16. Assignment Operator
17. Ternary, Bit-wise and Increment/Decrement Operator
Control Statements
18. If
If….Else
Else If Ladder
Match….Case(Switch Statement)
Loop Controls
19. While Loop
For Loop
Rang Function
Break
Continue
Pass Statements with Loop
Introduction of Python
- It is used for:
o web development (server-side),
o software development,
o mathematics,
o system scripting.
Why Python?
- Python works on different platforms (Windows, Mac, Linux, Raspberry
Pi, etc).
- Python has a simple syntax similar to the English language.
- Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
- Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be
very quick.
- Python can be treated in a procedural way, an object-oriented way or
a functional way.
Characteristics of Python
- It supports functional and structured programming methods as well as
OOP.
- It can be used as a scripting language or can be compiled to byte-code
for building large applications.
- It provides very high-level dynamic data types and supports dynamic type
checking.
- It supports automatic garbage collection.
- It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Applications of Python
- Python is a general purpose programming language known for its
readability. It is widely applied in various fields.
- In Data Science, Python libraries like Numpy, Pandas,
and Matplotlib are used for data analysis and visualization.
- Python frameworks like Django, and Pyramid, make the development
and deployment of Web Applications easy.
- This programming language also extends its applications to computer
vision and image processing.
- It is also favored in many tasks like Automation, Job Scheduling, GUI
development, etc.
Features of Python
- Standard Library - Even though it has a very few keywords (only Thirty-
Five), Python software is distributed with a standard library made of large
number of modules and packages. Thus Python has out of box support
for programming needs such as serialization, data compression, internet
data handling, and many more. Python is known for its batteries included
approach.
NumPy
Pandas
Matplotlib
Tkinter
Math
Step 1: Install Python. Make sure that Python is installed on your system
or not. If Python is not installed, then install it from
here: https://www.python.org/downloads/
Step 3: Open Text Editor or IDE, create a new file, and write the code to
print Hello World.
Step 4: Save the file with a file name and extension ".py".
In the above code, we wrote two lines. The first line is the Python
comment that will be ignored by the Python interpreter, and the second
line is the print() statement that will print the given message ("Hello
World") on the output screen.
Output
Hello World
In Command Prompt
C:\Users\MAHESH>python
Elements of Python
The elements of a Python program refer to the basic building blocks or
components that make up a Python program. Understanding these elements
is crucial for writing effective and efficient Python code.
1. Variables
Variables store data values. In Python, you don’t need to declare the type of a
variable beforehand; Python automatically detects the type.
Python variables are the reserved memory locations used to store values with
in a Python Program. This means that when you create a variable you reserve
some space in the memory.
Example:
x = 5 # integer
name = "Alice" # string
pi = 3.14 # float
is_valid = True # Boolean
- A variable name cannot start with a number or any special character like
$, (, * % etc.
If the name of variable contains multiple words, we should use these naming
patterns −
2. Data Types
Python has the following data types built-in by default, in these categories:
Python data types are actually classes, and the defined variables are their
instances or objects. Since Python is dynamically typed, the data type of a
variable is determined at runtime based on the assigned value.
In general, the data types are used to define the type of a variable. It represents
the type of data we are going to store in a variable and determines what
operations can be done on it.
Each programming language has its own classification of data items. With these
datatypes, we can store different types of data values.
Python numeric data types store numeric values. Number objects are created
when you assign a value to them.
Example:
Python strings are immutable which means when you perform an operation on
strings, you always produce a new string object of the same type, rather than
mutating an existing string.
Example:
>>> 'TutorialsPoint'
'TutorialsPoint'
>>> "TutorialsPoint"
'TutorialsPoint'
>>> '''TutorialsPoint'''
'TutorialsPoint'
Python Lists are the most versatile compound data types. A Python list contains
items separated by commas and enclosed within square brackets ([]).
One difference between them is that all the items belonging to a Python list can
be of different data type where as C array can store elements related to a
particular data type.
A list in Python is an object of list class. We can check it with type() function.
<class 'list'>
As mentioned, an item in the list may be of any data type. It means that a list object can
also be an item in another list. In that case, it becomes a nested list.
A list can have items which are simple numbers, strings, tuple, dictionary, set or object of
user defined class also.
The values stored in a Python list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way to end -1.
The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator. A list in Python is an object of list class. We can check it with type() function.
<class 'list'>
It means that a list object can also be an item in another list. In that case, it becomes a
nested list.
A list can have items which are simple numbers, strings, tuple, dictionary, set or object of
user defined class also. A list in Python is an object of list class. We can check it with
type() function.
<class 'list'>
As mentioned, an item in the list may be of any data type. It means that a list object can
also be an item in another list. In that case, it becomes a nested list.
A list can have items which are simple numbers, strings, tuple, dictionary, set or object of
user defined class also.
Python tuple is another sequence data type that is similar to a list. A Python
tuple consists of a number of values separated by commas. Tuples are
enclosed within parentheses (...).
A tuple is also a sequence, hence each item in the tuple has an index referring
to its position in the collection. The index starts from 0.
In Python, a tuple is an object of tuple class. We can check it with the type()
function.
<class 'tuple'>
print(i)
This type of data is commonly used when dealing with things like files, images,
or anything that can be represented using just two possible values.
So, instead of using regular numbers or letters, binary sequence data types use
a combination of 0s and 1s to represent information.
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.
Python dictionary is like associative arrays or hashes found in Perl and consist
of key:value pairs.
The pairs are separated by comma and put inside curly brackets {}. To establish
mapping between key and value, the semicolon':' symbol is put between the
two.
An object cannot appear more than once in a set, whereas in List and Tuple,
same object can appear more than once.
Comma separated items in a set are put inside curly brackets or braces {}. Items
in the set collection can be of different data types.
Note that items in the set collection may not follow the same order in which they
are entered.
Python's Set is an object of built-in set class, as can be checked with the type()
function.
<class 'set'>
Python Interpreter
As we all know Python is one of the most high-level languages used today
because of its massive versatility and portable library & framework features. It
is an interpreted language because it executes line-by-line instructions. There
are actually two way to execute python code one is in Interactive mode and
another thing is having Python prompts which is also called script mode.
Python does not convert high level code into low level code as many other
programming languages do rather it will scan the entire code into something
called bytecode.
Compiler Interpreter
It takes lot of time to analyze the code It takes less time compared to
structure compilers.
Python Indentation
Indentation is a critical part of the syntax. It is used to define blocks of code
that belong together. Unlike many other programming languages that use
braces {} to delimit blocks, Python uses indentation to group statements.
Example:
# Python indentation
site = 'gfg'
if site == 'gfg':
print('Logging on to geeksforgeeks...')
else:
print('retype the URL.')
print('All set !')
Strong typing
strong typing refers to the concept that variables have a specific type, and the
language enforces type correctness in operations. This means that once a
variable is assigned a particular type, it cannot be implicitly coerced into another
type (unless explicitly converted). This is a characteristic of strongly-typed
languages.
Example: a = 10 # Integer
b = "5" # String
c=a+b
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
Dynamic typing
The type of a variable is determined only during runtime. This allows for
flexibility in programming, but can impact performance.
Expressions
The operators used in these expressions are arithmetic operators like addition,
subtraction, etc.
print(add)
print(sub)
print(pro)
print(div)
3. Integral Expressions: These are the kind of expressions that produce only
integer results after all computations and type conversions.
c = a + int(b)
print(c)
c=a/b
print(c)
Those arithmetic expressions are evaluated first, and then compared as per
relational operator and produce a boolean output in the end.
Example:
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Comments in Python
- Python comments start with the hash symbol # and continue to the end
of the line.
- Comments in Python are useful information that the developers provide
to make the reader understand the source code.
- It explains the logic or a part of it used in the code.
- Comments in Python are usually helpful to someone maintaining or
enhancing your code when you are no longer around to answer
questions about it.
Example:
# This is a comment
# This is a single line comment
# This is multi line comment
'''
This is a multi-line comment using triple-quoted strings.
It can span multiple lines and is often used for doc-strings.
'''
Python Statement
It signifies that each line of a Python script contains a statement. These all
help the user to get the required output.
Multi-Line Statements
Python Conditional and Loop Statements
o Python If-else
o Python for loop
o Python while loop
o Python try-except
o Python with statement
Python Expression statements
o Python pass statement
o Python del statement
o Python return statement
o Python import statement
o Python continue and
o Python break statement
The program is converted into byte code. Byte code is a fixed set of
instructions that represent arithmetic, comparison, memory operations, etc.
It can run on any operating system and hardware. The byte code instructions
are created in the .pyc file.
The .pyc file is not explicitly created as Python handles it internally but it can
be viewed with the following command
Interpreter
The next step involves converting the byte code (.pyc file) into machine code.
This step is necessary as the computer can understand only machine code
(binary code).
Python Virtual Machine (PVM) first understands the operating system and
processor in the computer and then converts it into machine code.
Further, these machine code instructions are executed by a processor and the
results are displayed.
- With the print() function, you can display output in various formats, while
the input() function enables interaction with users by gathering input
during program execution.
Example 1:
print("Hello, World!")
Example 2:
name=input(“Enter your name : ”)
print("Hello, ", name)
Atoms Python
There are multiple matches for atoms in Python, including a Python package
for machine learning, a framework for creating Python objects, and the basic
elements of expressions in Python
ATOM
An open-source Python package for machine learning that helps users:
Train multiple models with one line of code
Analyze data and model performance with plots
Avoid refactoring to test new pipelines
Atom framework
A framework for creating memory-efficient Python objects with features like:
Dynamic initialization
Validation
Change notification for object attributes
Atoms in expressions
The basic elements of expressions in Python, including:
Identifiers or literals
Atom can also refer to Atom, an open-source, cross-platform text editor and
integrated development environment (IDE) for Python:
Keywords
Reserved words with special meanings that cannot be used as variable names.
Examples: if, else, for, while, def, class, import, True, False
Identifiers:
Python Identifier is the name we give to identify a variable, function, class,
module or other object.
That means whenever we want to give an entity a name, that's called identifier.
A python identifier is a name given to various entities like variables, functions,
and classes.
Example:
my_variable = 10
def calculate_sum(a, b):
return a + b
class MyClass:
pass
# having an empty function definition like this, would raise an error without the
pass statement
Here, my_variable, calculate_sum, and MyClass are identifiers.
You can use the isidentifier() method to check if a string is a valid identifier:
print("my_variable".isidentifier()) # True
print("1my_variable".isidentifier()) # False (starts with a number)
print("for".isidentifier()) # False (keyword)
Literals in Python
Literals are notations representing fixed values in the source code. They are
the raw data that is assigned to variables or constants.
String Literals:
Single-quoted: 'Hello, world!'
Double-quoted: "Python is fun"
Triple-quoted: '''Multi-line string''' or """Multi-line string"""
Boolean Literals:
True
False
None Literal:
None (represents the absence of a value)
Collection Literals:
List: [1, 2, 3]
Tuple: (1, 2, 3)
Dictionary: {'name': 'Alice', 'age': 25}
Set: {1, 2, 3}
Python Strings
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
Example:
a = "Hello, World!"
print(a[1])
Python Operators
1. Arithmetic Operators
2. Relational/Comparison Operators
3. Logical/Boolean Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary Operator
7. Increment and Decrement Operators
1. Arithmetic Operators
Subtraction: subtracts
– x–y
two operands
Multiplication: multiplies
* x*y
two operands
2. Comparison Operators
3. Logical Operators
Python Logical operators perform Logical AND, Logical OR, and Logical
NOT operations. It is used to combine conditional statements.
4. Bitwise Operators
Python Bitwise operators act on bits and perform bit-by-bit operations. These
are used to operate on binary numbers.
| Bitwise OR x|y
~ Bitwise NOT ~x
5. Assignment Operators
6. Ternary Operator
It simply allows testing a condition in a single line replacing the multiline if-
else making the code compact.
you would have known Increment and Decrement operators (both pre and
post) are not allowed in it.
Python is designed to be consistent and readable.
One common error by a novice programmer in languages with ++ and —
operators are mixing up the differences (both in precedence and in return
value) between pre and post-increment/decrement operators.
Arrays
Python Arrays are a data structure that can hold a collection of items.
Unlike lists, which can hold items of different data types, arrays in Python are
typically used to store items of the same data type.
Python does not have a built-in array data type, but the ‘array’ module provides
an array type that can be used for this purpose.
Example:
# accessing Araay
a.append(5)
print(a)
Conditional Statements
1. if Statement
Example of If Statement:
if (i > 50):
2. if….else Statement
if (i > 0):
print("i is positive")
else:
print("i is 0 or Negative")
else:
else:
else:
4. if…elif…else Statement
if-elif-else statement in Python is used for multi-way decision-making. This
allows you to check multiple conditions sequentially and execute a specific
block of code when a condition is True. If none of the conditions are true,
the else block is executed.
passing_marks = 40
print("Result: Distinction")
else:
print("Result: Fail")
else:
print("Result: Fail")
Developers coming from languages like C/C++ or Java know that there is a
conditional statement known as a Switch Case.
This Match Case is the Switch Case of Python which was introduced
in Python 3.10. Here we have to first pass a parameter and then try to check
with which case the parameter is getting satisfied.
If we find a match we will execute some code and if there is no match at all, a
default action will take place.
Syntax:
match parameter:
case pattern1:
case pattern2:
case patterN:
case _:
Loops Controls
1. While Loop
A while loop is used to execute a block of statements repeatedly until a given
condition is satisfied.
When the condition becomes false, the line immediately after the loop in the
program is executed.
Syntax:
while expression:
statement(s)
Example:
count = 0
while (count < i):
count = count + 1
print(count)
2. For Loop
For loops are used for sequential traversal. For example: traversing
a list or string or array etc. In Python, there is “for in” loop which is similar
to foreach loop in other languages. Let us learn how to use for loops in Python
for sequential traversals with examples.
Syntax:
statements(s)
Example:
print(i)
range() Function
The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and stops before a specified
number.
Syntax:
range(start, stop, step)
Example:
x = range(6)
for n in x:
print(n)
1. break Statement:
The break statement is used to exit a loop prematurely when a certain
condition is met.
Output:
1
2
3
4
Breaking the loop as we found 5
2. continue Statement:
The continue statement is used to skip the current iteration of the loop and
move to the next iteration when a condition is met.
Output:
1
2
3
4
Skipping 5
6
7
8
9
10
3. pass Statement:
The pass statement is a null operation. It’s a placeholder that does nothing. It
is commonly used when you need a syntactically correct block of code but
don’t want to do anything yet.
Output:
Processing 1
Processing 2
Processing 3
Processing 4
Processing 5