0% found this document useful (0 votes)
2 views30 pages

Python Unit One

The document outlines key features of Python, including its ease of learning, readability, and broad standard library. It also provides instructions for installing Python, applications of the language, rules for naming identifiers, and various types of statements and operators in Python. Additionally, it covers data types, input/output statements, and examples of expressions and type conversions.

Uploaded by

sacitca
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views30 pages

Python Unit One

The document outlines key features of Python, including its ease of learning, readability, and broad standard library. It also provides instructions for installing Python, applications of the language, rules for naming identifiers, and various types of statements and operators in Python. Additionally, it covers data types, input/output statements, and examples of expressions and type conversions.

Uploaded by

sacitca
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Features:

Easy-to-learn :
Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
Easy-to-read :
Python code is more clearly defined and visible to the eyes.
Easy-to-maintain:
Python's source code is fairly easy-to-maintain.
A broad standard library :
Python's bulk of the library is very portable and cross-platform compatible
on UNIX, Windows.
Databases :
Python provides interfaces to all major commercial databases.
Portable:
Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
It can be easily integrated with C, C++,java.

Installing Python
 Open a Web browser and go to [Link]
 Follow the link for the Windows installer [Link] file where XYZ
is the version you need to install.
 To use this installer [Link], the Windows system must support
Microsoft Installer 2.0. Save the installer file to your local machine and then
run it to find out if your machine supports MSI.
 Run the downloaded file. This brings up the Python install wizard, which is
really easy to use. Just accept the default settings, wait until the install is
finished, and you are done.
Applications of Python
1. Web Development
2. Data Science & Data Analysis
3. Machine Learning & Artificial Intelligence
4. Automation & Scripting
5. Game Development
6. Scientific & Numerical Computing
7. Networking Applications
8. Cybersecurity
9. Internet of Things (IoT)

Python Identifiers
Identifiers: Any name that is used to define a class, function, variable module, or
object is an identifier.

Rules for Naming Identifiers

1. Start with a letter or underscore (_): Identifiers must begin with an alphabetic
character (A-Z, a-z) or an underscore (_). They cannot start with a digit.

2. Only alphanumeric characters and underscores: Identifiers can include letters,


digits, and underscores but no special characters like @, #, or spaces.

3. Reserved words like if, else, True, and None cannot be used as identifiers.

4. Case-sensitive: Identifiers are case-sensitive, meaning variable, Variable, and


VARIABLE are treated as distinct names.

Keywords
These are reserved words and you cannot use them as constant or variable or
any other identifier names. All the Python keywords contain lowercase letters only.
The following list shows the Python keywords.
and
del
for
elif
return
break
else
global
not
tryclass
except
while
continue

Indentation
Python provides no braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation.
The number of spaces in the indentation is variable, but all statements within
the block must be indented the same amount.
For example −
if True:
print "True"
else:
print "False"
Thus, in Python all the continuous lines indented with same number of spaces
would form a block.
Rules of Indentation in Python
 All statements inside a block must have the same indentation level.
 Standard indentation in Python is 4 spaces (PEP 8 style guide).
 Mixing tabs and spaces in indentation is not allowed.
 Improper indentation will cause an Indentation Error.
Data Types in Python

A data type specifies the type of value a variable can hold. Python is a
dynamically typed language, so you do not need to declare the data type
explicitly.

Python data types are broadly classified into:

1. Numeric Data Types


2. Sequence Data Types
3. Set Data Types
4. Mapping Data Type
5. Boolean Data Type
6. None Data Type

1. Numeric Data Types


Used to store numerical values.

a) int (Integer)

Stores whole numbers (positive or negative).

a=12

b) float

Stores decimal (floating-point) numbers.

a=12.5

c) complex

Stores complex numbers with real and imaginary parts.

c = 2 + 3j

2. Sequence Data Types


Used to store collections of values.

a) str (String)

Stores text or characters enclosed in quotes.

name = "Python"
b) list

Stores ordered and changeable values.

marks = [80, 85, 90]

c) tuple

Stores ordered but unchangeable values.

X = (10, 20)

[Link] Data Types


set

Stores unordered and unique values.

fruits = {"apple", "banana", "orange"}

4. Mapping Data Type


dict (Dictionary)

Stores data in key-value pairs.

