0% found this document useful (0 votes)
19 views52 pages

Unit - I - Python Programming

The document provides an overview of Python programming, including its history, features, and basic concepts such as literals, constants, variables, identifiers, and keywords. It emphasizes Python's readability, ease of use for beginners, and its object-oriented nature. Additionally, it covers the types of literals and rules for naming variables and identifiers 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)
19 views52 pages

Unit - I - Python Programming

The document provides an overview of Python programming, including its history, features, and basic concepts such as literals, constants, variables, identifiers, and keywords. It emphasizes Python's readability, ease of use for beginners, and its object-oriented nature. Additionally, it covers the types of literals and rules for naming variables and identifiers 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

UNIT - I

Basics of python programming: history of python - features of python -


literal - constants - variables - identifiers - keywords - built-in data types
- output statements - input statements - comments - indentation -
operators - expressions - type conversion. Python arrays: defining and
processing arrays - array methods.

Python Introduction

 Python was created by Guido van Rossum in 1991 and further


developed by the Python Software Foundation.
 It was designed with focus on code readability and its syntax
allows us to express concepts in fewer lines of code.

Definition

 Python is a high-level, interpreted, interactive and object-oriented


scripting language. Python is designed to be highly readable.
 It uses English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than other
languages.

Python is Interpreted: Python is processed at runtime by the


interpreter. You do not need to compile your program before executing it.

Python is Interactive: You can actually sit at a Python prompt and


interact with the interpreter directly to write your programs.

Python is Object-Oriented: Python supports Object-Oriented style or


technique of programming that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for the
beginner-level programmers and supports the development of a wide
range of applications from simple text processing to WWW browsers to
games.

History of Python

 Python was developed by Guido van Rossum in the late eighties


and early nineties at the National Research Institute for
Mathematics and Computer Science in the Netherlands.
 Python is derived from many other languages, including ABC,
Modula-3, C, C++, Algol-68, SmallTalk, Unix shell, and other
scripting languages.
 At the time when he began implementing Python, Guido van
Rossum was also reading the published scripts from "Monty
Python's Flying Circus" (a BBC comedy series from the seventies, in
the unlikely case you didn't know). It occurred to him that he
needed a name that was short, unique, and slightly mysterious, so
he decided to call the language Python.
 Python is now maintained by a core development team at the
institute, although Guido van Rossum still holds a vital role in
directing its progress.
 Python 1.0 was released on 20 February, 1991.
 Python 2.0 was released on 16 October 2000 and had many major
new features, including a cycle detecting garbage collector and
support for Unicode. With this release the development process was
changed and became more transparent and communitybacked.
 Python 3.0 (which early in its development was commonly referred
to as Python 3000 or py3k), a major, backwards-incompatible
release, was released on 3 December 2008 after a long period of
testing. Many of its major features have been back ported to the
backwards-compatible Python 2.6.x and 2.7.x version series.
 In January 2017 Google announced work on a Python 2.7 to go
transcompiler, which The Register speculated was in response to
Python 2.7's planned end-of-life.

Features of Python

 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 crossplatform compatible on UNIX, Windows, and
Macintosh.
 Interactive Mode: Python has support for an interactive mode
which allows interactive testing and debugging of snippets of code.
 Portable: Python can run on a wide variety of hardware platforms
and has the same interface on all platforms.
 Extendable: You can add low-level modules to the Python
interpreter. These modules enable programmers to add to or
customize their tools to be more efficient.
 Databases: Python provides interfaces to all major commercial
databases.
 GUI Programming: Python supports GUI applications that can be
created and ported to many system calls, libraries, and windows
systems, such as Windows MFC, Macintosh, and the X Window
system of UNIX.
 Scalable: Python provides a better structure and support for large
programs than shell scripting

Understanding Hello World Program in Python

 Hello, World! in python is the first python program which we learn


when we start learning any program.
 It’s a simple program that displays the message “Hello, World!” on
