0% found this document useful (0 votes)
3 views

PYTHON NOTES

This document provides comprehensive notes on Python programming, covering its introduction, features, types of programming languages, and installation steps on Windows. It explains key concepts such as software, programs, coding, and the differences between compilers and interpreters. Additionally, it outlines Python's history, applications, and essential features that make it a popular choice for both beginners and experienced programmers.

Uploaded by

jaikumar84980
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

PYTHON NOTES

This document provides comprehensive notes on Python programming, covering its introduction, features, types of programming languages, and installation steps on Windows. It explains key concepts such as software, programs, coding, and the differences between compilers and interpreters. Additionally, it outlines Python's history, applications, and essential features that make it a popular choice for both beginners and experienced programmers.

Uploaded by

jaikumar84980
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

PYTHON PROGRAMMING NOTES @abdulbasidshaik

INTRODUCTION TO PYTHON
UNIT-I

INTRODUCTION TO PYTHON PROGRAMMING, OPERATORS, CONTROL FLOW


STATEMENTS
Introduction to Python programming: why to learn Python, procedure for executing
Python program, keywords, Variables and identifiers, Data types, and conversions,
indentation
Operators & Control flow statements: Operators, Conditional statements, Iterations,
break continue statements.

#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.

- A computer program is a collection of instructions that can be executed by a computer to


perform a specific task. A computer program is usually written by a computer programmer in
a programming language. From the program in its human-readable form of source code, a
compiler or assembler can derive machine code—a form consisting of instructions that the
computer can directly execute. Alternatively, a computer program may be executed with the
aid of an interpreter.

#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..

TYPES OF PROGRAMMING LANGUAGES:


- There are three types of programming languages………

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

Difference between Compiler and Interpreter:


COMPILER:
1. A language processor that converts a program written in a high-level language into machine
language, an entire program at once, is called a compiler. Thus, the input of a compiler is a
high-level language code (called source code), while its output is a machine language code
(called object code).

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

S.NO COMPILER INTERPRETER

1. The compiler scans the whole Translates program one statement at a


program in one go. time.

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.

3. The main advantage of compilers is Due to interpreters being slow in executing


their execution time. the object code, it is preferred less.

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.

6. C, C++, C# etc. Python, Ruby, Perl, SNOBOL, MATLAB,


etc.

INTRODUCTION TO PYTHON

● Python is a general-purpose, high-level, interpreted, interactive, object-oriented


programming language developed by Guido van Rossum in the late 1980 - 1990s
(1991) at the National Research Institute for Mathematics and Computer Science in
the Netherlands.
● Python is one of the most popular and widely used programming languages used for a
set of tasks including console-based, GUI-based, web programming, and data
analysis.
● Python is an easy-to-learn and simple programming language so even if you are new
to programming, you can learn Python without facing any problems.

Fact: Python is named after the comedy television show “Monty Python's Flying Circus”
and not after Python Snake.
PYTHON PROGRAMMING NOTES @abdulbasidshaik

❖ Python is General-purpose: Python is a general-purpose language, not specialized


for any specific problems, and used to create various programs. This versatility and its
beginner-friendliness have made it one of the most used programming languages
today.
❖ Python is High-level: Python is a high-level programming language known for its
readability and ease of use.
❖ Python is Interpreted: Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it. This is similar to PERL and PHP.
❖ Python is Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
❖ Python is Object-Oriented: Python supports an Object-Oriented style or technique
of programming that encapsulates code within objects.
❖ Python is a Beginner's Language: Python is a great language for beginner-level
programmers and supports the development of a wide range of applications from
simple text processing to WWW browsers to games.

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

● ABC programming language is said to be the predecessor of Python language, which


was capable of Exception Handling and interfacing with the Amoeba Operating
System.
● The following programming languages influence Python:
➔ ABC language
➔ Modula-3
Why the name python?
● There is a fact behind choosing the name Python. Guido Van Rossum was
reading the script of a popular BBC comedy series “Monty Python’s Flying
Circus”. It was late on-air 1970s.
● Van Rossum wanted to select a name which unique, sort, and a little mysterious.
So he decided to select naming Python after “Monty Python’s Flying Circus”
for their newly created programming language.
● The comedy series was creative and well random. It talks about everything.
Thus it is slow and unpredictable, which makes it very interesting.

#FEATURES OF PYTHON, or Why Learn Python?

👌🏻
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

9. Large Standard Library 📚


1. Easy to Learn and Use: Python is easy to learn and use compared with other
programming languages. It is developer-friendly and high-level programming language.
2. Interpreted Language: Python is an interpreted language because no need for
compilation. This makes debugging easy and thus suitable for beginners.
3. Cross-platform Language: Python can run equally on different platforms such as
Windows, Linux, Unix Macintosh, etc. So, we can say that Python is a portable language.
4. Free and Open Source: Python language is freely available at the official web
address. The source code is also available. Therefore it is open source.
5. Object-Oriented Language: Python supports object-oriented language and concepts
of classes and objects come into existence. It supports:
★ Inheritance,
★ Polymorphism,
★ Data Abstraction and
★ Encapsulation, etc.

