Notes
Notes
Language
1. Programming Language
A programming language is a formal language comprising a set of instructions that produce
various kinds of output. These languages are used in computer programming to implement
algorithms and control the behavior of machines.
Python is a high-level, interpreted, and general-purpose programming language known for
its readability and simplicity.
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.
Key Features of Python
Python’s simple and readable syntax makes it beginner-friendly.
Python runs seamlessly on Windows, macOS and Linux.
Includes libraries for tasks like web development, data analysis and
machine learning.
Variable types are determined automatically at runtime, simplifying
code writing.
Supports multiple programming paradigms, including object-oriented,
functional and procedural programming.
Python is free to use, distribute and modify.
Introduction to Python Programming Language
1. Programming Language
A programming language is a formal set of instructions used to produce various outputs such
as applications and programs. It is used to write software programs, scripts, and other sets of
instructions for computers to execute.
3. Features of Python
4. Limitations of Python
Memory Management ? Python uses a garbage collector to manage memory and clean up unused
objects automatically. While this can make writing and maintaining code easier, it can also lead to
inefficiencies and slowdowns if not used properly. Additionally, Python does not provide low-level
memory access, making writing memory-intensive or real-time applications difficult.
Concurrency and Parallelism ? Python is not designed for concurrent or parallel programming. It
uses a global interpreter lock (GIL) to prevent multiple threads from executing simultaneously, which
can limit the performance of multi-threaded applications. While there are ways to work around the
GIL, they can be complex and difficult to implement.
Static Typing ? Python is a dynamically typed language, which means that variables do not have a
fixed type and can be assigned any value at any time. While this can be convenient and flexible, it
can also make catching errors or bugs at compile time difficult. In contrast, statically typed languages
like Java or C++ require variables to be explicitly declared with a specific type, which can help to
prevent errors and improve code quality.
Limited Web Support ? Python is not as widely supported on the web as other languages like
JavaScript or PHP. While it can be used for server-side web development, it is not as well-suited for
client-side development or front-end scripting. Additionally, some web browsers and platforms do
not have built-in Python support, making it difficult to use in web-based applications.
Python does not support operator overloading, so developers cannot define custom behavior for
built-in operators like + or -. This can make it difficult to define custom types or data structures that
use these operators naturally and intuitively.
Python's standard library is not as extensive as other languages like Java or C++. This means that
developers may need to rely on third-party libraries or frameworks to access certain functionality,
which can add complexity and dependencies to their projects.
Python's syntax is not as concise or readable as some other languages. This can make it more
difficult for new developers to learn and understand, making code more verbose and harder to
maintain.
Python does not support multiple inheritances, which means that classes cannot inherit from more
than one superclass. This can make it more difficult to reuse or combine existing code and limit the
language's flexibility and expressiveness.
Python is not well-suited for mobile development. While it is possible to use Python for Android or
iOS apps, it is not as widely supported or optimized for mobile platforms compared to languages like
Java or Swift.
Python's dynamic nature can make it difficult to perform static analysis or optimization. This can
make it harder to optimize the performance or efficiency of Python code, making it more difficult to
integrate with other languages or tools.
1. Visit https://www.python.org
2. Download the latest stable version.
3. Run the installer and follow instructions.
4. Select "Add Python to PATH" during installation.
python --version
8. Running Python
Interactive Mode:
o Open command prompt/terminal and type python.
o Execute commands line by line.
Script Mode:
o Write code in a .py file.
o Run using:
python filename.py
9. First Python Program
print("Hello, World!")
Steps:
python hello.py
10. Python Interactive Help Feature
help()
help(print)
11. Python Differences from Other Languages
Feature Python Other Languages
Python Keywords
Keywords are reserved words. Each keyword has a specific meaning to the
Python interpreter. As Python is case sensitive, keywords must be written
exactly as given in Table
IDENTIFIERS
In programming languages, identifiers are names used to identify a
variable, function, or other entities in a program. The rules for naming an
identifier in Python are as follows:
VARIABLES
Variable is an identifier whose value can change. For example variable
age can have different value for different person. Variable name should be
unique in a program. Value of a variable can be string (for example, ‘b’,
‘Global Citizen’), number (for example 10,71,80.52) or any combination of
alphanumeric (alphabets and numbers for example ‘b10’) characters. In
Python, we can use an assignment statement to create new variables and
assign specific values to them.
Variables must always be assigned values before they are used in the
program, otherwise it will lead to an error. Wherever a variable name
occurs in the program, the interpreter replaces it with the value of that
particular variable.
Program 3-2 Write a Python program to find the sum of two numbers.
#Program 3-2
num2
print(result)
Output:
30
Python If
Python try-except
Here, we are going to discuss all the statements in Python briefly along with simple
examples and their outputs.
Example:
print("Hello, Python!")
Run Code
Output:
Hello, Python!
Python Multi-Line Statements
In Python, we use multi-line statements when a single logical line of code is too long.
Python allows us to break long code lines using backslashes (\) or by wrapping them
in brackets (), [], or {}.
Example:
# Multi-line addition using backslash
total = 10 + 20 + \
30 + 40
print("Total:", total)
Run Code
Output:
Total: 100
2. Using Parentheses - Implicit line continuation
We use the implicit line continuation to split a long statement using brackets [],
parentheses (), and braces {}.
Example:
# Multi-line addition using parentheses
total = (10 + 20 +
30 + 40)
print("Total:", total)
Run Code
Output:
Total: 100
Python Conditional and Loop Statements
1. Python If Statement
if is a conditional statement in Python used to decide whether a given code or block
of code will be executed or not. It is the simplest decision-making statement in
Python and executes a code only when a certain condition is true.
Syntax:
if condition:
# code to run if condition is true
Flowchart of an if Statement
Example:
x = 10
if x > 5:
print("x is greater than 5")
Run Code
Output:
x is greater than 5
2. Python if-else Statement
The if statement in Python executes a block of code only if the given condition is
true. If the condition is false, it doesn’t execute the code.
If the given condition in the if statement is evaluated to be true, it will execute the
statement and skip the else condition. However, when the if statement is evaluated
as false, it will execute the else condition and skip the if statement.
Syntax:
if condition:
# code to run if condition is true
else:
# code to run if condition is false
Flowchart of If-else Statement
Example:
age = 18
if age >= 18:
print("You can vote")
else:
print("You cannot vote")
Run Code
Output:
You can vote
3. Python if-elif-else Statement
The if-elif-else statement lets us check multiple conditions one by one. When one
condition is true, its block runs, and the rest are skipped. This avoids writing multiple
separate if statements.
We use the elif statement in Python when we need to test more than two possibilities
in a decision-making process.
Syntax:
if condition1:
# code if condition1 is true
elif condition2:
# code if condition2 is true
else:
# code if none of the above conditions are true
Flowchart of elif Statement in Python
Example:
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 70:
print("Grade B")
else:
print("Grade C")
Run Code
Output:
Grade B
4. Python Nested If Statement
A nested if statement means using one if statement inside another. It helps us check
multiple conditions in steps, where a new condition is only checked if the first one is
true.
We use the nested if statement in Python when one decision depends on another
condition being true.
Syntax:
if condition1:
if condition2:
# code runs if both condition1 and condition2 are true
Flowchart of Python Nested if Statement
Example:
bug_count = 5
tests_passed = True
if bug_count == 0:
if tests_passed:
print("Ready for deployment")
else:
print("Fix test issues before deployment")
else:
if bug_count < 10:
print("Minor bugs – fix before release")
else:
print("Too many bugs – not ready for release")
Run Code
Output:
Minor bugs – fix before release
5. Python for loop
The for loop in Python is a special loop statement used for sequential traversal. We
use this loop to iterate over an iterable, such as a tuple, set, string, dictionary, or list.
The for loop statement in Python supports collection-based iteration, allowing us to
access each item one by one.
Syntax:
for variable in iterable:
# code to run for each item
Flowchart of Python For Loop
Example:
for i in range(1, 6):
print(i)
Run Code
Output:
1
2
3
4
5
Iterating Over Different Data Types Using a for Loop in Python
In Python, we use the for loop to iterate over various iterable types like lists, tuples,
sets, strings, and dictionaries.
Output:
apple
banana
cherry
2. Iterating over a Tuple
Example:
numbers = (1, 2, 3)
for number in numbers:
print(number)
Run Code
Output:
1
2
3
3. Iterating over a Set
Example:
red
green
blue
4. Iterating over a String
Example:
word = "hello"
for letter in word:
print(letter)
Run Code
Output:
h
e
l
l
o
5. Iterating over a Dictionary
Example:
Output:
name : Alex
age : 30
city : New York
6. Python while loop
The while statement in Python executes a block of code or statement repeatedly until
a certain condition is met. If the condition is evaluated as false, the program will
execute the line immediately after the loop.
Syntax:
while condition:
# code to run
Flowchart of Python While Loop
Example:
count = 1
while count <= 3:
print("Count is:", count)
count += 1
Run Code
Output:
Count is: 1
Count is: 2
Count is: 3
7. Python try-except
We use the try-except statement in Python to manage errors within the code. The try
block checks the code for any errors and executes the program if there are no errors
in the code given inside the try block. However, if the program finds an error in the
try block, it executes the code inside the except block.
Syntax:
try:
# code that may raise an error
except:
# code to handle the error
Example:
num = int("abc")
print("Conversion successful")
Run Code
try:
num = int("abc")
print("Conversion successful")
except:
print("An error occurred")
Output:
An error occurred
8. Python with Statement
The with statement in Python is used when we work with files or other resources. It
automatically handles opening and closing, so we don’t need to close them
manually. This helps us write cleaner and safer code.
Example:
with open("sample.txt", "w") as file:
file.write("Welcome to Python!")
Run Code
Output:
(Contents written to example.txt)
Note: This code writes "Hello, Python!" into a file named example.txt. No need to
manually close the file — with does it for us.
Basically, we use the return statement to invoke a function and execute the pass
statements. We can’t use the return statement outside the function.
Syntax:
def function_name():
return value
Example:
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Run Code
Output:
8
2. Python pass Statement
Sometimes, users don’t want to write code or don’t know what code to write. In such
cases, they can use a pass statement in Python. They can place a pass in the line
where empty code is not allowed, such as function definitions, loops, class
definitions, and if statements. Pass is a null statement and helps users avoid any
error when using an empty code.
Syntax:
pass
Example:
def future_function():
pass # we'll add code later
for i in range(3):
pass # loop does nothing for now
Run Code
The program does not show any output, and the code runs without error.
Syntax:
for/while item in iterable:
if condition:
break
Example:
for i in range(5):
if i == 3:
break
print(i)
Run Code
Output:
0
1
2
4. Python continue Statement
Like the break statement, continue is also a loop control Python statement. However,
the continue statement is the opposite of the break statement. It doesn’t terminate
the loop but forces the loop to execute the next iteration of that loop.
As we execute the continue statement in Python, it skips the code written inside the
loop following the continue statement and starts the next iteration of the loop.
Syntax:
for/while item in iterable:
if condition:
continue
# remaining code
Example:
for i in range(5):
if i == 2:
continue
print(i)
Run Code
Output:
0
1
3
4
Indentation in Python
Whitespace is used for indentation in Python. Unlike many other
programming languages which only serve to make the code easier to
read, Python indentation is mandatory. One can understand it better by
looking at an example of indentation in Python.
Role of Indentation in Python
A block is a combination of all these statements. Block can be regarded
as the grouping of statements for a specific purpose. Most programming
languages like C, C++, and Java use braces { } to define a block of code
for indentation. One of the distinctive roles of Python is its use of
indentation to highlight the blocks of code. All statements with the same
distance to the right belong to the same block of code. If a block has to be
more deeply nested, it is simply indented further to the right.
Example 1:
The lines print('Logging on to 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.
# Python indentation
site = 'gfg'
if site == 'gfg':
print('Logging on to geeksforgeeks...')
else:
print('retype the URL.')
print('All set !')
Output
Logging on to geeksforgeeks...
All set !