PYTHON NOTES
PYTHON NOTES
INTRODUCTION TO PYTHON
UNIT-I
#SOFTWARE:
- Software is a set of instructions, data, or programs used to operate computers and execute
specific tasks.
- Software is a collection of programs and data that tell a computer how to perform specific
tasks.
#PROGRAM:
- A Program is a specific set of instructions designed to perform a particular task.
#CODE:
- The set of instructions or a system of rules, written in a particular programming language (i.e
the source code).
#CODING:
- Coding is a list of step-by-step instructions that get computers to do what you want them to
do.
- Coding makes it possible for us to create computer software, games, apps, and websites.
- Coders or programmers behind everything we see and do on a computer.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
#PROGRAMMING:
- The language used to communicate with a computer to perform a specific task is known as
“Programming Language”.
- Programming language is a medium to interact with a system.
- Programming can be done using a variety of Computer programming languages such as C,
C++, java, python, etc..
1. Low-Level Language
2. Middle-Level Language
3. High-Level Language
1. Low-Level Language:
- Low level is also known as “Machine Level Language”.
- A language which is understandable, and readable by a machine.
- Machine understands only binary language i.e. 0’s and 1’s.
- Which is easy for a computer to understand but not for humans.
Example: 100100111 [Binary Language]
2. Middle-Level Language:
- The language that is understandable by the microprocessor is known as
“Middle-Level Language”.
- Middle-Level Language is also known as “Assembly Level Language”.
Example: Add A, B [Assembly Language]
3. High-Level Language:
- Human understandable language (or) Human readable form, it is a normal English
form known as “High-Level Language”.
- The language which is easy to read, write, and understand the instructions is known
as “High-Level Language”
- The high-level language is understandable by the machine with the help of a software
called compiler.
Example: C = A + B
PYTHON PROGRAMMING NOTES @abdulbasidshaik
INTERPRETER:
1. A language translator that converts a high-level language program into a machine language
program, one line at a time, is referred to as an interpreter. Interpreters convert the codes
slower than the compiler. This is because the interpreter can scan and translate only one
statement of the program at a time. Therefore, interpreters convert the source code into
machine code during the execution of the program.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
2. As it scans the code in one go, the Considering it scans code one line at a
errors (if any) are shown at the end time, errors are shown line by line.
together.
4. It converts the source code into It does not convert source code into object
object code. code instead it scans it line by line
PYTHON PROGRAMMING NOTES @abdulbasidshaik
5. It does not require source code for It requires source code for later execution.
later execution.
INTRODUCTION TO PYTHON
Fact: Python is named after the comedy television show “Monty Python's Flying Circus”
and not after Python Snake.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
Python History
● 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.
● Python is copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL).
● 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.
● In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt. sources.
● In 1994, Python 1.0 was released with new features like lambda, map, filter, and
reduce.
● Python 2.0 added new features such as list comprehensions, and garbage collection
systems.
● On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify the fundamental flaw of the language.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
👌🏻
Python provides lots of features that are listed below.
1. Easy to Learn and Use
PYTHON PROGRAMMING NOTES @abdulbasidshaik
2. Interpreted Language 💻
3. Cross-platform Language 🌎
4. Free and Open Source 🆓
🔐
🎨
5. Object-Oriented Language
6. GUI Programming Support
⏫
🔥
7. Integrated
8. Dynamic Memory Allocation
The object-oriented procedure helps programmers to write reusable code and develop
applications in less code.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
#Python Applications:
Python is a general-purpose programming language that makes it applicable in almost all domains of
software development. Python as a whole can be used to develop any type of application.
Here, we are providing some specific application areas where Python can be applied.
● Web Applications
● Desktop GUI Applications
● Software Development
● Scientific and Numeric
● Business Applications
● Console-Based Applications
● Audio or Video-based Applications
● 3D CAD Applications
● Enterprise Applications
● Image processing Applications
PYTHON PROGRAMMING NOTES @abdulbasidshaik
We recommend Python 3, as Python 2 reached its end of life in 2020. Download Python 2
only if you work with legacy scripts and older projects. Also, choose a stable release over
the newest since the newest release may have bugs and issues.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
3. Click the link to download the file. Choose either the Windows 32-bit or 64-bit
installer.
● Add Python to PATH. The second option places the executable in the PATH
variable after installation. You can also add Python to the PATH environment
variable manually later.
3. Select the Install Now option for the recommended installation (in that case, skip the
next two steps).
To adjust the default installation options, choose Customize installation instead and
proceed to the following step.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
Customizing the installation allows changing these installation options and parameters.
4. Choose the optional installation features. Python works without these features, but
adding them improves the program's usability.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
Choose whether to install Python for all users. The option changes the install location to
C:\Program Files\Python[version]. If selecting the location manually, a common choice is
C:\Python[version] because it avoids spaces in the path, and all users can access it. Due to
administrative rights, both paths may cause issues during package installation.
Other advanced options include creating shortcuts, file associations, and adding Python to
PATH.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
After picking the appropriate options, click Install to start the installation.
6. Select whether to disable the path length limit. Choosing this option will allow
Python to bypass the 260-character MAX_PATH limit.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
The option will not affect any other system settings, and disabling it resolves potential
name-length issues. We recommend selecting the option and closing the setup.
Adding the Python path to the PATH variable alleviates the need to use the full path to
access the Python program in the command line. It instructs Windows to review all the
folders added to the PATH environment variable and to look for the python.exe program in
those folders.
1. In the Start menu, search for Environment Variables and press Enter.
4. Double-click the first empty field and paste the Python installation folder path.
Alternatively, click the New button instead and paste the path.
5. Click OK to save the changes. If the command prompt is open, restart it for the
following step.
However, for newcomers to Python, getting started with running Python programs may
seem daunting. In this guide, we’ll walk you through the process of running Python
programs, whether you’re using a text editor, an Integrated Development Environment
(IDE), or the command line. By the end of this guide, you’ll be equipped with the
PYTHON PROGRAMMING NOTES @abdulbasidshaik
knowledge and confidence to execute Python code and unleash the power of Python in
your projects.
Now let’s dive into the various methods for running Python programs.
interactive mode is a useful way to run Python programs when you want to test small
pieces of code or experiment with different functions. To run a Python program in
interactive mode, you need to follow these steps:
STEP-2: Type “python" and press Enter to enter the Python interpreter.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
You can see the >>> symbol in the cmd. This shows that you are in the interactive mode
of Python.
STEP-3: Type your Python code directly in the interpreter and press Enter to execute
each line. For example,
As you can see we get the output of the statement as soon as we press enter.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
Here by typing the exit() statement, we come out of the Python interpreter.
Using the Python command line is a simple and efficient way to run Python programs. To
run a Python program using the Python command line, you need to follow these steps:
STEP-1: First write your Python program in “Notepad” and save it with the program.py
name.
STEP-2: Open your terminal or command prompt and Navigate to the directory where
your Python file is located using the cd command.
STEP-3: Now type py welcomecode.py in the command prompt to run the python
program and press enter.
As soon as we press enter, the file gets executed and we can see the output of the program
on the screen.
Text editors are simple software applications that allow you to create and edit text files.
The most popular Text Editor is Microsoft’s Visual Studio Code. Follow these steps to
run your Python program on the VS Code.
STEP-1: Open VS Code and install the Python extension from the extensions section.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
STEP-2: Create a new file with the extension .py and save it.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
STEP-5: The output of the Python program will be visible in the Terminal present in the
VS Code.
💻 🍎 🐧
Python may be a cross-platform programming dialect, which suggests that it can run on
☕
different platforms like Windows, macOS, and Linux, and it has indeed been
ported to Java and .NET virtual machines. It is free and open-source.
IDEs make the developer's job easier by combining necessary tools during software
development. Many IDE (Integrated Development Environment) and code editors are
available as per the developer's requirement. A few famous IDEs and code editors are
PyCharm, Visual Studio Code, Jupyter Notebook, Google Colab, etc.
Google Colab is a powerful and free development environment that provides many
features for developing and running Python code. Google Colab is an excellent platform
for developing and running Python code without any installations. Google Colab also
provides advanced components like GPU and TPU support, which are useful for running
machine learning and deep learning models. You can also use Google Colab to
collaborate with others on your code in real time by directly pushing it to GitHub or
sharing it via the link now, making it an excellent platform for team projects. It's an ideal
platform for beginners and advanced enthusiasts.
📓 Colab, or "Colaboratory," allows you to write and execute Python in your browser,
with
https: //colab.research.google.com/
PYTHON PROGRAMMING NOTES @abdulbasidshaik
1. Free to Use: 💰 One of the most significant advantages of Google Colab is its
completely free use. You don't need to pay any subscription fees or download any
software. You only need a Google account to access the service without
☁️
prerequisites.
2. Cloud-Based: Google Colab is entirely cloud-based, meaning you don't need
to install anything on your computer. All the processing is done on Google's
servers, which makes it easy to use on any device and also saves your PC's
🤝
memory.
3. Easy Collaboration: Google Colab makes collaborating with others in real
time easy. You can share your notebooks with others, and they can edit or view
them in real-time. This is particularly useful if you're working on a team project or
💻🎮
want to share your work with others.
4. GPU Support: Google Colab provides GPU support, which helps work on
deep learning or other computationally intensive tasks. You can use a GPU for free
📚
for up to 12 hours at a time, after which you'll need to request another one.
5. Built-in Libraries: Google Colab comes with many built-in libraries, such as
NumPy, pandas, matplotlib, and many more, which have to import, and we can
access their functionality. Even we can build our module and import it as a library
to use it. You can also install additional libraries using pip, which makes it easy to
work with a wide range of tools.
Google Colab is an excellent tool for machine learning projects. It provides access to free
GPU and TPU resources that can significantly speed up model training. To use the GPU
or TPU, select it from the "Runtime" menu. You can also install popular machine learning
libraries such as Sklearn, TensorFlow, and PyTorch to use those in your modeling.
Note: You can only use a GPU or TPU for a limited time, up to 12 hours before it times
out.
🔎 Open Google Colab: To use Google Colab, open your web browser and go to
https://colab.research.google.com/ or type "google.colab" 🔎 in the search bar,
1.
and you will find Google Colab. You'll need to sign in with your Google account if
📓
you still need to do so.
🆕
2. Create a New Notebook: Once you're signed in, you can create a new
notebook by clicking the "New Notebook" button. It will take you to the colab
✍️
notebook.
3. Write Your Code: You can write your code in the code cells of your notebook.
It is straightforward to use and add text cells to document your code. Google Colab
▶️ ▶️
supports many programming languages, but it's primarily used for Python.
4. Run Your Code: To run your code, tap on the play button following the
code cell, utilize the alternate route "Shift+Enter" or go to runtime and select
choices from the alternatives; we have alternatives like run all, run some time
recently, run after, etc. Google Colab will execute your code and show the yield
💾
underneath the cell.
5. Spare Your Notebook: Once you've written your code, you'll be able to save
your notebook by clicking "File" and after that "Save." The code will be
auto-saved; you'll check your modification history and have version control. Your
notebook will be saved to your Google Drive account.
Python Code Execution: Python’s traditional runtime execution model: The source code
you type is translated to bytecode, which is then run by the Python Virtual Machine (PVM).
Your code is automatically compiled, but then it is interpreted.
ERRORS:
● Programming errors are called bugs, and the process of tracking them down is called
debugging.
TYPES OF ERRORS:
● Three kinds of errors can occur in a program: syntax errors, runtime errors, and
semantic errors.
1. Syntax Errors:
● Syntax errors are mistakes in the programming language's grammar rules that make
the program unable to compile. A syntax mistake might be produced for several
reasons, such as a missing semicolon, unmatched braces, or incorrect variable
declarations.
2. Semantic Errors
● Semantic errors refer to logical errors or incorrect program logic that lead to undesired
output or unexpected behavior. Although a program with semantic errors can compile
successfully, it does not function as intended.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
3. Runtime Errors:
● Runtime errors are errors that occur during the execution of a program. A program
with runtime errors can compile successfully, but unexpected events or situations may
trigger the program to crash or result in incorrect output when executed.
➔ Division by zero
➔ Null pointer dereferencing
➔ Array index out of bounds
➔ Resource leaks (e.g., memory or open file handles)
Example-program-1:
print("is awesome")
Output:
CseHackTech is awesome
Example-program-2:
PYTHON PROGRAMMING NOTES @abdulbasidshaik
Output:
CseHacker says your awesome
Example-program-3:
Output:
Hello back benchers, am your cseh4ck3r
Python comments 👏
● A comment is a text that doesn’t affect the outcome of a code; it is just a piece of
text to let someone know what you have done in a program or what is being done
in a block of code.
● This is especially helpful when someone else has written a code and you are
analyzing it for bug fixing or making a change in logic. By reading a comment,
you can understand the purpose of the code much faster than by just going through
the actual code.
2. Multi-line comment
● In Python, we use # special character to start the comment. Let’s take a few
examples to understand the usage.
2. MULTI-LINE COMMENT:
'''
This is a
multi-line
comment
'''
'''
We are writing a simple program here
First print statement.
This is a multiple-line comment.
'''
PYTHON PROGRAMMING NOTES @abdulbasidshaik
print("Hello Backbenchers")
TOKENS:
Types of tokens:
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Punctuators
6. Datatypes
Python Keywords
➢ Python keywords are special reserved words that convey a special meaning to the
compiler/interpreter.
➢ Each keyword has a special meaning and a specific operation. These keywords can't
be used as variables.
➢ The Python keywords are...
➢ We can get the list of keywords in your current version by typing the following in
the prompt.
>>> help("keywords")
(or)
>>> print(keyword.kwlist)
Identifiers:
List of components:
★ Class
★ Function
★ Variable, etc..,
PYTHON PROGRAMMING NOTES @abdulbasidshaik
Note: A programmer should follow the “rules” and “conventions” for an identifier.
Example:
➔ my_variable ✅
➔ MY_VARIABLE ✅
➔ my_Variable1 ✅
➔ 1variable ❌
Example:
➔ variable✅
➔ variable1 ✅
➔ 1variable ❌
➔ 2_variable ❌
➔ Variable ✅
3. While declaring identifiers, we should not use any special characters like !, @, #,
$, %, etc., except underscore ( _ )
Example:
➔ num ✅
➔ _abdulbasid ✅
➔ num1 ✅
➔ my!num ❌
➔ @abdulbasid137 ❌
PYTHON PROGRAMMING NOTES @abdulbasidshaik
➔ abdul_basid137 ✅
➔ Abdul_.basid137 ❌
➔ num$ ❌
➔ $my_num ❌
Example:
➔ Abdu l❌
➔ Ab dul ❌
➔ Abdul basid❌
➔ Abdul_basid ✅
➔ @bdul_basid ❌
Example:
➔ global❌
➔ else ❌
➔ Global ✅
➔ global_ ✅
Conventions:
● The coding or industrial standard to be followed by the programmer is known as a
"convention”.
Note:
● The compiler doesn't validate the convention; therefore, if conventions are not
followed then we won’t get a “compile-time-error”.
● It is highly recommended to follow the “convention”.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
Things to remember:
● Python is a case-sensitive language. This means, Variable and variable are not the
same.
● Always give the identifier a name that makes sense. While c = 10 is a valid name,
writing count = 10 would make more sense, and it would be easier to figure out what
it represents when you look at your code after a long gap.
● Multiple words can like this_is_a_long_variable.
Variables in Python
Variables are one of the most fundamental ideas of Python. Variables hold information and
provide it with a name that may be used later in the code. Using a single equals symbol (=),
they may carry a variety of data types, including strings 💬, integers 🔢, and boolean values
In this tutorial, we will go over variables in Python in depth.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
What is a variable?
Syntax:
variable_name = value
Example:
name = “abdubasid”
There are a few rules we need to follow while creating a variable in Python:
PYTHON PROGRAMMING NOTES @abdulbasidshaik
➔ Please ensure that the name only includes letters, numbers, and underscores. No other
special characters are permitted, like @, #, and &. ❌
➔ The variable name should either begin with an uppercase (A to Z) or lowercase (a to
z) character or an underscore(_). 🔡
➔ The name must not begin with a number. ❌
➔ The name should be descriptive and easy to understand. 💡
➔ The name is case-sensitive, meaning "age" and "Age" are two different variables.
🔤
➔ Avoid using Python-reserved words as variable names. ⚠️
➔ White spaces are not used as variable names.
Some valid variable names are:
harry
harry_potter
harryPotter
harryPotter2
Example-1:
Output:
Example-2:
x = 11
print(x)
Output:
11
Example-3:
a = 10
a = "CseHackTech"
PYTHON PROGRAMMING NOTES @abdulbasidshaik
print(a)
Output:
CseHackTech
Example-4:
a = 10
b = 20
print(a+b)
a = "CseHack"
b = "Tech"
print(a+b)
Output:
30
CseHackTech
Example-5:
a = 10
b = "Tech"
print(a+b)
Output:
Example:
a = b = c = 10
Example-Program:
a = b = c = 10
print(a)
print(b)
print(c)
Here, an integer object is created with the value 10, and all three variables are assigned to
the same memory location.
Output:
10
10
10
Example:
a, b, c = 1, 2, "abdulbasid"
PYTHON PROGRAMMING NOTES @abdulbasidshaik
Example-Program:
print(a)
print(b)
print(c)
Here, two integer objects with values 10 and 20 are assigned to the variables a and b
respectively, and one string object with the value "abdulbasid" is assigned to the
variable c.
Output:
10
20
abdulbasid
Types of variables:
There are two types of variables:
1. Local variable
2. Global variable
1. Local Variable:
● Local variables in Python are the ones that are defined and declared inside a function.
We can not call this variable outside the function.
Example-Program:
PYTHON PROGRAMMING NOTES @abdulbasidshaik
fun()
Output:
2. Global Variable:
● Global variables in Python are the ones that are defined and declared outside a
function, and we need to use them inside a function.
Example-Program:
# Global scope
s = "I love Python"
fun()
Output:
I love Python
PYTHON PROGRAMMING NOTES @abdulbasidshaik
Literals in Python
🔢 indicates a fixed value in the code.
★ In Python, a literal
★ It is a constant value that doesn't change 🚫 during the execution 💻 of the
program📚.
★ The material in this module provides an in-depth understanding of Python literals.
What are literals in Python?
There was a software engineer named Alie who needed to learn Python. She chose to begin
with the basics; one of the primary things she learned about was literal. 💡 Alie knew that in
Python, literals are fixed values that represent constant data in Python code. They are utilized
to assign values to variables, define constants, and perform different operations within the
code. 💻 She was presented with a few types of literals, such as numeric literals, string
literals in Python, boolean literals, None literals, and container literals 📦. To better
understand these literals in Python, Alie decided to utilize them in a story. 📖 This lesson
will examine diverse types of literals in Python and their utilization.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
1. Numeric Literals
2. String Literals
3. Boolean Literals
4. None Literal
5. Container Literals
A numeric literal in Python is a notation that represents a fixed numeric number in code.
Python supports three types of numeric literals:
● Integer literals
● Floating-point literals
● Complex literals
PYTHON PROGRAMMING NOTES @abdulbasidshaik
1. Integer Literals: Python uses integer literals to represent whole numbers. They might be
positive, negative, or zero.
Example:
42 # positive integer
-123 # negative integer
0 # zero
Example:
2. Complex Literals: In Python, complex literals are used to represent complex numbers,
which consist of a real part and an imaginary part. The imaginary part is denoted by the
letter "j" to differentiate it from actual numbers.
Example:
Example:
Next, Alie used string literals to represent the characters' names in her story. She wrote:
name1 = 'Abdulbasid'
name2 = "CseHacker"
name3 = '''Learn With Abdulbasid'''
Example:
Alie also used boolean literals to represent whether the characters were friends. She wrote:
Abdulbasid_and_Ashok_are_friends = True
Ashok_and_charlie_are_friends = False
Example:
Container literals in Python are data structures that can contain other literals.
1. List Literals: List literals are used to express a sequence of values. They are
contained in square brackets and separated by comma.
2. Tuple Literals: Tuple literals are used to denote a series of values. They are contained
in parentheses and separated by comma.
3. Dictionary Literals: Dictionary literals represent key-value pairs. They're contained
in curly brackets and separated by comma.
4. Set Literals: Set is the collection of the unordered data set. It is enclosed by the curly
brackets, and each element is separated by comma.
Example:
These literals in Python are used to represent constant values in Python programs, and they
cannot be modified once they are defined.
DataTypes in Python
● Datatype is used to represent what type of value we can assign to a variable.
● Datatypes are used to create variables of a specific type.
● Variables can hold values, and every value has a datatype.
● Python is a dynamically typed language. hence, we do not need to define the type of
the variable while declaring it.
● The interpreter implicitly binds the value to its type.
a = 10
➔ The variable ‘a’ holds an integer value of ten, and we did not define its type.
PYTHON PROGRAMMING NOTES @abdulbasidshaik
Example:
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<class 'int'>
<class 'str'>
<class 'float'>
Data types refer to the classification or categorization of data items. Python provides the
following built-in data types.
Telegram: telegram.me/CseHacktech
Whatsapp: bit.ly/Csehacktech
PYTHON PROGRAMMING NOTES @abdulbasidshaik
Happy coding!!
Thank You
For Your Valuable Time and Patience….
Thanks and Regards
Ur Abdulbasid Shaik
Signing Of
CSEH4CK3R