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

Python Notes

Uploaded by

MANJUNATH K B
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)
8 views17 pages

Python Notes

Uploaded by

MANJUNATH K B
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
You are on page 1/ 17

Features and Applications of Python

➢ Top Features of Python

1. For learning it is easy and to use: Python is easy to learn and use, even
for beginners. The syntax is plain and straightforward, almost like writing in
English.
2. Object-oriented: Python is an object-oriented programming language that
has highlights such as code reusability and measured quality. It supports
highlights such as abstraction, encapsulation, inheritance and
polymorphism.

3. Interpreted: Python is an interpreted language, which implies line by


line the code is executed. This makes the process faster and more efficient
as it eliminates the need for a compilation step, and if some error occurs, it
will not wait for the whole code to compile. It will throw an error at that
particular line itself.

4. Cross-platform: Python has the capability to run on multiple platforms,


including Windows, Mac, Linux, and Unix. This makes it highly portable,
allowing developers to write code on one platform and run it on another.
5. Extensive standard library: Python has an extensive standard library that
contains modules for many everyday tasks, e.g. file input/output, regular
expressions and networks. This reduces the code developers have to write
and saves time and effort.

6. Dynamically typed: Python is dynamically typed, meaning variable


types are determined at runtime. We don't have to tell the data type of the
variable explicitly. This makes the language more flexible and adaptable to
changing requirements.
7. High-level language: Python may be a high-level language, meaning that it
abstracts absent numerous of the low-level points of interest of computer
hardware. This permits designers to focus on the problem they are
attempting to unravel, instead of the usage points of interest.
8. Support for numerous programming ideal models: Python supports
numerous programming standards, counting procedural, functional and
object-oriented programming. This makes it exceedingly versatile to
distinctive coding styles and extend necessities.
9. Free and open source: The Python programming language is free and open
source, which suggests it can be utilized on any working framework for

1
complimentary. You'll be able download Python and the related libraries
and documentation from the official Python site. In expansion to
downloading, you'll too make and convey your possess modules or
libraries.

10. Extensive feature: The Python programming language can be extended


and is more versatile than many other programming languages. Its
adaptability to various functionalities makes Python a universal
programming language in the software development industry. Code written
in different programming languages can be executed. Python gains new
capabilities and functionality by integrating code from other programming
languages.
11.Database support: Python provides robust support for working with
databases through its standard library and third-party packages such as
SQLite3, MySQL Connector, PostgreSQL, SQLAlchemy, and MongoDB.
Python also supports Object-Relational Mapping (ORM) frameworks such
as Django ORM and SQLAlchemy, which provide an abstraction layer on top
of databases, making it easier to work with data in object-oriented Python
code.

12. GUI Programming Support: Python provides several GUI programming


frameworks and libraries, including Tkinter, PyQt, and wxPython where.
Tkinter is a standard GUI toolkit included in Python. PyQt delivers a powerful
and flexible toolkit for creating cross-platform desktop GUI applications,
and wxPython provides a native look and feels for desktop GUI applications
on Windows, macOS, and Linux.
Python's simplicity, versatility, and readability make it popular for developers
across many industries and applications. Now let's see some applications of
Python.
Applications of Python
Python is a compelling, easy-to-use and versatile language. There is a large
community of excellent developers, and the language has a simple, English-
language syntax. Python is a versatile programming language that allows you to
create applications in many areas.

2
Python is a versatile programming language that can be used for various
applications. Some typical applications of Python include:

1. Web development: Django, Flask, and Pyramid are popular web


frameworks in Python, used for building applications ranging from small
websites to large enterprise applications.

2. Data science and analytics: Python is a highly demanded language in


data science and machine learning, with popular libraries like NumPy,
Pandas, Matplotlib, and Scikit-learn for data analysis, visualization, and
ML.

3. Scientific computing: Python is widely used in scientific computing,


with modules for numerical calculations, optimization, linear algebra,
interpolation, and special functions. Libraries like SciPy and NumPy provide
a powerful way to perform scientific computations.
4. Automation and scripting: Python is extensively used for automation
tasks, such as scripting, testing, and deployment, providing an efficient way
to automate repetitive tasks and integrate systems and services.

3
5. Desktop GUI applications: Python provides several GUI toolkits like
Tkinter, PyQt, and wxPython, allowing developers to create desktop
applications with a native look and feel.