student = {

"name": "Deepa",

"age": 20,

"course": "IT"

5. Boolean Data Type


bool

Stores only two values: True or False.

is_passed = True

6. None Data Type


Represents the absence of a value.

result = None

Statement in Python
A Python statement is an instruction that the Python interpreter can execute.
There are different types of statements in Python language as Assignment
statements, Conditional statements, Looping statements, etc.

1. Assignment Statements

Assignment statements are used to assign values to variables.

age = 25

name = "John"

2. Conditional Statements

Conditional statements are used to execute different blocks of code based on


certain conditions. The most common conditional statements are if, elif, and else.

x = 15

if x > 10

print("x is greater than 10")

else:

print("x is less than or equal to 10")

output

x is greater than 10

3. Loop Statements

Loop statements are used to execute a block of code repeatedly. Python has
two types of loops:

 for loop and


 while loop.

For loop example


for i in range(5):

print(i)

While loop example

count = 0

while count < 5:

print(count)

count = count + 1

4. Function Definition Statements

Function definition statements are used to define reusable blocks of code.

def add_numbers(a, b):

return a + b

result = add_numbers(3, 5)

print(result)

output

5. Import Statements
This statement is mainly used to include external modules.
import math
print([Link](16))
Output
4.0
6. Exception Handling Statements
Exception handling statements are mainly used to handle errors safely.
try:
x=1/0
except ZeroDivisionError:
print("Division by zero not allowed")
Output
Division by zero not allowed
[Link]-line Statements
Some statements are too long to fit on one line. Python allows breaking them
into multiple lines:
7.1 Using backslash (\)
s=1+2+3+\
4+5+6+\
7+8+9
print(s)
Output
45
7.2 Using parentheses ()
n = (1 * 2 * 3 +
4 + 5 + 6)
print(n)
Output
21

7.3 Using square brackets []


footballers = [
"Messi",
"Neymar",
"Suarez"
]
print(footballers)
Output
['Messi', 'Neymar', 'Suarez']
7.4 Using braces {}
numbers = {1, 2, 3,
4, 5}
print(numbers)
Output
{1, 2, 3, 4, 5}

Python Operators
In Python programming, Operators in general are used to perform
operations on values and variables.
 Operators: Special symbols like -, + , * , /, etc.
 Operands: Value on which the operator is applied.

[Link] operators
Python Arithmetic operators are used to perform basic
mathematical operations like addition, subtraction, multiplication and
division.
Operator Description Syntax

+ Addition: adds two operands x+y

Subtraction: subtracts two


x–y
– operands

Multiplication: multiplies two


x*y
* operands

Division (float): divides the


x/y
/ first operand by the second

Division (floor): divides the


x // y
// first operand by the second

Modulus: returns the


remainder when the first
x%y
operand is divided by the
% second

Power: Returns first raised to


x ** y
** power second
Example:
a = 15
b=4
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625
[Link] Operators
In Python, Comparison (or Relational) operators compares values.
It either returns True or False according to the condition.
< Less than a<b

> Greater than a>b

<= Less than or equal to a<=b

>= Greater than or equal to a>=b

== Is equal to a==b

!= Is not equal to a!=b


Example
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Output
False
True
False
True
False
True
[Link] Operators
Python Logical operators perform Logical AND, Logical OR and Logical
NOT operations. It is used to combine conditional statements.
Logical Operators in Python is as follows:
1. Logical not
2. logical and
3. logical or

perator Description Syntax

Returns True
if both the
and x and y
operands are
true
perator Description Syntax

Returns True
if either of
or x or y
the operands
is true

Returns True
if the
not not x
operand is
false

Example
a = True
b = False
print(a and b)
print(a or b)
print(not a)
Output
False
True
False
[Link] Operators
Python Bitwise operators act on bits and perform bit-by-bit operations.
These are used to operate on binary numbers.
Operator Description Syntax

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y


Operator Description Syntax

>> Bitwise right shift x>>

<< Bitwise left shift x<<

Bitwise Operators in Python are as follows:


1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
[Link] Operators
In Python, in and not in are the membership operators that are used to test
whether a value or variable is in a sequence.
in :True if value is found in the sequence
not in :True if value is not found in the sequence
Example
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")

Output
x is NOT present in given list
y is present in given list

[Link] Operator
In Python, Ternary operators also known as conditional expressions are
operators that evaluate something based on a condition being true or false.
Syntax : [on_true] if [expression] else [on_false]
Example
a, b = 10, 20
min = a if a < b else b
print(min)
Output
10

Expressions in Python
An expression is a combination of operators and operands that is interpreted
to produce some other value. In any programming language, an expression is
evaluated as per the precedence of its operators. So that if there is more than one
operator in an expression, their precedence decides which operation will be
performed first.
1. Constant Expressions:
These are the expressions that have constant values only.
Example:
x = 15 + 1.3
print(x)
Output
16.3
2. Arithmetic Expressions:
An arithmetic expression is a combination of numeric values, operators, and
sometimes parenthesis. The result of this type of expression is also a numeric
value. The operators used in these expressions are arithmetic operators like
addition, subtraction, etc
Operator
Syntax Functioning
s

+ x+y Addition

- x-y Subtraction

* x*y Multiplication

/ x/y Division

// x // y Quotient

% x%y Remainder

** x ** y Exponentiation

Example
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335
3. Relational Expressions:
In these types of expressions, arithmetic expressions are written on both
sides of relational operator (> , < , >= , <=). Those arithmetic expressions are
evaluated first, and then compared as per relational operator and produce a boolean
output in the end.

a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True

[Link] Expressions:
These are kinds of expressions that result in either True or False. It basically
specifies one or more conditions.
Operator Syntax Functioning

P and It returns true if both P and Q are true


and
Q otherwise returns false

It returns true if at least one of P and


or P or Q
Q is true

not not P It returns true if condition P is false

Example
P = (10 == 9)
Q = (7 > 5)
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
Output
False
True
True

[Link] Expressions:
We can also use different types of expressions in a single expression, and
that will be termed as combinational expressions.
Example:
a = 16
b = 12
c = a + (b >> 1)
print(c)
Output
22

Input and output statement


Input and Output (I/O) statements in Python are used to interact with the user.
 Input allows the user to provide data to the program.
 Output displays results or information to the user.
Python mainly uses the input() function for input and the print() function for
output.

Input Statement in Python


Python uses the input() function to read data from the user.
Syntax
variable = input(" message")

 Always returns data as a string.

 Type conversion is required for numeric input.

 Input is taken from the keyboard at runtime.

Examples

name = input("Enter your name: ")

age = int(input("Enter your age: "))

salary = float(input("Enter salary: "))

Type Conversion in Input

Since input() returns a string, conversion is needed.


Function Purpose
int() : Converts to integer
float() : Converts to decimal
str() : Converts to string

Example

a = int(input("Enter a number: "))

b = int(input("Enter another number: "))

print(a + b)

Multiple Inputs in One Line in Python

 Python allows taking multiple inputs in a single line using the input()
function.
 The input values are usually separated by spaces.
 The split() method is used to divide the input string into separate values.
 The map() function is used to convert input values to a required data type
(int, float, etc.).

Syntax

a, b = map(int, input().split())

Example

x, y, z = map(float, input("Enter three numbers: ").split())

print(x, y, z)

Sample Input
10 20 30

Sample Output
10.0 20.0 30.0

Output Statement in Python


Python uses the print() function to display output.

Syntax

print(value)

Features

 Can print text, numbers, and variables.


 Multiple values can be printed at once.
 Output appears on the screen.

Example
print("Welcome to Python")
print(10 + 20)

Printing Multiple Values


a=5
b = 10
print(a, b)
Output
5 10
Separator (sep) Parameter
It is Used to separate multiple values.
print("A", "B", "C", sep="-")
Output
A-B-C

End (end) Parameter


It Controls what is printed at the end.
print("Hello", end=" ")
print("World")
Output
Hello World
Using f-strings
Example
name = "abc"
marks = 92
print(f"Name: {name}, Marks: {marks}")
Output
Name: abc, Marks: 92
Formatting Decimal Values
Example
pi = 3.14159
print(f"Value of pi: {pi:.2f}")
Output
Value of pi: 3.14
Escape Characters in Output
Character Meaning
\n New line
\t Tab
\\ Backslash
Example
print("Hello\nPython")
Output
Hello
Python

Conditional statements
Conditional statements in Python are used to execute certain blocks of code based
on specific conditions. These statements help control the flow of a program,
making it behave differently in different situations.
[Link] if Conditional Statement
If statement is the simplest form of a conditional statement. It executes a block of
code if the given condition is true.
syntax
if condition:
statement(s)

Example
x = 10
if x > 5:
print("x is greater than 5")
Output
x is greater than 5
[Link] Hand if
Short-hand if statement allows us to write a single-line if statement.
Syntax
if condition: statement
Example
a = 10
b=5
if a > b: print("a is greater than b")
Output
a is greater than b
[Link] Conditional Statement
If Else allows us to specify a block of code that will execute if the
condition(s) associated with an if or elif statement evaluates to False. Else block
provides a way to handle all other cases that don't meet the specified conditions.
Syntax
if condition:
statement(s)
else:
statement(s)
Example
x=3
if (x % 2) == 0:
print("Even number")
else:
print("Odd number")
Output
Odd number
[Link] Statement
elif statement in Python stands for "else if." It allows us to check multiple
conditions, providing a way to execute different blocks of code based on which
condition is true. Using elif statements makes our code more readable and efficient
by eliminating the need for multiple nested if statements.
Syntax
if condition1:
statement(s)
elif condition2:
statement(s)
else:
statement(s)

Example
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")
Output
Grade B

[Link] if..else Conditional Statement


Nested if..else means an if-else statement inside another if statement. We can use
nested if statements to check conditions within conditions.

Syntax
if condition1:
if condition2:
statement(s)
Example
num = 20
if num > 0:
if num % 2 == 0:
print("Positive Even Number")
Output
Positive Even Number

[Link] Conditional Statement


A ternary conditional statement is a compact way to write an if-else condition in a
single line. It’s sometimes called a "conditional expression."
Syntax
statement1 if condition else statement2
Example
a = 10
b = 20
print("a is greater") if a > b else print("b is greater")
Output
b is greater
Looping Statements in Python
Loops are used to execute a block of code repeatedly until a condition is
satisfied.
Python provides two main looping statements:
1. for loop (counting through items
2. while loop (based on conditions).
For Loop
loops is used to iterate over a sequence such as a list, tuple, string or range.
It allow to execute a block of code repeatedly, once for each item in the sequence.
Syntax
for variable in sequence:
statement(s)

Example1:
numbers = [10, 20, 30, 40, 50]
for num in numbers:
print(num)

Output
10
20
30
40
50

Example2:
n=4
for i in range(0, n):
print(i)

Output
0
1
2
3
Example3: Iterating by Index of Sequences
We can also use the index of elements in the sequence to iterate. The key
idea is to first calculate the length of the list and then iterate over the sequence
within the range of this length.
fruits = ["apple", "banana", "mango"]

for i in range(len(fruits)):
print(i, fruits[i])
Output
0 apple
1 banana
2 mango

While Loop
In Python, 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 condition:
statement(s)

Example
i=1
while i <= 5:
print(i)
i=i+1
Output
1
2
3
4
5
Nested Loops
Python programming language allows to use one loop inside another loop
which is called nested loop.
Syntax
for i in range():
for j in range():
statement(s)
Example
for i in range(1, 4):
for j in range(1, 3):
print(i, j)
Output
11
12
21
22
31
32
Loop Control Statements in Python
Loop control statements are used to change the normal flow of execution of
a loop. They allow us to stop, skip, or do nothing during loop execution based on a
condition.
Python provides three loop control statements:
1. break Statement
2. continue Statement
3. pass Statement
1. break Statement
The break statement is used to terminate the loop immediately, even if the
loop condition is still true.
Example:
for i in range(1, 6):
if i == 3:
break
print(i)
Output:
1
2

[Link] Statement
The continue statement is used to skip the current iteration of the loop and
continue with the next iteration.
Example:
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
[Link] Statement
The pass statement is used as a null statement. It does nothing and is used when a
statement is syntactically required but no action is needed.
Example:
for i in range(5):
pass

Literals in Python
Literals are fixed values assigned directly to variables. They represent
constant data stored in a variable.
Types of Literals in Python
1. Numeric Literals
Numeric literals represent numbers.
a) Integer Literals
a = 10
b = -25
c=0
b) Floating-point Literals
x = 3.14
y = -0.5
c) Complex Literals
z = 2 + 3j
[Link] Literals
String literals are a sequence of characters enclosed in quotes.
Example
name = "Python"
msg = 'Programming'
text = """Python
is
easy"""
Enclosed in triple single (''' ''') or triple double (""" """) quotes, generally used for
multi-line strings
Boolean Literals
Boolean literals represent truth values in Python. They help in decision-making
and logical operations. Boolean literals are useful for controlling program flow in
conditional statements like if, while, and for loops.
Types of Boolean Literals:
 True – Represents a positive condition (equivalent to 1).
 False – Represents a negative condition (equivalent to 0).
Collection Literals
Python provides four different types of literal collections:
 List literals: [1, 2, 3]
 Tuple literals: (1, 2, 3)
 Dictionary literals: {"key": "value"}
 Set literals: {1, 2, 3}

You might also like