Introduction to Python
Python is a high-level, general-purpose programming language. Python can
be used in a wide range of applications, from website development and data
analysis to machine learning and automation.
Features of Python
Python is a high-level language. It is a free and open-source
language.
It is an interpreted language, as Python programs are executed by an
interpreter.
Python programs are easy to understand
Python is case-sensitive. For example, NUMBER and number are not
same in Python.
Python is platform independent, means it can run on various operating
systems and hardware platforms.
Python has a rich library of predefined functions.
Python is also helpful in web development. Many popular web
services and applications are built using Python.
Executing a simple “hello world” program
To execute a simple “hello world” program in Python, write the following
program.
print("Hello, World!")
Execution Modes
There are two ways to use the Python interpreter:
Interactive mode
Script mode
Interactive Mode
Programmers can quickly run the commands and try out or test code without
generating a file by using the Python interactive mode, commonly known as
the Python interpreter or Python shell.
Script Mode
In the script mode, a Python programme can be written in a file, saved, and
then run using the interpreter.
Python scripts are stored in files with the “.py” extension. Python scripts are
saved by default in the Python installation folder.
Python character set
The character set in Python refers to the collection of characters used in
writing Python programs. Python supports various characters, including:
Letter: Python allows both uppercase (A – Z) and lowercase (a – z)
letters.
Digit: Digits (0 – 9) can be used but cannot be the first character of a
variable.
Special Characters: Python supports special characters like arithmetic
operators (+, -, *, /), special symbols (@, #, %, $), and brackets ({}, [],
()).
Escape Sequences: Python uses backslash (\) for escape sequences.
New line (\n), tab (\t)
Unicode Characters: Python supports Unicode characters, emojis and
mathematical symbols. smiley = “????”
Python Keywords
Keywords are reserved words. Each keyword has a specific meaning to the
Python interpreter, and we can use a keyword in our program only for the
purpose for which it has been defined. As Python is case sensitive, keywords
must be written exactly.
Identifiers
Identifiers are names used in programming languages to identify a variable,
function, or other things in a programme. Python has the following guidelines
for naming an identifier:
The name should begin with an uppercase or a lowercase alphabet or
an underscore sign (_).
It can be of any length.
It should not be a keyword or reserved word.
We cannot use special symbols like !, @, #, $, %, etc.
Literal in Python
In Python, a literal represents a fixed value directly using the program. It is raw
data assigned to a variable. Literals are immutable, meaning the value of a
literal cannot be changed during program execution.
Python supports several types of literals:
Numeric Literals: integer_literal = 100, float_literal = 10.5,
complex_literal = 3 + 5j
String Literals: string_literal = ‘Hello, Python!’
Boolean Literals: boolean_literals = True
Special Literals: x = None
List Literals: my_list = [1, “Amit”, 34]
Tuple Literals: my_tuple = (1, “Amit”, 34)
Dictionary literals: my_dict = {“rollno”: 1, “name”: “Amit”, “age”: 34}
Set Literal: my_set = {1, 2, 3}
Operator in Python
Operators are specialized symbols that perform arithmetic or logical
operations. The operation in the variable is applied using operands. The
python operators are:
Arithmetic operators (+, -, * /, %, **, //)
Bitwise operators (&, ^, |)
Shift operators (<<, >>)
Identity operators (is, is not)
Relational operators (>, <, >=, <=, ==, !=)
Logical operators (and, or)
Assignment operator ( = )
Membership operators (in, not in)
Arithmetic-assignment operators (/=, +=, -=, %=, **=, //=).
Punctuator in Python
The structures, statements, and expressions in Python are organized using
these symbols known as punctuators. Several punctuators are in python [ ] { }
( ) @ -= += *= //= **== = , etc.
Variables
A variable is used to hold the values. In Python, the term “variable” refers to
an object, where a variable points to objects in memory. A variable’s value can
be a string, such as “Amit”, or a number, such as “345”, or any combination of
alphanumeric characters (CD67). In Python, we can create new variables and
give them particular values by using an assignment operator (=).
gender = ‘M’
message = “Keep Smiling”
price = 987.9
Concept of l-value and r-value
In Python, “L-value” refers to a memory location that identifies an object, and
“R-value” refers to the data value that is stored at some address in memory.
Example,
L – Value: This refers to the variable name which helps to hold the R –
Values. Example, x = 10 (‘x’ is the l-value)
R – Value: This refers to the actual data or object being assigned to
the l-value. Example, y = x + 5 (‘x + 5’ is the r-value)
Comments
In the source code, comments are used to add remarks or notes in the
program. The interpreter uses comments to make the source code simpler
and easy to understand for the programmer. Comments always start with #.
Example,
#Add your python comments
Data Types
In Python, each value corresponds to a certain data type. A variable’s data
type describes the kinds of data values it can store and the types of
operations it can execute on that data. The data types that Python.
Number
Only numerical values are stored in the Number data type. Three other
categories are used to further categories it: int, float, and complex.
Sequence
An ordered group of things, each of which is identified by an integer index, is
referred to as a Python sequence. Strings, Lists, and Tuples are the three
different forms of sequence data types that are available in Python.
1. String – A string is a collection of characters. These characters could
be letters, numbers, or other special characters like spaces. Single or
double quotation marks are used to surround string values for example,
‘Hello’ or “Hello”).
2. List – List is a sequence of items separated by commas and the items
are enclosed in square brackets [ ]. example list1 = [5, 3.4, “New Delhi”,
“20C”, 45]
3. Tuple – A tuple is a list of elements enclosed in parenthesis and
separated by commas ( ). Compared to a list, where values are denoted
by brackets [], this does not. We cannot alter the tuple once it has been
formed. example tuple1 = (10, 20, “Apple”, 3.4, ‘a’)
Set
A set is a group of elements that are not necessarily in any particular order
and are enclosed in curly brackets. The difference between a set and a list is
that a set cannot include duplicate entries. A set’s components are fixed once
it is constructed. examle set1 = {10,20,3.14,”New Delhi”}
None
A unique data type with only one value is called None. It is employed to
denote a situation’s lack of worth. None is neither True nor False, and it does
not support any special operations (zero). example myVar = None
Mapping
Python has an unordered data type called mapping. Python currently only
supports the dictionary data type as a standard mapping data type.
1. Dictionary – Python’s dictionary stores data elements as key-value
pairs. Curly brackets are used to surround words in dictionaries.
Dictionary use enables quicker data access. example, dict1 =
{‘Fruit’:’Apple’, ‘Climate’:’Cold’, ‘Price(kg)’:120}
Mutable and Immutable Data Types
Once a variable of a certain data type has been created and given values,
Python does not enable us to modify its values. Mutable variables are those
whose values can be modified after they have been created and assigned.
Immutable variables are those whose values cannot be modified once they
have been created and assigned.
Expressions
Expressions are fundamental building blocks of Python code. They are a
combination of values, variables, operators, and function calls that the
interpreter can evaluate to produce a result.
For example:
5 + 3: This equation is an expression that adds two numbers.
x * 2: If x = 4, this expression would evaluate to 8.
‘Hello’ + ‘ World’: This joins two strings to form “Hello World.”
Order of Precedence
Order of
Operators Description
Precedence
1 ** Exponentiation (raised to the power)
Complement, unary plus and unary
2 ~ ,+, –
minus
Multiply, divide, modulo and floor
3 ,/, %, //
division
4 +, – Addition and subtraction
5 <= ,< ,> ,>= Relational operators
Order of
Operators Description
Precedence
6 == ,!= Equality operators
7 =, %=, /=, //=, -=, +=, *=, **= Assignment operators
8 is, is not Identity operators
9 in, not in Membership operators
10 not, or, and Logical operators
Statement
In Python, a statement is a unit of code that the Python interpreter can
execute.
x=4 #assignment statement
cube = x ** 3 #assignment statement
print (x, cube) #print statement
4 64
Input and Output
The input() function allows a program to receive data from the user and the
print() function allows a program to display data to the user.
fname = input("Enter your first name: ")
age = input("Enter your age: ")
print(fname + age)
Statement Output
print(“Hello”) Hello
print(10*2.5) 25.0
print(“I” + “love” + “my” + “country”) Ilovemycountry
print(“I’m”, 16, “years old”) I’m 16 years old
Type Conversion
Type conversion is also known as type casting in Python. Type conversion
refers to the process of changing a value from one data type to another.
Python supports two main types of type conversion:
1. Explicit Conversion
2. Implicit Conversion
Explicit Conversion
Explicit type conversion, also known as type casting, is used when a
programmer manually converts a value from one data type to another using a
built-in function, such as int(), float(), or str().
Type Conversion between Numbers and Strings
num_str = "10" # A string
num_int = int(num_str) # Convert string to integer
print(num_int) # Output: 10
print(type(num_int)) # Output: <class 'int'>
Implicit Conversion
When Python converts data types automatically without a programmer’s
instruction, this is referred to as implicit conversion, also known as coercion.
Implicit type conversion from int to float
num_int = 5 # Integer
num_float = 2.5 # Float
result = num_int + num_float
print(result) # Output: 7.5
print(type(result)) # Output: <class 'float'>
Debugging
Debugging is the process of finding and fixing errors, or ‘bugs,’ in
programming code. It involves identifying the type of error—whether it is a
syntax error, runtime error, or logical error—and resolving it to ensure the
program runs correctly. There are three types of errors:
1. Syntax errors
2. Logical errors
3. Runtime errors
Syntax Errors
When the code does not follow the rules of the programming language.
Example: missing parentheses in Python.
print("Hello" # SyntaxError: missing closing parenthesis
Logical Errors
Logical errors do not crash the program but generate incorrect output due to
incorrect logic.
x = 10
y=5
result = x - y # Logical error: should be x + y
print("Result:", result) # Expected output: 15, but prints 5
Runtime Error
A runtime error occurs when the program is running, and an error is generated
due to invalid operations like dividing by zero.
num = 5 / 0 # RuntimeError: division by zero