6. Game development: Python can be used to develop games with


libraries like Pygame, which provides graphics, sound, and input handling
tools for game development.

7. Networking: Python has robust networking libraries, such as sockets


and Requests, which make it easy to create network-based applications,
such as web scrapers and web crawlers.

8. Education: Python's simplicity and ease of use make it a popular choice


for introductory programming courses in academia and online.

9. DevOps: Python is used extensively in the DevOps community for tasks


such as automation, infrastructure management, and deployment. Tools
such as Ansible and SaltStack are written in Python.

10.Finance: Python is widely used for quantitative analysis, algorithmic


trading, and risk management. Banks such as JPMorgan and Goldman
Sachs use Python for financial modeling and analysis.

11.Healthcare: Python is used for medical imaging, data analysis, and


research. The National Institutes of Health (NIH) uses Python for genomic
data analysis.
These are just a few of the many applications of Python, and its versatility and wide
range of libraries and frameworks make it a popular choice for many developers
and organizations.
Conclusion
Python is easy to learn and use, object-oriented, interpreted, cross-platform, has
an extensive standard library, is dynamically typed, supports multiple
programming paradigms, is free and open source, and supports databases and
GUI programming. Python has a number of applications, including web
development, data science and analytics, scientific computing, machine
learning, artificial intelligence, game development, and more. Python's popularity,
powerful libraries, and active community of developers make it a go-to choice for
many programming tasks.
Key Takeaways

4
• Python is an interpreted high-level programming dialect known for its
straightforwardness, flexibility and meaningfulness.
• It is simple to learn and utilize, object-oriented, interpreted, cross-platform,
has an broad standard library, is powerfully written, and supports numerous
programming standards.
• Python is free and open source and bolsters databases and GUI
programming.
• It incorporates a wide extend of applications, counting web advancement,
information science and analytics, logical computing, computerization and
scripting, and manufactured insights and machine learning.
• Its adaptability to distinctive functionalities makes it an greatly flexible
programming dialect within the program improvement industry.
QUIZ
1. Which of the following is NOT a feature of Python?
a. Cross-platform
b. Object-oriented
c. Compiled
d. Dynamically typed
Answer: c. Compiled
2. What is the advantage of Python's dynamically typed nature?
a. It makes the language more rigid
b. It allows for more excellent type safety
c. It makes the language more flexible and adaptable to changing
requirements
d. It makes the language faster
Answer: c. It makes the language more flexible and adaptable to changing
requirements
3. What is the advantage of Python's extensive standard library?
a. It makes the language faster
b. It reduces the amount of code developers need to write, saving time
and effort

5
c. It makes the language more rigid
d. It allows for more excellent type safety
Answer: b. It reduces the amount of code developers need to write, saving time
and effort
4. What are some common applications of Python?
a. Web development, data science and analytics, scientific computing,
and automation and scripting
b. Web development, machine learning, scientific computing, and
database management.
c. Web development, data science and analytics, machine learning,
and database management
d. Web development, data analysis, scientific computing, and artificial
intelligence
Answer: a. Web development, data science and analytics, scientific computing,
and automation and scripting
2.1 Identifiers
An identifier is a name given to a variable, function, class, or module. Identifiers may
consist of one or more characters and follow these rules:
❖ Identifiers can be a combination of lowercase letters (a–z), uppercase letters (A–Z), digits
(0–9), and underscores (_).
❖ Examples of valid identifiers: myCountry, other_1, good_morning.
❖ A Python identifier must begin with a letter (A–Z, a–z) or an underscore (_).
❖ An identifier cannot start with a digit but can have digits elsewhere.
(Example: 1plus is invalid, but plus1 is valid)
❖ Keywords cannot be used as identifiers.
❖ One cannot use spaces and special symbols like !, @, #, $, % etc. as identifiers.
❖ Identifier can be of any length.

2.2 Keywords
Keywords are a list of reserved words that have predefined meaning. Keywords are
special vocabulary and cannot be used by programmers as identifiers for variables,
functions, constants or with any identifier name. Attempting to use a keyword as an
identifier name will cause an error. The following TABLE 2.1 shows the Python keywords.