The object-oriented procedure helps programmers to write reusable code and develop
applications in less code.
PYTHON PROGRAMMING NOTES @abdulbasidshaik

6. GUI Programming Support: A Graphical User Interface is used for developing


Desktop applications. PyQT5, Tkinter, and Kivy are the libraries that are used for
developing the web application.
7. Integrated: It can be easily integrated with languages like C, C++, and JAVA, etc.
Python runs code line by line like C, C++ Java. It makes it easy to debug the code.
8. Dynamic Memory Allocation: In Python, we don't need to specify the data type of
the variable. When we assign some value to the variable, it automatically allocates the
memory to the variable at run time. Suppose we are assigned an integer value 15 to x,
then we don't need to write int x = 15. Just write x = 15.
9. Large Standard Library: Python has a large and broad library and provides a rich set
of modules and functions for rapid application development.

#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

PYTHON INSTALLATION ON WINDOWS


The installation requires downloading the official Python .exe installer and running it on your
system. The sections below will explain several options and details during the installation process.

STEP-1: Select Python Version


Deciding on a version depends on what you want to do in Python. The two major versions
are Python 2 and Python 3. Choosing one over the other might be better depending on your
project details. If there are no constraints, choose whichever one you prefer.

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

STEP-2: Download Python Executable Installer


Start by downloading the Python executable installer for Windows:
1. Open a web browser and navigate to the Downloads for Windows section of the
official Python website.
2. Locate the desired Python version.

3. Click the link to download the file. Choose either the Windows 32-bit or 64-bit
installer.

The download is approximately 25MB.

STEP-3: Run Executable Installer


The steps below guide you through the installation process:
1. Run the downloaded Python Installer.
2. The installation window shows two checkboxes:
● Admin privileges. The parameter controls whether to install Python for the
current or all system users. This option allows you to change the installation
folder for Python.
PYTHON PROGRAMMING NOTES @abdulbasidshaik

● 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.

For the most straightforward installation, we recommend ticking both checkboxes.

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

The default installation installs Python to


C:\Users\[user]\AppData\Local\Programs\Python\Python[version] for the current user. It
includes IDLE (the default Python editor), the PIP package manager, and additional
documentation. The installer also creates necessary shortcuts and file associations.

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

Click Next to proceed to the Advanced Options screen.

5. The second part of customizing the installation includes advanced options.

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.

STEP4: Add Python to Path (Optional)


If the Python installer does not include the Add Python to PATH checkbox or you have not
selected that option, continue in this step. Otherwise, skip to the next step.

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.

To add Python to PATH, do the following:

1. In the Start menu, search for Environment Variables and press Enter.

2. Click Environment Variables to open the overview screen.


PYTHON PROGRAMMING NOTES @abdulbasidshaik

3. Double-click Path on the list to edit it.


PYTHON PROGRAMMING NOTES @abdulbasidshaik

Alternatively, select the variable and click the Edit button.

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.

PROCEDURE TO EXECUTING PYTHON PROGRAM: (Running Python


Scripts)

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.

How to Run a Python Program in Interactive Mode?

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-1: Open your terminal or command prompt.

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

STEP-4: To exit the interpreter, type exit() and press Enter.

Here by typing the exit() statement, we come out of the Python interpreter.

How to Run a Python Program Using Python Command Line?

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.

NOTE: Python programs are always saved with a .py extension.


PYTHON PROGRAMMING NOTES @abdulbasidshaik

STEP-2: Open your terminal or command prompt and Navigate to the directory where
your Python file is located using the cd command.

Now we are in the directory where our welcomecode.py file is saved.


PYTHON PROGRAMMING NOTES @abdulbasidshaik

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.

How to Run a Python Program on a Text Editor?

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-3: Now type your Python program in the file.

STEP-4: To run this file, double-click on Run Python File in Terminal.


PYTHON PROGRAMMING NOTES @abdulbasidshaik

STEP-5: The output of the Python program will be visible in the Terminal present in the
VS Code.

Introduction to Google Colab


Google Colaboratory, or Google Colab, is a web-based development environment
allowing users to run and write code in Python. It is a free-of-cost environment provided
by Google that enables users to execute code, save and share notebooks, and collaborate
with others in real-time. It can also be directly put into GitHub.
PYTHON PROGRAMMING NOTES @abdulbasidshaik

Getting started with Python Coding

💻 🍎 🐧
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 for Python Programming

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

● Zero configuration required


● Access to GPUs free of charge
● Easy sharing

