Python Basics
Md. Alamgir Hossain
Research Instructor, Skill Morph
Google Scholar: [Link]
Today’s Outline
Introduction to Python Programming, Variables & Data Types
Operators in Python
Control Structures (if-else, loops)
Python
Python is a widely used programming language that offers several
unique features and advantages compared to languages like Java
and C++.
It is a general-purpose, dynamically typed, high-level,
compiled and interpreted, garbage-collected, and purely
object-oriented programming language that supports
procedural, object-oriented, and functional programming.
Features of Python
Easy to use and Read: Python’s syntax is clear and easy to read,
making it an ideal language for both beginners and experienced
programmers. This simplicity can lead to faster development and reduce
the chances of errors.
Dynamically Typed: The data types of variables are determined during
run-time. We do not need to specify the data type of a variable during
writing codes.
High-level: High-level language means human readable code.
Compiled and Interpreted: Python code first gets compiled into
bytecode, and then interpreted line by line. When we download the
Python in our system form org we download the default implement of
Python known as CPython. CPython is considered to be Complied and
Interpreted both.
Garbage Collected: Memory allocation and de-allocation are
automatically managed. Programmers do not specifically need to manage
the memory.
Features of Python
Purely Object-Oriented: It refers to everything as an object,
including numbers and strings.
Cross-platform Compatibility: Python can be easily installed on
Windows, macOS, and various Linux distributions, allowing
developers to create software that runs across different operating
systems.
Rich Standard Library: Python comes with several standard
libraries that provide ready-to-use modules and functions for
various tasks, ranging from web development and data
manipulation to machine learning and networking.
Open Source: Python is an open-source, cost-free programming
language. It is utilized in several sectors and disciplines as a result.
Why learn Python?
Easy to use and Learn: Python has a simple and easy-to-
understand syntax, unlike traditional languages like C, C++, Java,
etc., making it easy for beginners to learn.
Expressive Language: It allows programmers to express complex
concepts in just a few lines of code or reduces Developer’s Time.
Interpreted Language: Python does not require compilation,
allowing rapid development and testing. It uses Interpreter instead
of Compiler.
Object-Oriented Language: It supports object-oriented
programming, making writing reusable and modular code easy.
Open-Source Language: Python is open-source and free to use,
distribute and modify.
Why learn Python?
Extensible: Python can be extended with modules written in C,
C++, or other languages.
Learn Standard Library: Python’s standard library contains
many modules and functions that can be used for various tasks,
such as string manipulation, web programming, and more.
GUI Programming Support: Python provides several GUI
frameworks, such as Tkinter and PyQt, allowing developers to
create desktop applications easily.
Integrated: Python can easily integrate with other languages and
technologies, such as C/C++, Java, and . NET.
Embeddable: Python code can be embedded into other
applications as a scripting language.
Why learn Python?
Dynamic Memory Allocation: Python automatically manages memory
allocation, making it easier for developers to write complex programs
without worrying about memory management.
Wide Range of Libraries and Frameworks: Python has a vast
collection of libraries and frameworks, such as NumPy, Pandas, Django,
and Flask, that can be used to solve a wide range of problems.
Versatility: Python is a universal language in various domains such as
web development, machine learning, data analysis, scientific computing,
and more.
Large Community: Python has a vast and active community of
developers contributing to its development and offering support. This
makes it easy for beginners to get help and learn from experienced
developers.
Why learn Python?
Career Opportunities: Python is a highly popular language in the job
market. Learning Python can open up several career opportunities in
data science, artificial intelligence, web development, and more.
High Demand: With the growing demand for automation and digital
transformation, the need for Python developers is rising. Many industries
seek skilled Python developers to help build their digital infrastructure.
Increased Productivity: Python has a simple syntax and powerful
libraries that can help developers write code faster and more efficiently.
This can increase productivity and save time for developers and
organizations.
Big Data and Machine Learning: Python has become the go-to
language for big data and machine learning. It has become popular
among data scientists and machine learning engineers with libraries like
NumPy, Pandas, Scikit-learn, TensorFlow, and more.
Where is Python used?
Data Science: Data Science is a vast field, and Python is an important
language for this field because of its simplicity, ease of use, and
availability of powerful data analysis and visualization libraries like
NumPy, Pandas, and Matplotlib.
Desktop Applications: PyQt and Tkinter are useful libraries that can
be used in GUI - Graphical User Interface-based Desktop Applications.
Console-based Applications: Python is also commonly used to create
command-line or console-based applications because of its ease of
use and support for advanced features such as input/output redirection
and piping.
Mobile Applications: While Python is not commonly used for creating
mobile applications, it can still be combined with frameworks like Kivy or
BeeWare to create cross-platform mobile applications.
Software Development: Python is considered one of the best software-
making languages. Python is easily compatible with both from Small
Scale to Large Scale software.
Where is Python used?
Artificial Intelligence: AI is an emerging Technology, and Python is a
perfect language for artificial intelligence and machine learning
because of the availability of powerful libraries such as TensorFlow,
Keras, and PyTorch.
Web Applications: Python is commonly used in web development on the
backend with frameworks like Django and Flask and on the front
end with tools like JavaScript HTML and CSS.
Enterprise Applications: Python can be used to develop large-scale
enterprise applications with features such as distributed computing,
networking, and parallel processing.
3D CAD Applications: Python can be used for 3D computer-aided
design (CAD) applications through libraries such as Blender.
Machine Learning: Python is widely used for machine learning due to
its simplicity, ease of use, and availability of powerful machine learning
libraries.
Where is Python used?
Computer Vision or Image Processing Applications: Python can be
used for computer vision and image processing applications through
powerful libraries such as OpenCV and Scikit-image.
Speech Recognition: Python can be used for speech recognition
applications through libraries such as SpeechRecognition and
PyAudio.
Scientific computing: Libraries like NumPy, SciPy, and Pandas
provide advanced numerical computing capabilities for tasks like data
analysis, machine learning, and more.
Education: Python’s easy-to-learn syntax and availability of many
resources make it an ideal language for teaching programming to
beginners.
Testing: Python is used for writing automated tests, providing
frameworks like unit tests and pytest that help write test cases and
generate reports.
Where is Python used?
Gaming: Python has libraries like Pygame, which provide a platform for
developing games using Python.
IoT: Python is used in IoT for developing scripts and applications for devices like
Raspberry Pi, Arduino, and others.
Networking: Python is used in networking for developing scripts and
applications for network automation, monitoring, and management.
DevOps: Python is widely used in DevOps for automation and scripting of
infrastructure management, configuration management, and deployment
processes.
Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for
financial modeling and analysis.
Audio and Music: Python has libraries like Pyaudio, which is used for audio
processing, synthesis, and analysis, and Music21, which is used for music
analysis and generation.
Writing scripts: Python is used for writing utility scripts to automate tasks like
file operations, web scraping, and data processing.
Python vs Java vs C
Python print() Function
Python print() function is used to display output to the console or
terminal. It allows us to display text, variables and other data in a human
readable format.
Syntax: print(object(s), sep = separator, end = end, file = file, flush =
flush)
It takes one or more arguments separated by comma(,) and adds a
‘newline’ at the end by default.
Parameters:
object - value(s) to be printed
sep (optional) - allows us to separate multiple objects inside print().
end (optional) - allows us to add specific values like new line “\n”, tab “\t”
file (optional) - where the values are printed. It’s default value is [Link]
(screen)
flush (optional) - boolean specifying if the output is flushed or buffered. Default:
False
Python print() Function
Variables and Literals
In programming, a variable is a container (storage area) to hold
data. For example, number = 10; Here, number is a variable
storing the value 10. We use the assignment operator = to assign a
value to a variable.
Assigning values to Variables in Python:
Note: Python is a type-inferred language, so you don’t have to
explicitly define the variable type.
Assigning Multiple Values to Multiple Variables
Changing the Value of a Variable
Rules for Naming Python Variables
Constant and variable names should have a combination of letters
in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore (_). For example:
snake_case, MACRO_CASE, camelCase, CapWords
Create a name that makes sense. For example, vowel makes
more sense than v.
If you want to create a variable name having two words, use
underscore to separate them. For example:
my_name, current_salary
Python is case-sensitive. So num and Num are different variables.
Avoid using keywords like if, True, class, etc., as variable names.
Python Literals
Literals are representations of fixed values in a program. They can
be numbers, characters, or strings, etc. For example, ‘Hello,
World!’, 12, 23.0, ‘C’, etc.
Literals are often used to assign values to variables or constants.
For example, org_name = ‘SKILLMORPH’; org_name is a variable,
and ‘SKILLMORPH’ is a literal.
Numeric Literals
Numeric Literals are immutable (unchangeable). Numeric literals
can belong to 3 different numerical types: Integer, Float, and
Complex.
Integer literals are numbers without decimal parts. It also consists
of negative numbers. For example, 5, -11, 0, 12, etc.
Floating-point literals are numbers that contain decimal parts. For
example, 2.5, 6.76, 0.0, -9.45, etc.
Complex literals are numbers that represent complex numbers.
Here, numerals are in the form a + bj, where a is real and b is
imaginary. For example, 6+9j, 2+3j.
String Literals
In Python, texts wrapped inside quotation marks are called string
literals. For example: “This is a string.”
We can also use single quotes to create strings. ‘This is also a
string.’
Others Literals
There are two boolean literals: True and False. For example,
is_pass = True
Character literals are unicode characters enclosed in a quote. For
example, some_character = ‘S’.
Python contains one special literal None. We use it to specify a
null variable. For example, value = None;
Collection Literals
Python Type Conversion
In programming, type conversion is the process of converting data
of one type to another. For example: converting int data to str.
There are two types of type conversion in Python.
Implicit Conversion - automatic type conversion
Explicit Conversion - manual type conversion
In certain situations, Python automatically converts one data type
to another. This is known as implicit type conversion.
In Explicit Type Conversion, users convert the data type of an
object to required data type.
Converting integer to float (Implicit)
Let’s see an example where Python promotes the conversion of the
lower data type (integer) to the higher data type (float) to avoid
data loss.
Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an
object to required data type.
We use the built-in functions like int(), float(), str(), etc to perform
explicit type conversion.
This type of conversion is also called typecasting because the user
casts (changes) the data type of the objects.
Explicit Type Conversion (Example)
Key Points to Remember
Type Conversion is the conversion of an object from one data type
to another data type.
Implicit Type Conversion is automatically performed by the Python
interpreter.
Python avoids the loss of data in Implicit Type Conversion.
Explicit Type Conversion is also called Type Casting, the data
types of objects are converted using predefined functions by the
user.
In Type Casting, loss of data may occur as we enforce the object to
a specific data type.
Key Points to Remember
Type Conversion is the conversion of an object from one data type
to another data type.
Implicit Type Conversion is automatically performed by the Python
interpreter.
Python avoids the loss of data in Implicit Type Conversion.
Explicit Type Conversion is also called Type Casting, the data
types of objects are converted using predefined functions by the
user.
In Type Casting, loss of data may occur as we enforce the object to
a specific data type.
Python Basic Input and Output
Python Operators
Operators are special symbols that perform operations on
variables and values. For example, print(5 + 6) # 11
Here’s a list of different types of Python operators that we will
learn in this tutorial.
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Bitwise Operators
Special Operators
Python Arithmetic Operators
Arithmetic operators are used to perform mathematical operations
like addition, subtraction, multiplication, etc.
Operator Operation Example
+ Addition 5+2=7
- Subtraction 4-2=2
* Multiplication 2*3=6
/ Division 4/2=2
// Floor Division 10 // 3 = 3
% Modulo 5%2=1
** Power 4 ** 2 = 16
Python Arithmetic Operators (Example)
Python Assignment Operators
Assignment operators are used to assign values to variables. For
example, # assign 5 to x; x = 5
Operator Name Example
= Assignment Operator a=7
+= Addition Assignment a += 1 # a = a + 1
-= Subtraction Assignment a -= 3 # a = a - 3
*= Multiplication Assignment a *= 4 # a = a * 4
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
**= Exponent Assignment a **= 10 # a = a ** 10
Python Assignment Operators (Example)
Python Comparison Operators
Comparison operators compare two values/variables and return a
boolean result: True or False. For example, a = 5; b = 2; print (a >
b) # True
Operator Meaning Example
== Is Equal To 3 == 5 gives us False
!= Not Equal To 3 != 5 gives us True
> Greater Than 3 > 5 gives us False
< Less Than 3 < 5 gives us True
Greater Than or Equal
>= 3 >= 5 give us False
To
<= Less Than or Equal To 3 <= 5 gives us True
Comparison Operators (Example)
Python Logical Operators
Logical operators are used to check whether an expression is True
or False. They are used in decision-making.
Operator Example Meaning
Logical AND:
and a and b
True only if both the operands are True
Logical OR:
or a or b
True if at least one of the operands is True
Logical NOT:
not not a
True if the operand is False and vice-versa.
Logical Operators (Example)
Python Bitwise Operators
Bitwise operators act on operands as if they were strings of binary
digits. They operate bit by bit, hence the name. For example, 2 is
10 in binary, and 7 is 111. In the table below: Let x = 10 (0000
1010 in binary) and y = 4 (0000 0100 in binary)
Operator Meaning Example
& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x >> 2 = 2 (0000 0010)
<< Bitwise left shift x 0010 1000)
Python Special operators
Python language offers some special types of operators like the
identity operator and the membership operator.
Identity operator: In Python, is and is not are used to check if two
values are located at the same memory location.
It’s important to note that having two variables with equal values
doesn’t necessarily mean they are identical.
Operator Meaning Example
True if the operands are identical (refer to the same
is x is True
object)
True if the operands are not identical (do not refer
is not x is not True
to the same object)
Identity Operators (Example)
Here, we see that x1 and y1 are integers of the same values, so
they are equal as well as identical. The same is the case with x2
and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is
because the interpreter locates them separately in memory,
although they are equal.
Membership operators
In Python, in and not in are the membership operators. They are
used to test whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary).
In a dictionary, we can only test for the presence of a key, not the
value.
Operator Meaning Example
in True if value/variable is found in the sequence 5 in x
True if value/variable is not found in the
not in 5 not in x
sequence
Membership Operators (Example)
Here, ‘H’ is in message, but ‘hello’ is not present in message
(remember, Python is case-sensitive).
Similarly, 1 is key, and ‘a’ is the value in dictionary dict1. Hence,
‘a’ in y returns False.
Python Flow Control (Conditional Statement)
Python if...else Statement
The if statement is a conditional statement. It is used to execute a
block of code only when a specific condition is met. For example,
If a student scores above 90, assign grade A
If a student scores above 75, assign grade B
If a student scores above 65, assign grade C
These conditional tasks can be achieved using the if statement.
Python if Statement
An if statement executes a block of code only when the specified
condition is met.
Syntax:
if condition:
# body of if statement
Here, condition is a boolean expression, such as number > 5, that
evaluates to either True or False.
If condition evaluates to True, the body of the if statement is executed.
If condition evaluates to False, the body of the if statement will be skipped
from execution.
Example
Example
Indentation in Python
Python uses indentation to define a block of code, such as the body of an
if statement. For example,
Here, the body of if has two statements. We know this because two
statements (immediately after if) start with indentation.
We usually use four spaces for indentation in Python, although any
number of spaces works as long as we are consistent.
Python if...else Statement
An if statement can have an optional else clause. The else
statement executes if the condition in the if statement evaluates to
False.
Syntax:
if condition:
# body of if statement
else:
# body of else statement
Example
Example
Python if…elif…else Statement
The if...else statement is used to execute a block of code among
two alternatives.
However, if we need to make a choice between more than two
alternatives, we use the if...elif...else statement.
Syntax:
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
Example
Python program to check a number is
Positive, Negative or Zero
Python Nested if Statements
It is possible to include an if statement inside another if
statement. For example,
Python Nested if Statements
Compact if Statement
In certain situations, the if statement can be simplified into a
single line. For example,
Ternary Operator in Python:: if...else
Python doesn’t have a ternary operator. However, we can use
if...else to work like a ternary operator in other languages. For
example,
Logical Operators to Add Multiple
Conditions
If needed, we can use logical operators such as and and or to
create complex conditions to work with an if statement.
Grade Calculation
Simple traffic light system
Body Mass Index (BMI) Calculation
Leap Year Checker
Loop
Loops
Python loops allow us to execute a statement or group of
statements multiple times.
In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second,
and so on. There may be a situation when you need to execute a
block of code several number of times.
Python “for” Loop
In Python, we use a for loop to iterate over sequences such as
lists, strings, dictionaries, etc.
Flowchart:
Example: Loop Through a String
“for” Loop with Python range()
Sum of First N Natural Numbers
Multiplication Table
Factorial of a Number
Check for Prime Number
Count Vowels in a String
Fibonacci Sequence
Python while Loop
In Python, we use a while loop to repeat a block of code until a
certain condition is met.
Syntax:
while condition:
# body of while loop
Python while Loop (Example)
Python while loop with an else clause
In Python, a while loop can have an optional else clause - that is
executed once the loop condition is False.
Python “for” loop vs “while” loop
The for loop is usually used in the sequence when the number of
iterations is known.
The while loop is usually used when the number of iterations is
unknown.
Python “break” Statement
The break statement terminates the loop immediately when it's
encountered.
“break” Statement with “for” Loop
We can use the break statement with the for loop to terminate the
loop when a certain condition is met.
Python “while” loop with “break” statement
Python “while” loop with “break” statement
We can use a break statement inside a while loop to terminate the
loop immediately without checking the test condition.
Python “continue” Statement
The continue statement skips the current iteration of the loop and
the control flow of the program goes to the next iteration.
“continue” Statement with “for” Loop
“continue” Statement with “while” Loop
Simple number guessing game where the
user has to guess a secret number
Reverse a Number
Python “pass” Statement
In Python programming, the pass statement is a null statement
which can be used as a placeholder for future code.
Suppose we have a loop or a function that is not implemented yet,
but we want to implement it in the future. In such cases, we can
use the pass statement.
Using “pass” With Conditional Statement
Coding Notebook
GitHub Link: [Link]
Morph/blob/main/Python_Basics.ipynb
Assignment
Link: [Link]
Approach: Upload the complete Notebook to GitHub and just add
the link.
Date of Submission: Before the next class.
Thank You