6
7
Introduction to Features and Applications of Python; Python Versions; Installation of Python;
Python Command Line mode and Python IDEs; Simple Python Program.
Python Basics: Identifiers; Keywords; Statements and Expressions; Variables; Operators;
Precedence and Association; Data Types; Indentation; Comments; Built-in Functions-
Console Input and Console Output, Type Conversions; Python Libraries; Importing Libraries
with Examples.
Python Control Flow: Types of Control Flow; Control Flow Statements- if, else, elif, while loop,
break, continue statements, for loop Statement; range () and exit () functions.

Introduction to Features and Applications of Python


Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and
readability. It was created by Guido van Rossum and released in 1991. Python follows
an object-oriented, procedural, and functional programming approach, making it
versatile for different applications.
Key Features of Python
1. Easy to Learn and Use – Python has a simple syntax that is easy to read and
write.
2. Interpreted Language – Python code is executed line-by-line, making debugging
easier.
3. Dynamically Typed – No need to declare variable types; Python assigns types at
runtime.
4. Platform Independent – Runs on multiple platforms like Windows, Linux, and
macOS.
5. Extensive Libraries – Rich standard libraries like NumPy, Pandas, Matplotlib,
etc.
6. Open-source and Free – Python is freely available and open for modification.
7. Supports Multiple Programming Paradigms – Procedural, Object-Oriented,
and Functional.
8. Large Community Support – A vast community of developers contributing to
Python's growth.
Applications of Python
1. Web Development – Frameworks like Django and Flask.
2. Data Science & Machine Learning – Libraries like NumPy, Pandas, TensorFlow,
and Scikit-learn.
3. Automation & Scripting – Used for writing automation scripts.
4. Game Development – Used in game engines like Pygame.
5. Cybersecurity – Employed in ethical hacking and penetration testing.
6. Embedded Systems – Used in IoT applications.
7. Desktop GUI Applications – Tkinter, PyQt for GUI development.

8
8. Finance & Banking – Used for risk analysis, stock market predictions, and fraud
detection.
9. Networking – Supports socket programming and network automation.
10. Cloud Computing & DevOps – Automation using Ansible, Terraform, and AWS
SDKs.

Python Versions
Python has gone through several versions, with major improvements in each.
Key Python Versions:
1. Python 1.x – Initial version (1991), mainly used for scripting.
2. Python 2.x – Introduced Unicode support, print statement, and more libraries.
o Python 2.7 was the last version before discontinuation in 2020.
3. Python 3.x – Modern Python version with improved syntax and features.
o Introduced print() as a function, f-strings, better integer division, type
hints, and async/await.
o Latest version: Python 3.12 (as of 2024).
Differences between Python 2 and Python 3
Feature Python 2 Python 3
Print print "Hello" print("Hello")
Integer Division 5/2 = 2 5/2 = 2.5
Unicode Support Strings are ASCII by default Strings are Unicode by default
Iterating over Dictionaries .iteritems() .items()
xrange() Available Removed, use range() instead
End of Life Discontinued (2020) Actively maintained

Installation of Python
Python can be installed on different operating systems like Windows, macOS, and
Linux.
Steps to Install Python
1. Download Python Installer:
o Visit the official Python website: https://www.python.org/downloads/
o Choose the latest Python 3 version.
2. Install on Windows:
o Run the downloaded .exe file.
o Check the "Add Python to PATH" option before installation.
o Click on Install Now and follow the setup instructions.
o Verify installation by running:
o python --version
3. Install on macOS:
o macOS has Python pre-installed, but it is outdated.

9
o Install the latest version using:
o brew install python
o Verify installation:
o python3 --version
4. Install on Linux:
o Use package managers like apt (for Debian-based systems) or yum (for
RedHat-based systems):
o sudo apt update
o sudo apt install python3
o Verify installation:
o python3 --version

Python Command Line Mode and Python IDEs


Python Command Line Mode
• The Python Interpreter (REPL - Read Eval Print Loop) allows executing Python
code line by line.
• Open the Python shell by typing:
• python
or
python3
(depending on installation)
• Example:
• >>> print("Hello, World!")
• Hello, World!
• >>> 2 + 3
• 5
• Exit REPL mode using:
• exit()
Python IDEs (Integrated Development Environments)
IDEs provide an interactive environment for writing, debugging, and running Python
code.
Popular Python IDEs and Code Editors
1. IDLE (Python’s Default IDE) – Comes with Python installation.
2. PyCharm – A powerful IDE with debugging and code analysis.
3. VS Code – Lightweight and supports extensions.
4. Jupyter Notebook – Popular for Data Science and AI.
5. Spyder – Best for scientific computing.
6. Eclipse + PyDev – Eclipse plugin for Python.
7. Thonny – Beginner-friendly IDE.

