0% found this document useful (0 votes)
3 views17 pages

Notes

The document provides a comprehensive introduction to Python programming, detailing its history, features, limitations, and major applications. It covers essential concepts such as variables, identifiers, and different types of statements, including conditional and loop statements. Additionally, it includes instructions for installation and running Python programs, along with examples to illustrate key points.
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)
3 views17 pages

Notes

The document provides a comprehensive introduction to Python programming, detailing its history, features, limitations, and major applications. It covers essential concepts such as variables, identifiers, and different types of statements, including conditional and loop statements. Additionally, it includes instructions for installation and running Python programs, along with examples to illustrate key points.
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
You are on page 1/ 17

Introduction to Python Programming

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.

2. History and Origin of Python Language

 Created by: Guido van Rossum


 Year: 1989 (Released in 1991)
 Developed at: Centrum Wiskunde & Informatica (CWI), Netherlands
 Purpose: To create a successor to the ABC language with a focus on readability and
productivity.
 Name: Named after the British comedy series "Monty Python's Flying Circus."
 Maintained by: Python Software Foundation (PSF)

3. Features of Python

 Easy to Learn and Use: Simple syntax resembling English.


 Interpreted Language: Code is executed line by line.
 High-Level Language: Easy to understand and write.
 Cross-Platform: Runs on various operating systems.
 Open Source: Freely available to everyone.
 Extensive Standard Libraries: Comes with numerous modules and packages.
 Supports Multiple Paradigms: Object-Oriented, Procedural, Functional Programming.
 Dynamic Typing: No need to declare variable types.
 Automatic Memory Management: Built-in garbage collection.

4. Limitations of Python

 Slower than compiled languages (e.g., C, C++).


 High Memory Usage.
 Limited in mobile and game development.
 Runtime Errors due to dynamic typing.
 Global Interpreter Lock (GIL) restricts multi-threading.

Performance and Speed ? Python is an interpreted language executed at runtime by a virtual


machine or interpreter. This can make it slower and less efficient than compiled languages like C or
C++. Python is also not well-suited for applications that require a high level of performance, such as
video games or scientific simulations.

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.

5. Major Applications of Python

 Web Development: Django, Flask


 Data Science & Machine Learning: NumPy, Pandas, TensorFlow
 Automation/Scripting: Task automation, scripting
 Game Development: Pygame
 Desktop Applications: Tkinter, PyQt
 Networking: Network scripting, sockets
 IoT & Embedded Systems: MicroPython, Raspberry Pi
 Cybersecurity: Security tools and ethical hacking

6. Getting & Installing Python

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.

7. Setting up Path and Environment Variables

 Automatically set if "Add Python to PATH" is checked.


 To manually set PATH:
o Add Python install directory to system PATH.
o Example: C:\\Python312\\ and C:\\Python312\\Scripts\\
 Verify 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:

1. Open a text editor and write the code.


2. Save the file as hello.py.
3. Run it using the command:

python hello.py
10. Python Interactive Help Feature

 Use help() function in Python interpreter to access help.


 Example:

help()
help(print)
11. Python Differences from Other Languages
Feature Python Other Languages

Syntax Simple, readable Often complex (e.g., C, Java)

Typing Dynamically typed Statically typed (e.g., C, Java)

Compilation Interpreted Compiled (e.g., C, C++)

Speed Slower Faster in compiled languages

Libraries Extensive Limited in some languages

Memory Management Automatic (Garbage Collection) Manual (e.g., C, C++)

Community Support Very large and active Varies

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

False class finally is


None continue for lambda
True def from nonlocal
and del global not
as elif if or
False class finally is
assert else import pass
break except in raise

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:

 The name should begin with an uppercase or a lowercase alphabet or an


underscore sign (). This may be followed by any combination of
characters , 0-9 or underscore (). Thus, an identifier cannot start with a
digit.
 It can be of any length. (However, it is preferred to keep it short and
meaningful).
 It should not be a keyword or reserved word given in Table 3.1.
 We cannot use special symbols like !, @, #, $, \%, etc. in identifiers.

For example, to find the average of marks obtained by a student in three


subjects namely Maths, English, Informatics Practices (IP), we can choose
the identifiers as marksMaths, marksEnglish, marksIP and avg rather than
a, b, c, or A, B, C, as such alphabets do not give any clue about the data
that variable refers to.

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.

gender ‘M’ message “Keep Smiling” price

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

#To find the sum of two given numbers


num1

num2

result num1 + num2

print(result)

#print function in python displays the output

Output:

30

Types of Statements in Python


Now, let’s understand every Python statement in detail with the help of a few
examples:

1. Python Simple Statements

2. Python Multi-Line Statements

3. Python Conditional and Loop Statements

 Python If

 Python if-else Statement

 Python if-elif-else Statement

 Python Nested If Statement

 Python for loop

 Python while loop

 Python try-except

 Python with statement

4. Python Expression statements

 Python return statement

 Python pass statement

 Python break statement


 Python continue statement

 Python del statement

 Python import statement

Here, we are going to discuss all the statements in Python briefly along with simple
examples and their outputs.

Python Simple Statements


Simple statements in Python are the smallest unit of execution that do not contain
any logical or conditional expressions. They are simple standalone statements that
include a single line of code and perform a basic action, such as calling functions,
assigning values to variables, and printing out values.

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

1. Using Backslash (\) - Explicit line continuation


We use a backslash to split one logical statement into multiple lines manually.

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.

1. Iterating over a List


Example:

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)
Run Code

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:

colors = {"red", "green", "blue"}


for color in colors:
print(color)
Run Code

Output (order may vary):

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:

person = {"name": "Alex", "age": 30, "city": "New York"}


for key, value in person.items():
print(key, ":", value)
Run Code

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

This code will raise an error. Let’s fix it using try-except:

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.

Python Expression Statements


In Python, expression statements are lines of code that evaluate and return a value.
They can assign values to variables, call functions, or perform calculations to
produce results during execution.

1. Python return Statement


The return statement in Python is used to stop the execution of a function call and
return the output to the caller. The program doesn’t execute the statement after the
return statement. However, if the return statement doesn’t have any expression, it
returns None.

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.

3. Python break Statement


The break statement in Python terminates the loop in which it is placed. After
breaking, control passes to the first statement following the loop. If used inside a
nested loop, it only breaks the innermost loop where the break occurs.

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 !

You might also like