the screen.

Here’s the “Hello World” program:

# This is a comment. It will not be executed.

print("Hello, World!")

Output

Hello, World!
How does this work:
 print() is a built-in Python function that tells the computer to
show something on the screen.
 The message "Hello, World!" is a string, which means it's just text.
In Python, strings are always written inside quotes (either single ' or
double ").
 Anything after # in a line is a comment. Python ignores comments
when running the code, but they help people understand what the
code is doing.
 Comments are helpful for explaining code, making notes or
skipping lines while testing.

Literals

Literals in Python are fixed values written directly in the code that
represent constant data. They provide a way to store numbers, text, or
other essential information that does not change during program
execution. Python supports different types of literals, such as numeric
literals, string literals, Boolean literals, and special values like
None. For example:
 10, 3.14, and 5 + 2j are numeric literals.
 'Hello' and "Python" are string literals.
 True and False are Boolean literals.

1. Numeric Literals
Numeric literals represent numbers and are classified into three types:
 Integer Literals – Whole numbers (positive, negative, or zero)
without a decimal point. Example: 10, -25, 0
 Floating-point (Decimal) Literals – Numbers with a decimal
point, representing real numbers. Example: 3.14, -0.01, 2.0
 Complex Number Literals – Numbers in the form a + bj, where a
is the real part and b is the imaginary part. Example: 5 + 2j, 7 - 3j

# Integer literals
a = 100
b = -50

# Floating-point literals
c = 3.14
d = -0.005

# Complex number literals


e = 4 + 7j
f = -3j

print(a, b, c, d, e, f)

Output

100 -50 3.14 -0.005 (4+7j) (-0-3j)

2. String Literals
String literals are sequences of characters enclosed in quotes. They are
used to represent text in Python.
Types of String Literals:
 Single-quoted strings – Enclosed in single quotes (' '). Example:
'Hello, World!'
 Double-quoted strings – Enclosed in double quotes (" "). Example:
"Python is fun!"
 Triple-quoted strings – Enclosed in triple single (''' ''') or triple
double (""" """) quotes, generally used for multi-line strings or
docstrings. Example:
'''This is
a multi-line
string'''

 Raw strings – Prefix with r to ignore escape sequences (\n, \t,


etc.). Example: r"C:\Users\Python" (backslashes are treated as
normal characters).
# Different string literals

a = 'Hello' # Single-quoted

b = "Python" # Double-quoted

c = '''This is

a multi-line string''' # Triple-quoted

d = r"C:\Users\Python" # Raw string

print(a)

print(b)

print(c)

print(d)
Output

Hello

Python

This is

a multi-line string

C:\Users\Python

3. 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).

# Boolean literals
a = True
b = False

print(a, b) # Output: True False


print(1 == True) # Output: True
print(0 == False) # Output: True
print(True + 5) # Output: 6 (1 + 5)
print(False + 7) # Output: 7 (0 + 7)

Explanation:
 True is treated as 1, and False is treated as 0 in arithmetic
operations.
 Comparing 1 == True and 0 == False returns True because Python
considers True as 1 and False as 0.

4. 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}

Rank = ["First", "Second", "Third"] # List


colors = ("Red", "Blue", "Green") # Tuple
Class = { "Jai": 10, "Anaya": 12 } # Dictionary
unique_num = {1, 2, 3} # Set

print(Rank, colors, Class, unique_num)

Output

['First', 'Second', 'Third'] ('Red', 'Blue', 'Green') {'Jai': 10, 'Anaya': 12} {1, 2, 3}

Special Literal
Python contains one special literal (None). 'None' is used to define a null
variable. If 'None' is compared with anything else other than a 'None', it
will return false.
res = None

print(res)

Output

None

Explanation: None represents "nothing" or "empty value."

Constants

In Python, constants are variables whose values are intended to remain


unchanged throughout a program. They are typically defined using
uppercase letters to signify their fixed nature, often with words
separated by underscores (e.g., MAX_LIMIT).
Example:

# Mathematical constant

PI = 3.14159

# Acceleration due to gravity

GRAVITY = 9.8

print(PI)

print(GRAVITY)
Output

3.14159

9.8

Rules while declaring a Constant


 Python constant and variable names can include:
o Lowercase letters (a-z)
o Uppercase letters (A-Z)
o Digits (0-9)
o Underscores (_)
 Naming rules for constants:
o Use UPPERCASE letters for constant names
(e.g., CONSTANT = 65).
o Do not start a constant name with a digit.
o Only the underscore (_) is allowed as a special character;
other characters (e.g., !, #, ^, @, $) are not permitted.

 Best practices for naming constants:


o Use meaningful and descriptive names (e.g., VALUE instead
of V) to make the code clearer and easier to understand.

Example of Constant
There are multiple use of constants here are some of the examples:
1. Mathematical Constant:
PI = 3.14159
E = 2.71828
GRAVITY = 9.8
2. Configuration settings:
MAX_CONNECTIONS = 1000
TIMEOUT = 15
3. UI Color Constants:
BACKGROUND_COLOR = "#FFFFFF"
TEXT_COLOR = "#000000"
BUTTON_COLOR = "#FF5733"

Variables
In Python, variables are used to store data that can be referenced and
manipulated during program execution. A variable is essentially a name
that is assigned to a value. Unlike many other programming languages,
Python variables do not require explicit declaration of type. The type of
the variable is inferred based on the value assigned.
Variables act as placeholders for data. They allow us to store and reuse
values in our program.
Example:

# Variable 'x' stores the integer value 10

x=5

# Variable 'name' stores the string "Samantha"

name = "SAASC"

print(x)

print(name)
Output
5

SAASC

Rules for Naming Variables


To use variables effectively, we must follow Python’s naming rules:
 Variable names can only contain letters, digits and underscores
(_).
 A variable name cannot start with a digit.
 Variable names are case-sensitive (myVar and myvar are
different).
 Avoid using Python keywords (e.g., if, else, for) as variable names.

Valid Example:

age = 21

_colour = "lilac"

total_score = 90

Invalid Example:

1name = "Error" # Starts with a digit

class = 10 # 'class' is a reserved keyword

user-name = "Doe" # Contains a hyphen


Assigning Values to Variables
Basic Assignment
Variables in Python are assigned values using the = operator.

x=5

y = 3.14

z = "Hi"

Dynamic Typing
Python variables are dynamically typed, meaning the same variable can
hold different types of values during execution.

x = 10

x = "Now a string"

Multiple Assignments
Python allows multiple variables to be assigned values in a single line.

Assigning the Same Value


Python allows assigning the same value to multiple variables in a single
line, which can be useful for initializing variables with the same value.

a = b = c = 100

print(a, b, c)
Output
100 100 100

Assigning Different Values


We can assign different values to multiple variables simultaneously,
making the code concise and easier to read.

x, y, z = 1, 2.5, "Python"

print(x, y, z)

Output
1 2.5 Python

Identifiers in Python
Identifier is a user-defined name given to a variable, function, class,
module, etc. The identifier is a combination of character digits and an
underscore. They are case-sensitive i.e., 'num' and 'Num' and 'NUM' are
three different identifiers in python. It is a good programming practice
to give meaningful names to identifiers to make the code
understandable.
We can also use the Python string isidentifier() method to check
whether a string is a valid identifier or not.
Rules for Naming Python Identifiers
 It cannot be a reserved python keyword.
 It should not contain white space.
 It can be a combination of A-Z, a-z, 0-9, or underscore.
 It should start with an alphabet character or an underscore ( _ ).
 It should not contain any special character other than an
underscore ( _ ).
Examples of Python Identifiers
Valid identifiers:
 var1
 _var1
 _1_var
 var_1
Invalid Identifiers
 !var1
 1var
 1_var
 var#1
 var 1

Keywords
Python Keywords are some predefined and reserved words in Python
that have special meanings. Keywords are used to define the syntax of
the coding. The keyword cannot be used as an identifier, function, or
variable name. All the keywords in Python are written in lowercase
except True and False. There are 35 keywords in Python.
Rules for Keywords in Python
 Python keywords cannot be used as identifiers.
 All the keywords in Python should be in lowercase except True
and False.
List of Python Keywords

Keywords
Description

This is a logical operator which returns true if both the


and operands are true else returns false.

This is also a logical operator which returns true if anyone


or operand is true else returns false.

This is again a logical operator it returns True if the


not operand is false else returns false.

if This is used to make a conditional statement.

Elif is a condition statement used with an if statement. The


elif statement is executed if the previous conditions were
elif not true.

Else is used with if and elif conditional statements. The


else else block is executed if the given condition is not true.

for This is used to create a loop.

while This keyword is used to create a while loop.

break This is used to terminate the loop.


Keywords
Description

as This is used to create an alternative.

def It helps us to define functions.

lambda It is used to define the anonymous function.

pass This is a null statement which means it will do nothing.

return It will return a value and exit the function.

True This is a boolean value.

False This is also a boolean value.

try It makes a try-except statement.

with The with keyword is used to simplify exception handling.

This function is used for debugging purposes. Usually used


assert to check the correctness of code

class It helps us to define a class.

continue It continues to the next iteration of a loop


Keywords
Description

del It deletes a reference to an object.

except Used with exceptions, what to do when an exception occurs

Finally is used with exceptions, a block of code that will be


finally executed no matter if there is an exception or not.

from It is used to import specific parts of any module.

global This declares a global variable.

import This is used to import a module.

It's used to check whether a value is present in a list,


in range, tuple, etc.

is This is used to check if the two variables are equal or not.

This is a special constant used to denote a null value or


avoid. It's important to remember, 0, any empty
none container(e.g empty list) do not compute to None

nonlocal It's declared a non-local variable.

raise This raises an exception.


Keywords
Description

yield It ends a function and returns a generator.

async It is used to create asynchronous coroutine.

await It releases the flow of control back to the event loop.

Built-in Data Types

 In programming, data type is an important concept.

 Variables can store data of different types, and different types can
do different things.

 Python has the following data types built-in by default, in these


categories:

1. Numeric Type

int: Integer values Example: 10, -3, 0

float: Floating point numbers (decimals) Example: 3.14, -0.001

complex: Complex numbers Example: 2 + 3j

2. Text Type

str: String(sequence of Unicode characters)Example: "Hello", 'Python'


3. Sequence Types

list: Ordered, mutable sequence

Example: [1, 2, 3], ['a', 'b']

tuple: Ordered, immutable sequence

Example: (1, 2, 3)

range: Immutable sequence of numbers

Example: range(5)

4. Mapping Type

dict: Collection of key-value pairs

Example: {'name': 'Alice', 'age': 30}

5. Set Types

set: Unordered collection of unique elements

Example: {1, 2, 3}

frozenset: Immutable version of a set

Example: frozenset([1, 2, 3])

6. Boolean Type

bool: Boolean values (subclass of in)

Values: True, False


[Link] Types

bytes: Immutable sequence of bytes

Example: b'hello'

bytearray: Mutable sequence of bytes

Example: bytearray([65, 66, 67])

memoryview: Memory view object of another binary object

Example: memoryview(b'abc')

8. None Type

NoneType: Represents the absence of a value

Value: None

Example:

# Numeric Types

a=5 # int

b = 3.14 # float

c = 2 + 4j # complex

# Text Type

text = "Python" # str


# Sequence Types

my_list = [1, 2, 3] # list

my_tuple = (4, 5, 6) # tuple

my_range = range(3) # range

# Mapping Type

my_dict = {'name': 'Alice', 'age': 25} # dict

# Set Types

my_set = {1, 2, 3} # set

my_frozenset = frozenset([1, 2]) # frozenset

# Boolean Type

is_valid = True # bool

# Binary Types

my_bytes = b'ABC' # bytes


my_bytearray = bytearray([65, 66, 67]) # bytearray

my_memory = memoryview(b'XYZ') # memoryview

# None Type

nothing = None # NoneType

Getting the Data Type

You can get the data type of any object by using the type() function:

Example

#Print the data type of the variable x:

x=5
print(type(x))

Output:
<class 'int'>

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

x = "Hello World"
#display x:
print(x)
#display the data type of x:
print(type(x))

Output:
HelloWorld
<class 'str'>

Input and Output in Python


Understanding input and output operations is fundamental to Python
programming. With the print() function, we can display output in
various formats, while the input() function enables interaction with
users by gathering input during program execution.
Taking input in Python
Python's input() function is used to take user input. By default, it
returns the user input in form of a string.
Example:

name = input("Enter your name: ")

print("Hello,", name, "! Welcome!")

Output
Enter your name: SAASC
Hello, SAASC! Welcome!

Printing Output using print() in Python


At its core, printing output in Python is straightforward, thanks to the
print() function. This function allows us to display text, variables and
expressions on the console. Let's begin with the basic usage of the
print() function:
In this example, "Hello, World!" is a string literal enclosed within double
quotes. When executed, this statement will output the text to the
console.

print("Hello, World!")

Output: Hello, World!

Printing Variables
We can use the print() function to print single and multiple variables.
We can print multiple variables by separating them with commas.

Example:
# Single variable

s = "Bob"

print(s)

# Multiple Variables

s = "Alice"

age = 25

city = "New York"

print(s, age, city)

Output
Bob

Alice 25 New York

Take Multiple Input in Python


We are taking multiple input from the user in a single line, splitting the
values entered by the user into separate variables for each value using
the split() method. Then, it prints the values with corresponding labels,
either two or three, based on the number of inputs provided by the
user.
# taking two inputs at a time

x, y = input("Enter two values: ").split()

print("Number of boys: ", x)

print("Number of girls: ", y)

# taking three inputs at a time

x, y, z = input("Enter three values: ").split()

print("Total number of students: ", x)

print("Number of boys is : ", y)

print("Number of girls is : ", z)

Python Comments
Comments in Python are the lines in the code that are ignored by the
interpreter during the execution of the program.
 Comments enhance the readability of the code.
 Comment can be used to identify functionality or structure the
code-base.
 Comment can help understanding unusual or tricky scenarios
handled by the code to prevent accidental removal or changes.
 Comments can be used to prevent executing any specific part of
your code, while making changes or testing.

# I am single line comment

""" Multi-line comment used

print("Python Comments") """

In Python, single line comments starts with hashtag symbol #.


# sample comment

name = "COMPUTER SCIENCE"

print(name)

Output

COMPUTER SCIENCE

Multi-Line Comments
Python does not provide the option for multiline comments. However,
there are different ways through which we can write multiline
comments.
Multiline comments using multiple hashtags (#)
We can multiple hashtags (#) to write multiline comments in Python.
Each and every line will be considered as a single-line comment.
# Python program to demonstrate

# multiline comments
print("Multiline comments")

""" Python program to demonstrate

multiline comments"""

print("Multiline comments")

Indentation
In Python, indentation is used to define blocks of code. It tells
the Python interpreter that a group of statements belongs to a specific
block. All statements with the same level of indentation are considered
part of the same block. Indentation is achieved using
whitespace (spaces or tabs) at the beginning of each line.
For Example:

if 10 > 5:

print("This is true!")

print("I am tab indentation")

print("I have no indentation")

Output
This is true!

I am tab indentation

I have no indentation
 The first two print statements are indented by 4 spaces, so they
belong to the if block.
 The third print statement is not indented, so it is outside the if
block.

If we Skip Indentation, Python will throw error.

Indentation in Conditional Statements


The lines print(‘GeeksforGeeks…’) and print(‘retype the URL.’) are two
separate code blocks. The two blocks of code in our example if-
statement are both indented four spaces. The final print(‘All set!’) is not
indented, so it does not belong to the else block.
a = 20

if a >= 18:

print('GeeksforGeeks...')

else:
print('retype the URL.')

print('All set !')

Output
GeeksforGeeks...

All set !

Indentation in Loops
To indicate a block of code in Python, we must indent each line of the
block by the same whitespace. The two lines of code in the while loop
are both indented four spaces. It is required for indicating what block of
code a statement belongs to.

j=1

while(j<= 5):

print(j)

j=j+1

Output
1

4
5

Operators
In Python programming, Operators in general are used to perform
operations on values and variables. These are standard symbols used
for logical and arithmetic operations. In this article, we will look into
different types of Python operators.
 OPERATORS: These are the special symbols. Eg- + , * , /, etc.
 OPERAND: It is the value on which the operator is applied.
Types of Operators in Python

Arithmetic Operators in Python


Python Arithmetic operators are used to perform basic mathematical
operations like addition, subtraction, multiplication and division.
# Variables

a = 15
b=4

# Addition

print("Addition:", a + b)

# Subtraction

print("Subtraction:", a - b)

# Multiplication

print("Multiplication:", a * b)

# Division

print("Division:", a / b)

# Floor Division

print("Floor Division:", a // b)

# Modulus
print("Modulus:", a % b)

# Exponentiation

print("Exponentiation:", a ** b)

Output
Addition: 19

Subtraction: 11

Multiplication: 60

Division: 3.75

Floor Division: 3

Modulus: 3

Exponentiation: 50625

Comparison of Python Operators


In Python Comparison of Relational operators compares the values. It
either returns True or False according to the condition.
Example of Comparison Operators in Python
Let's see an example of Comparison Operators in Python.
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

Logical Operators in Python


Python Logical operators perform Logical AND, Logical
OR and Logical NOT operations. It is used to combine conditional
statements.
The precedence of Logical Operators in Python is as follows:
1. Logical not
2. logical and
3. logical or
Example of Logical Operators in Python:
a = True

b = False

print(a and b)

print(a or b)
print(not a)

Output
False

True

False

Bitwise Operators in Python


Python Bitwise operators act on bits and perform bit-by-bit
operations. These are used to operate on binary numbers.
Bitwise Operators in Python are as follows:
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
Example of Bitwise Operators in Python:
a = 10

b=4

print(a & b)

print(a | b)

print(~a)

print(a ^ b)

print(a >> 2)
print(a << 2)

Output
0

14

-11

14

40

Assignment Operators in Python


Python Assignment operators are used to assign values to the
variables. This operator is used to assign the value of the right side of
the expression to the left side operand.
Example of Assignment Operators in Python:
a = 10

b=a

print(b)

b += a

print(b)

b -= a

print(b)

b *= a

print(b)
b <<= a

print(b)

Output
10

20

10

100

102400

Identity Operators in Python


In Python, is and is not are the identity operators both are used to
check if two values are located on the same part of the memory. Two
variables that are equal do not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical

Example of Identity Operators in Python:


a = 10

b = 20

c=a

print(a is not b)

print(a is c)
Output
True

True

Membership Operators in Python


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
Examples of Membership Operators in Python:
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

Ternary Operator in Python


in Python, Ternary operators also known as conditional expressions
are operators that evaluate something based on a condition being
true or false. It was added to Python in version 2.5.
It simply allows testing a condition in a single line replacing the
multiline if-else making the code compact.
Syntax : [on_true] if [expression] else [on_false]

Examples of Ternary Operator in Python:


a, b = 10, 20

min = a if a < b else b

print(min)

Output
10

Expressions
1. Definition
In Python, an expression is any legal combination of literals (constants),
variables, operators, and function calls that can be evaluated to produce
a value.
Example:
5 + 3 → Here, 5 and 3 are constants, '+' is the operator, and the result is
8.

2. Characteristics of Expressions
- Always produce a value after evaluation.
- Can be used anywhere a value is required.
- Can be simple (like 10) or complex (like (x * y) + (z / 2)).

3. Components of an Expression
Component Example Description

Values (Literals) 100, "Hello" Constant data


values

Variables x, name Named storage for


values

Operators +, -, *, / Symbols for


operations

Function calls len("Python") Execute built-in or


user-defined
functions

4. Types of Expressions in Python


4.1 Arithmetic Expressions
Perform mathematical calculations using operators like +, -, *, /, %, //,
**.
Example:
a=8
b=3
print(a + b) # 11
print(a - b) # 5
print(a * b) # 24
print(a / b) # 2.666...
print(a // b) # 2
print(a % b) # 2
print(a ** b) # 512

4.2 Relational (Comparison) Expressions


Compare two values and return True or False using operators like ==, !=,
<, >, <=, >=.
Example:
x = 10
y = 20
print(x > y) # False
print(x == y) # False
print(x != y) # True

4.3 Logical Expressions


Combine multiple conditions using and, or, not.
Example:
age = 18
citizen = True
print(age >= 18 and citizen) # True
print(age >= 18 or citizen) # True
print(not citizen) # False

4.4 String Expressions


Perform operations on strings using + (concatenation), * (repetition).
Example:
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2) # Hello World
print(s1 * 3) # HelloHelloHello

4.5 Sequence/List Expressions


Operations on lists, tuples, and other sequences.
Example:
numbers = [1, 2, 3]
print(numbers + [4, 5]) # [1, 2, 3, 4, 5]
print(numbers * 2) # [1, 2, 3, 1, 2, 3]

4.6 Conditional Expressions (Ternary)


Shorthand for if-else to select a value.
Example:
x=5
y = 10
result = x if x > y else y
print(result) # 10

5. Expression vs Statement
Expression Statement

Produces a value Performs an action

Can be part of a statement Cannot always be used where a


value is expected

Example: 2 + 3 Example: x = 2 + 3
6. Example Program

x = 15
y=4

# Arithmetic expression
sum_result = x + y

# Relational expression
is_greater = x > y

# Logical expression
logic_check = (x > 10) and (y < 10)

# String expression
greeting = "Hi" + " " + "Python"

# List expression
numbers = [1, 2] + [3, 4]

print("Sum:", sum_result)
print("Is x greater than y?", is_greater)
print("Logical check:", logic_check)
print("Greeting:", greeting)
print("Numbers List:", numbers)

Output:
Sum: 19
Is x greater than y? True
Logical check: True
Greeting: Hi Python
Numbers List: [1, 2, 3, 4]

Note:

- Every expression produces a value.


- Expressions can be nested inside one another.
- Statements may contain expressions.
- Expressions are the building blocks of Python programs.

Type Conversion

1. Definition
Type conversion is the process of converting the value of one data type
into another data type. Python supports two types of type conversion:
1. Implicit Type Conversion (Type Casting by Python)
2. Explicit Type Conversion (Type Casting by the programmer)

2. Implicit Type Conversion (Type Casting by Python)


- Also called Type Casting or Type Promotion.
- Python automatically converts smaller data types into larger data types
to prevent data loss.
- The programmer does not need to write any code for conversion.

Example:
x=5 # int
y = 2.5 # float
result = x + y # int + float → float
print(result) # 7.5
print(type(result)) # <class 'float'>

Explanation: x (integer) is automatically converted into float before


addition.

3. Explicit Type Conversion (Type Casting by Programmer)


- Conversion is done manually by using Python’s built-in functions.
- Common functions:
- int() → converts to integer
- float() → converts to float
- str() → converts to string
- list() → converts to list
- tuple() → converts to tuple
- set() → converts to set

Examples:
# Integer to Float
x = 10
y = float(x)
print(y) # 10.0
print(type(y)) # <class 'float'>

# Float to Integer
a = 7.9
b = int(a)
print(b) #7
print(type(b)) # <class 'int'>
# String to Integer
s = "100"
num = int(s)
print(num + 50) # 150

# Integer to String
n = 25
text = str(n)
print(text + " is my age") # 25 is my age

Note:
- Implicit conversion happens automatically; explicit conversion must be
done manually.
- When converting strings to numbers, the string must contain only
numeric values.
- Conversion from float to int truncates the decimal part (does not round
off).

5. Example Program
# Type Conversion in Python

# Implicit Conversion
num_int = 123
num_float = 1.23
num_new = num_int + num_float

print("Value:", num_new)
print("Type:", type(num_new))
# Explicit Conversion
num_str = "456"
num_int2 = int(num_str)

print("String to Integer:", num_int2)


print("Type:", type(num_int2))

Output:
Value: 124.23
Type: <class 'float'>
String to Integer: 456
Type: <class 'int'>

Python Arrays: Defining and Processing Arrays – Array


Methods

1. Introduction to Arrays in Python


An array is a data structure that stores multiple items of the same type
in a single variable. In Python, arrays are not built-in like lists; we use
the 'array' module to create them.

Syntax:
import array
[Link](typecode, [initial_elements])

2. Typecodes for Arrays


Typecode C Type Python Type Size (bytes)

b signed char int 1


B unsigned char int 1

i signed int int 2 or 4

I unsigned int int 2 or 4

f float float 4

d double float 8

3. Defining Arrays
Example:
import array as arr

# Create an integer array


numbers = [Link]('i', [10, 20, 30, 40, 50])

print(numbers) # array('i', [10, 20, 30, 40, 50])


print(numbers[0]) # Access first element
print(numbers[-1]) # Access last element

4. Processing Arrays
Traversing (Looping through an array)
for num in numbers:
print(num)

Updating elements
numbers[2] = 99
print(numbers) # array('i', [10, 20, 99, 40, 50])

Inserting elements
[Link](1, 15)
print(numbers) # array('i', [10, 15, 20, 99, 40, 50])
Deleting elements
[Link](99)
print(numbers) # array('i', [10, 15, 20, 40, 50])

5. Common Array Methods


Method Description

append(x) Adds element x to the end

insert(i, x) Inserts x at index i

remove(x) Removes first occurrence of x

pop([i]) Removes element at index i (or


last if index not given)

index(x) Returns first index of value x

reverse() Reverses the array

buffer_info() Returns tuple with memory


address and number of
elements

count(x) Counts occurrences of x

extend(iterable) Appends elements from another


iterable

fromlist(list) Adds elements from a list

tolist() Converts array to list

Example Program using Array Methods


import array as arr
# Create array
nums = [Link]('i', [1, 2, 3])

# Append element
[Link](4)
print(nums) # array('i', [1, 2, 3, 4])

# Insert element
[Link](1, 10)
print(nums) # array('i', [1, 10, 2, 3, 4])

# Remove element
[Link](2)
print(nums) # array('i', [1, 10, 3, 4])

# Pop element
[Link]()
print(nums) # array('i', [1, 10, 3])

# Reverse array
[Link]()
print(nums) # array('i', [3, 10, 1])

# Convert to list
lst = [Link]()
print(lst) # [3, 10, 1]

Output:
array('i', [1, 2, 3, 4])
array('i', [1, 10, 2, 3, 4])
array('i', [1, 10, 3, 4])
array('i', [1, 10, 3])
array('i', [3, 10, 1])
[3, 10, 1]

Note:
- Arrays store elements of the same type.
- Lists can store different data types, but arrays are more memory-
efficient for same-type data.
- Must use array module to create arrays.
- Use typecode to define the type of array elements.

You might also like