10
Simple Python Program
Here’s a simple Python program to print "Hello, World!" and perform basic arithmetic.
# Printing a message
print("Hello, World!")

# Performing arithmetic
a = 10
b=5
sum_value = a + b
print("The sum is:", sum_value)
Explanation
1. print("Hello, World!") → Prints text on the screen.
2. a = 10, b = 5 → Assigns values to variables.
3. sum_value = a + b → Adds two numbers.
4. print("The sum is:", sum_value) → Prints the result.
Output:
Hello, World!
The sum is: 15

Python Basics
1. Identifiers
Identifiers are names given to variables, functions, classes, and objects in Python.
Rules for Identifiers:
• Can contain letters (A-Z, a-z), digits (0-9), and underscores (_).
• Cannot start with a digit.
myVar is valid, 1stVar is invalid.
• Case-sensitive (name and Name are different).
• Cannot use keywords as identifiers (e.g., if = 10 is invalid).
• Can contain underscores (first_name, _hiddenVar).
• Naming should be meaningful ( total_score, x1).
Examples:
name = "John" # Valid
_age = 25 # Valid
1stName = "Alice" # Invalid (cannot start with digit)
if = 5 # Invalid (cannot use keyword)

2. Keywords
Python keywords are reserved words that cannot be used as identifiers.
List of Python Keywords:
import keyword
print(keyword.kwlist)

11
Sample output:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield']
Example Usage:
if True:
print("Hello") # "if" is a keyword

3. Statements and Expressions


Statements
• A statement is an instruction that Python executes.
• Examples: Assignment, Conditional, Looping statements.
a = 5 # Assignment statement
if a > 3: # Conditional statement
print("a is greater than 3")
Expressions
• Expressions produce a value when evaluated.
• Example:
x = 10 + 5 * 2 # 10 + (5*2) → 20
print(x)
• Here, 10 + 5 * 2 is an expression, and x = is an assignment statement.

4. Variables
A variable is a container for storing data in memory.
Declaring Variables:
name = "Alice"
age = 25
price = 99.99
Dynamic Typing:
Python automatically detects the type of a variable.
x = 10 # Integer
x = "Hello" # Now it's a string

5. Operators
Operators perform operations on values and variables.
Types of Operators:
1. Arithmetic Operators: +, -, *, /, //, %, **
2. x = 10 + 3 # Addition
3. y = 10 % 3 # Modulus (remainder)
4. z = 2 ** 3 # Exponentiation (2^3 = 8)

12
5. Comparison Operators: ==, !=, >, <, >=, <=
6. print(10 > 5) # True
7. Logical Operators: and, or, not
8. print(True and False) # False
9. Assignment Operators: =, +=, -=, *=, /=
10. x = 10
11. x += 5 # x = x + 5 → 15
12. Bitwise Operators: &, |, ^, ~, <<, >>
13. print(5 & 3) # 1 (Bitwise AND)
14. Membership Operators: in, not in
15. print("a" in "apple") # True
16. Identity Operators: is, is not
17. print(10 is 10) # True

6. Precedence and Association


Precedence determines which operation is performed first.
Associativity defines the direction of execution.
Operator Precedence Table
Operator Description Associativity
** Exponentiation Right to Left
* / // % Multiplication, Division Left to Right
+- Addition, Subtraction Left to Right
== != > < Comparisons Left to Right
not Logical NOT Right to Left
and Logical AND Left to Right
or Logical OR Left to Right
Example:
print(3 + 5 * 2) # 3 + (5*2) = 13
print(2 ** 3 ** 2) # 2 ** (3 ** 2) = 512

7. Data Types
Python provides different data types:
Data Type Example
int x = 10
float y = 3.14
str name = "Alice"
list numbers = [1, 2, 3]
tuple colors = ("red", "blue")

13
Data Type Example
dict person = {"name": "John"}
set fruits = {"apple", "banana"}
bool is_valid = True