Whether you are an understudy, a 🧑‍🔬


data researcher, or an AI analyst, Colab can make
your work less demanding. You'll begin your Python coding right absent from

https: //colab.research.google.com/
PYTHON PROGRAMMING NOTES @abdulbasidshaik

Why use Google Colab for Python

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.

Using Google Colab for Machine Learning

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.

How to Use Google Colab:


PYTHON PROGRAMMING NOTES @abdulbasidshaik

🔎 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.

Example: sample code in Python


PYTHON PROGRAMMING NOTES @abdulbasidshaik

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.

Some common examples of runtime errors are:

➔ Division by zero
➔ Null pointer dereferencing
➔ Array index out of bounds
➔ Resource leaks (e.g., memory or open file handles)

In Python, what does end =' do?


● In the print function, any string can be added using the end parameter. when the
Python print statement has finished producing its output.
● By default, the print function ends with a new line.
● Passing the whitespace to the end parameter (end=" ") indicates that the end
character has to be identified by whitespace and not a newline.

Example-program-1:

print("CseHackTech", end=" ")

print("is awesome")

Output:
CseHackTech is awesome

Example-program-2:
PYTHON PROGRAMMING NOTES @abdulbasidshaik

print("CseHacker", end=" says")

print(" your awesome")

Output:
CseHacker says your awesome

Example-program-3:

print("Hello", end=" back benchers, ")

print("am your cseh4ck3r")

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.

Types of Comments in Python

There are two types of comments in Python.

1. Single line comment


PYTHON PROGRAMMING NOTES @abdulbasidshaik

2. Multi-line comment

1. SINGLE LINE COMMENT:

● In Python, we use # special character to start the comment. Let’s take a few
examples to understand the usage.

# This is just a comment. Anything written here is ignored by Python

2. MULTI-LINE COMMENT:

● To have a multi-line comment in Python, we use triple single quotes at the


beginning and at the end of the comment, as shown below.

'''
This is a
multi-line
comment
'''

Python Comments Example:

● In this Python program, we are seeing three types of comments. Single-line


comments, multi-line comments, and comments that start in the same line after the
code.

'''
We are writing a simple program here
First print statement.
This is a multiple-line comment.
'''
PYTHON PROGRAMMING NOTES @abdulbasidshaik

print("Hello Backbenchers")

# Second print statement

print("How are You all?")

print("Welcome to hackersworld") # Third print statement

TOKENS:

● The smallest unit of programming language that is used to compose instructions is


known as “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...

False class from or None


PYTHON PROGRAMMING NOTES @abdulbasidshaik

continue global pass True def

if raise and del import

return as elif in try

assert else is while async

except lambda with await finally

nonlocal yield break for not

➢ We can get the list of keywords in your current version by typing the following in
the prompt.

>>> help("keywords")

(or)

>>> import keyword

>>> print(keyword.kwlist)

Identifiers:

● The name given to the components of Python by the programmer is known as an


identifier.
● Identifier means any name that is given by programmers.
● Identifiers in Python are symbolic names used for identification.

List of components:
★ Class
★ Function
★ Variable, etc..,
PYTHON PROGRAMMING NOTES @abdulbasidshaik

Note: A programmer should follow the “rules” and “conventions” for an identifier.

Rules for writing identifiers:


1. The identifier can be a combination of letters in lowercase (a to z) or uppercase
(A to Z) or digits (0 to 9) or an underscore ( _ ).

Example:
➔ my_variable ✅
➔ MY_VARIABLE ✅
➔ my_Variable1 ✅
➔ 1variable ❌

2. An identifier should not start with digits.

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 ❌

4. Character space is not allowed in the identifier.

Example:
➔ Abdu l❌
➔ Ab dul ❌
➔ Abdul basid❌
➔ Abdul_basid ✅
➔ @bdul_basid ❌

5. Keywords should not be used for identifiers.

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?

● A variable is a container that is used to store a single value.


📦 in a computer's memory 💾 that can hold a
● A variable is a named storage location
value🔢, which can be changed 🔁 during the execution 💻 of a program 📝 or
script 📃.
● Any data type in Python, such as an integer, string, or list, can be used as the value.
● Variables are used to store information that will be needed during the program.
● In Python, you do not need to define a variable before using it.
● When you assign a value to a variable, it is created.
● You can change the value of a variable at any moment. This will override the
variable's previous value.

How to create a variable


PYTHON PROGRAMMING NOTES @abdulbasidshaik

Creating a variable is a fundamental concept in programming and can be done in several


ways. The simplest way is to choose a name for your variable and use the assignment
operator = to assign a value to it. This process allows you to store data in memory and
reference it later in your program. To create a variable in Python, use this syntax:

Syntax:

variable_name = value

Example:

name = “abdubasid”

Rules for Creating Variables

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

Some invalid variable names are:

