What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released
in 1991.
• A high-level language, used in data science, automation, AI, web development and
more.
• Known for its readability, which means code is easier to write, understand and maintain.
• Backed by strong library support, we don’t have to build everything from scratch.
• It allows writing programs with fewer lines of code, improving readability.
• It automatically detects variable types at runtime, eliminating the need for explicit
declarations.
• It is used in web development, data analysis, automation, and many other fields.
What can Python do?
• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software
development.
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional way.
Basic Code Example
The following is a simple program that displays the message “Hello, World!” on the screen.
# Python Program to Print Hello World!
print("Hello World!")
• print() is a built-in Python function that instructs the computer to display text on the
screen.
• "Hello, World!" is a string, which is a sequence of text. In Python, strings are enclosed
in quotes (either single ' or double ").
Indentation in Python
In Python, Indentation is used to define blocks of code. It indicates to the Python interpreter
that a group of statements belongs to the same block. All statements with the same level of
indentation are treated as part of the same code block. Indentation is created using whitespace
at the beginning of each line, and the commonly accepted convention is to use four spaces
per indentation level.
Famous Application Built using Python
• YouTube: World’s largest video-sharing platform uses Python for features like video
streaming and backend services.
• Instagram: This popular social media app relies on Python’s simplicity for scaling and
handling millions of users.
• Spotify: Python is used for backend services and machine learning to personalize
music recommendations.
• Dropbox: The file hosting service uses Python for both its desktop client and server-
side operations.
• Netflix: Python powers key components of Netflix’s recommendation engine and
content delivery systems (CDN).
• Google: Python is one of the key languages used in Google for web crawling, testing
and data analysis.
• Uber: Python helps Uber handle dynamic pricing and route optimization using
machine learning.
• Pinterest: Python is used to process and store huge amounts of image data efficiently.
Advantages of Python
1. Presence of third-party modules: Python has a rich ecosystem of third-party modules
and libraries that extend its functionality for various tasks.
2. Extensive support libraries: Python boasts extensive support libraries like NumPy for
numerical calculations and Pandas for data analytics, making it suitable for scientific
and data-related applications.
3. Open source and large active community base: Python is open source, and it has a
large and active community that contributes to its development and provides support.
4. Versatile, easy to read, learn, and write: Python is known for its simplicity and
readability, making it an excellent choice for both beginners and experienced
programmers.
5. Dynamically typed language: Python is dynamically typed, meaning you don't need
to declare data types explicitly, making it flexible but still reliable.
6. Object-Oriented and Procedural programming language: Python supports both object-
oriented and procedural programming, providing versatility in coding styles.
7. Portable and interactive: Python is portable across operating systems and interactive,
allowing real-time code execution and testing.
Disadvantages of Python
1. Performance: Python is an interpreted language, which means that it can be slower
than compiled languages like C or Java. This can be an issue for performance-
intensive tasks.
2. Global Interpreter Lock: The Global Interpreter Lock (GIL) is a mechanism in Python
that prevents multiple threads from executing Python code at once. This can limit the
parallelism and concurrency of some applications.
3. Memory consumption: Python can consume a lot of memory, especially when
working with large datasets or running complex algorithms.
4. Dynamically typed: Python is a dynamically typed language, which means that the
types of variables can change at runtime. This can make it more difficult to catch
errors and can lead to bugs.
5. Packaging and versioning: Python has a large number of packages and libraries,
which can sometimes lead to versioning issues and package conflicts.
6. Lack of strictness: Python's flexibility can sometimes be a double-edged sword.
While it can be great for rapid development and prototyping, it can also lead to code
that is difficult to read and maintain.
7. Not Ideal for System Programming / Embedded Systems / Mobile Development /
Frontend: For real-time constraints, low-level systems programming (drivers, OS
kernels, embedded microcontrollers), or very tight performance latency, Python
typically isn’t used. There is comparatively weak support or adoption for mobile apps
or browser-side code
Python Tokens and Character Sets
In Python, every program is formed using valid characters and tokens. The character set
defines which characters are allowed in a Python program, while tokens represent the
smallest meaningful units such as keywords, identifiers, literals, operators, and symbols.
Character Set
A character set is the collection of valid characters that a programming language understands.
Python supports a wide range of characters, making it flexible and easy to use. Python
character set includes:
1. Alphabets: A–Z, a–z
2. Digits: 0–9
3. Special symbols: + - * / % = @ # $ & _ etc.
4. Whitespace characters: space, tab, newline
5. Unicode characters: Python supports full Unicode
These characters are used to form keywords, variables, expressions and statements.
Tokens
A token is the smallest meaningful unit in a Python program. Python code is interpreted by
breaking it into tokens. Python has the following types of tokens:
1. Keywords: Keywords are reserved words with special meaning in Python. They cannot
be used as variable or function names. Examples of keywords: if, else, for, while, break,
continue, True, False, import, class
2. Identifiers: Identifiers are names given to variables, functions, classes, etc. Rules for
identifiers:
• Can contain letters, digits, and _
• Cannot start with a digit
• Cannot be a keyword
• Case-sensitive
3. Literals (Values): Literals are the fixed values or data items used in a source code.
Python supports different types of literals such as:
String Literals represent text values enclosed in quotes.
msg = "Hello Python"
print(msg)
OUTPUT:
Hello Python
Numeric Literals represent integer or decimal numbers.
a = 10
b = 3.5
print(a)
print(b)
OUTPUT:
10
3.5
Boolean Literals represent logical values: True or False.
is_valid = True
4. Operators: These are the tokens responsible to perform an operation in an
expression. The variables on which operation is applied are called operands.
a=5
b=2
print(a + b)
print(~a)
5. Delimiters: These are the symbols that used in Python to organize the structures,
statements, and expressions. Some of the Punctuators are: [ ] { } ( ) @ -
= += *= //= **== = , etc.
Python Data Types
Data types in Python are a way to classify data items. They represent the kind of value, which
determines what operations can be performed on that data. Since everything is an object in
Python programming, Python data types are classes and variables are instances (objects) of
these classes.
a=5
print(type(a))
b = 5.0
print(type(b))
c = 2 + 4j
print(type(c))
OUTPUT:
<class 'int'>
<class 'float'>
<class 'complex'>
Python Operators
In Python programming, Operators in general are used to perform operations on
values and variables.
• Operators: Special symbols like -, + , * , /, etc.
• Operands: Value on which the operator is applied.
Arithmetic Operators
Python Arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication and division.
• Addition (+): Used to add two operands.
• Subtraction (-): Used to subtract the right operand from the left operand.
• Multiplication (*): Used to multiply two operands.
• Division (/): Used to divide the left operand by the right operand.
• Modulus (%): Used to get the remainder of the division of the left operand by the
right operand.
• Exponentiation (**): Used to raise the left operand to the power of the right operand.
• Floor Division (//): Used to perform division where the result is the quotient in which
the digits after the decimal point are removed.
# Variables
a = 15
b=4
# Addition
print("Addition:", a + b)
# Subtraction
print("Subtraction:", a - b)
# Multiplication
print("Multiplication:", a * b)
# Division
print("Division:", a / b)
# Floor Division
print("Floor Division:", a // b)
# Modulus
print("Modulus:", a % b)
# Exponentiation
print("Exponentiation:", a ** b)
OUTPUT:
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625
Comparison Operators
In Python, Comparison (or Relational) operators compares values. It either returns True or
False according to the condition.
• Equality or Equal to operator(==): used to compare if the values of two operands
are equal.
• Inequality or Not Equal to operator (!=): used to compare if the values of two
operands are not equal.
• Greater than sign(>): used to check if the left operand is greater than the right
operand.
• Less than sign(<): used to check if the left operand is less than the right operand.
• Greater than or Equal to sign(>=): used to compare if the left operand is greater
than or equal to the right operand.
• Less than or Equal to sign(<=): used to compare if the left operand is less than or
equal to the right operand
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
OUTPUT:
False
True
False
True
False
True
Logical Operators
Python Logical operators perform Logical AND, Logical OR and Logical NOT operations.
It is used to combine conditional statements.
• AND operator: returns True if both statements are true.
• NOT operator: returns True if one of the statements is true.
• OR operator: reverses or negates the result.
a = True
b = False
print(a and b)
print(a or b)
print(not a)
OUTPUT:
False
True
False
Identity Operators
In Python, is and is not are the identity operators both are used to check if two values are
located on the same part of the memory. Two variables that are equal do not imply that they
are identical.
is True: if the operands are identical
is not True: if the operands are not identical
a = 10
b = 20
c=a
print(a is not b)
print(a is c)
OUTPUT:
True
True
Membership Operators
In Python, in and not in are the membership operators that are used to test whether a value or
variable is in a sequence.
in True: if value is found in the sequence
not in True: if value is not found in the sequence
name = 'Praise'
print('P' in 'Praise') #output is True
print('q' not in 'Praise') #output is True
Python Variables
In Python, variables are used to store data that can be referenced and manipulated during
program execution. A variable is essentially a name that is assigned to a value.
• Unlike Java and many other languages, Python variables do not require explicit
declaration of type.
• The type of the variable is inferred based on the value assigned.
x=5
name = "Samantha"
print(x)
print(name)
OUTPUT:
5
Samantha
Rules for Naming Variables
To use variables effectively, we must follow Python’s naming rules:
1. Variable names can only contain letters, digits and underscores (_).
2. A variable name cannot start with a digit.
3. Variable names are case-sensitive like myVar and myvar are different.
4. Avoid using Python keywords like if, else, for as variable names.
Assigning Values to Variables
Basic Assignment: Variables in Python are assigned values using the = operator.
x=5
y = 3.14
z = "Hi"
Multiple Assignments
Assigning Same Value: Python allows assigning the same value to multiple variables in
a single line, which can be useful for initializing variables with the same value.
a = b = c = 100
print(a, b, c)
Assigning Different Values:
We can assign different values to multiple variables simultaneously, making the code
concise and easier to read.
x, y, z = 1, 2.5, "Python"
print(x, y, z)
Type of Variable
In Python, we can determine the type of a variable using the type() function. This built-
in function returns the type of the object passed to it.
n = 42
f = 3.14
s = "Hello, World!"
li = [1, 2, 3]
d = {'key': 'value'}
b = True
print(type(n))
print(type(f))
print(type(s))
print(type(li))
print(type(d))
print(type(b))
OUTPUT:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'bool'>
Python Keywords
Keywords in Python are special reserved words that are part of the language itself. They
define the rules and structure of Python programs which means you cannot use them as names
for your variables, functions, classes or any other identifiers.
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
Best Practices for Using Keywords:
• Avoid using keywords as identifiers.
• Keep your code readable by understanding the appropriate use of each keyword.
• The important thins is staying updated with new keywords introduced in Python
versions.
Input and Output in Python
In programming, input/output (I/O) refers to the communication between a computer program
and the outside world. This can involve reading data from a user, file, or external device (input),
and sending data back to these entities (output).
In Python, input is any data that flows into your program:
• User input from the keyboard
• Data read from files
• Network requests
• Signals from hardware sensors
Output is any data that flows out of your program to the external world:
• Text printed to the screen
• Data written to files
• Network responses
• Signals sent to hardware
The print() function is used for output in various formats and the input() function enables
interaction with users.
Taking Input using input()
Python's input() function is used to take user input. By default, it returns the user input in
form of a string.
name = input("Enter your name: ")
print("Hello,", name )
OUTPUT:
Enter your name: Guido Van Rossum
Hello, Guido Van Rossum
Change the Type of Input in Python
Print Names in Python
The code prompts the user to input a string (the color of a rose), assigns it to the variable
color and then prints the inputted color.
color = input("What color is rose?: ")
print(color)
Print Numbers in Python
The code prompts the user to input an integer representing the number of roses, converts the
input to an integer using typecasting and then prints the integer value.
n = int(input("How many roses?: "))
print(n)
Print Float or Decimal Number in Python
The code prompts the user to input the price of each rose as a floating-point number, converts
the input to a float using typecasting and then prints the price.
price = float(input("Price of each rose?: "))
print(price)
Printing Output using print()
At its core, printing output in Python is straightforward, thanks to the print() function. This
function allows us to display text, variables and expressions on the console. Let's begin with
the basic usage of the print() function:
In this example, "Hello, World!" is a string literal enclosed within double quotes. When
executed, this statement will output the text to the console.
print('Python is powerful')
# Output: Python is powerful
print('Good Morning!')
print('It is rainy today')
OUTPUT:
Good Morning!
It is rainy today
Printing Variables
We can use the print() function to print single and multiple variables. We can print multiple
variables by separating them with commas. Example:
number = -10.6
name = "Programiz"
# print literals
print(5)
# print variables
print(number)
print(name)
OUTPUT:
5
-10.6
Programiz
Print Without a New Line
By default, the print() function ends with a new line.
If you want to print multiple words on the same line, you can use the end parameter:
# print with end whitespace
print('Good Morning!', end= ' ')
print('It is rainy today')
OUTPUT:
Good Morning! It is rainy today