8. Indentation
Python uses indentation (spaces/tabs) to define code blocks instead of {}.
Example:
if 10 > 5:
print("Indentation is required!") # Correct
# No indentation → SyntaxError

9. Comments
Comments help explain the code.
Types of Comments
1. Single-line Comment:
2. # This is a comment
3. print("Hello") # Comment at end
4. Multi-line Comment:
5. """
6. This is a
7. multi-line comment
8. """

10. Built-in Functions


Python has many built-in functions.
Console Input & Output
• input() – Takes input from the user.
• name = input("Enter your name: ")
• print("Hello", name)
• print() – Displays output.
• print("Welcome to Python!")
• Formatted Output:
• age = 25
• print(f"I am {age} years old.") # f-string
Type Conversions
x = int("10") # Converts string to int
y = float("3.14") # Converts string to float
z = str(100) # Converts int to string

14
11. Python Libraries
Python has many useful libraries.
Popular Python Libraries:
Library Purpose
math Mathematical functions
random Generate random numbers
datetime Work with dates & time
Os Interact with the OS
Sys System-specific functions
Json JSON data handling
pandas Data analysis
numpy Numerical computations

12. Importing Libraries with Examples


import math
print(math.sqrt(16)) # 4.0

import random
print(random.randint(1, 10)) # Random number between 1 and 10

Conclusion
This guide covers Python Basics, including variables, operators, statements, data
types, functions, and libraries.

Type Conversions in Python


Type conversion refers to the process of converting one data type to another. Python
provides two types of type conversions:
1. Implicit Type Conversion: Python automatically converts one data type into
another without any user intervention.
o Example:
o a = 5 # Integer
o b = 2.5 # Float
o c = a + b # Implicit conversion to float
o print(c, type(c)) # Output: 7.5 <class 'float'>
2. Explicit Type Conversion (Type Casting): The user manually converts a data
type into another using built-in functions like int(), float(), str(), list(), etc.
o Example:
o x = "10"
o y = int(x) # Explicit conversion from string to integer
o print(y, type(y)) # Output: 10 <class 'int'>

15
Python Libraries
Python libraries are collections of modules that provide pre-written code for performing
various tasks.
• Standard Libraries: Built-in modules available in Python (e.g., math, datetime,
os, sys)
• Third-Party Libraries: External libraries installed using pip (e.g., numpy, pandas,
matplotlib)

Importing Libraries with Examples


To use libraries in Python, we need to import them using the import keyword.
• Importing a module:
• import math
• print(math.sqrt(25)) # Output: 5.0
• Importing specific functions:
• from math import sqrt
• print(sqrt(36)) # Output: 6.0
• Importing with an alias:
• import numpy as np
• arr = np.array([1, 2, 3])
• print(arr)

Python Control Flow


Control flow determines the execution path of a program based on conditions and
loops.
Types of Control Flow
1. Conditional Statements (if, else, elif)
2. Loops (for, while)
3. Jump Statements (break, continue, exit)

Control Flow Statements


1. if, else, elif Statements
Used for decision-making.
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
2. while Loop
Repeats a block of code while a condition is true.
i=1
while i <= 5:
print(i)
i += 1 # Increment
3. break and continue Statements
• break: Terminates the loop.

16
• continue: Skips the current iteration and moves to the next.
for num in range(1, 6):
if num == 3:
break # Stops at 3
print(num)

for num in range(1, 6):


if num == 3:
continue # Skips 3
print(num)
4. for Loop
Iterates over a sequence.
for i in range(5):
print(i)

range() and exit() Functions


• range(start, stop, step): Generates a sequence of numbers.
• for i in range(1, 10, 2):
• print(i) # Output: 1, 3, 5, 7, 9
• exit(): Stops program execution.
• import sys
• sys.exit("Terminating the program")

This concludes the detailed notes on Type Conversions, Python Libraries, Importing
Libraries, and Control Flow in Python.

# Get temperature input from user


temperature = float(input("Enter the temperature in Celsius: "))
# Check the temperature range
if temperature < 0:
print("It's freezing cold!")
elif 0 <= temperature <= 15:
print("It's cold.")
elif 16 <= temperature <= 25:
print("The weather is pleasant.")
elif 26 <= temperature <= 35:
print("It's warm.")
else:
print("It's very hot!")

17

You might also like