2harry #cannot start with a number


harry-potter #cannot contain a hyphen
h@rry #cannot contain a special character
harry potter #Spaces are not allowed in var names.

Assigning Values to Variables 👍


● Python variables do not need an explicit declaration to reserve memory space.
PYTHON PROGRAMMING NOTES @abdulbasidshaik

● The declaration happens automatically when you assign a value to a variable.


● The equal sign (=) is used to assign values to variables.
● The operand to the left of the “=” operator is the name of the variable, and the
operand to the right of the = operator is the value stored in the variable.

Example-1:

# Declare a variable named 'age'


age = 23

# Declare a variable named 'name'


name = "abdulbasid"

# Print the values of the variables 'age' and 'name'


print("My name is ", name, "and I am ", age, " years old")

Output:

My name is abdulbasid and I am 23 years old

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:

TypeError: unsupported operand type(s) for +: 'int' and 'str'


PYTHON PROGRAMMING NOTES @abdulbasidshaik

Assigning Values to Variables 👍


1. Python allows you to assign a single value to several variables simultaneously.

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

2. You can also assign multiple objects to multiple variables.

Example:

a, b, c = 1, 2, "abdulbasid"
PYTHON PROGRAMMING NOTES @abdulbasidshaik

Example-Program:

a, b, c = 10, 20, "abdulbasid"

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

# This function uses global variable s


def fun():
s = "Welcome to the entertainment world."
print(s)

fun()

Output:

Welcome to the entertainment world.

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:

# This function has a variable with


# name same as s
def fun():
print(s)

# 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

Types of Literals in Python

Python supports several types of literals, including:

1. Numeric Literals
2. String Literals
3. Boolean Literals
4. None Literal
5. Container Literals

Numeric Literals in Python

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

2. Floating-point Literals: Python uses floating-point literals to express decimal values.


They might be positive, negative, or zero and are expressed in scientific notation.

Example:

3.14 # positive floating-point number


- 2.5 # negative floating-point number
4.2e-3 # positive floating-point number written in scientific notation

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:

- 2 + 3j # complex number with a real part of 2 and an imaginary part of 3


- 1.5 - 2.5j # complex number with a real part of -1.5 and an imaginary
part of -2.5

String Literals in Python


String literals in Python represent strings of characters. They are enclosed in single quotes,
double quotes, or triple quotes.

Example:

- 'hello' # a string literal enclosed in single quotes


- "world" # a string literal enclosed in double quotes
PYTHON PROGRAMMING NOTES @abdulbasidshaik

- '''Python is a programming language. It is used for web development,


scientific computing,artificial intelligence, and more.''' # a string
literal enclosed in triple quotes

Next, Alie used string literals to represent the characters' names in her story. She wrote:

name1 = 'Abdulbasid'
name2 = "CseHacker"
name3 = '''Learn With Abdulbasid'''

Boolean Literals in Python


Boolean literals in Python represent the truth values True and False.

Example:

- True # a boolean literal representing true


- False # a boolean literal representing false

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

None Literal in Python

The None literal in Python represents a null value.

Example:

None # a None literal representing null

Container Literals In Python


PYTHON PROGRAMMING NOTES @abdulbasidshaik

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:

[1, 2, 3] # a list literal containing integers


{'name': 'Alie', 'age': 25} # a dictionary literal containing key-value
pairs
(1, 2, 3) # a tuple literal containing integers
{'a', 'e', 'i', 'o', 'u'} # a set literal containing unordered data set.

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

➔ Python interpreter will automatically interpret variables ‘a’ as an integer type.


➔ Python enables us to check the type of the variable used in the program.
➔ Python provides us with the type() function, which returns the type of the variable
passed.

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'>

Types of Data Types:

Data types refer to the classification or categorization of data items. Python provides the
following built-in data types.

Sl. No Name of Data Type Keywords Description

1 Numeric Types int, float, complex holds numeric values

2 String Type str holds a sequence of characters

3 Sequence Types list, tuple, range holds a collection of items

4 Mapping Type dict holds data in key-value pair form


PYTHON PROGRAMMING NOTES @abdulbasidshaik

5 Set Types set, frozenset holds a collection of unique items

6 Boolean Type bool holds either True or False

1. Numeric Types: (int, float, complex)


● In Python, the numeric data type is used to store numerical values.
● Python numbers include integers, floating-point numbers, and complex
numbers. In Python, they are classified as int, float, or complex.
➔ int - Holds signed integers of non-limited length.
➔ float - Contains floating decimal points and is accurate to 15
decimal places.
➔ complex - contains complex numbers.

[REMAINING NOTES UPDATE SOON…………………………]

An investment in knowledge always pays the best interest. I hope you


like the tutorial. Do come back for more because learning paves the
way for a better understanding

Do not forget to share and Follow.

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

You might also like