Unit 1
Unit 1
__________________________________________________________________________
Teaching hours :07 Total marks :10
Lecturer Name : B.P.Patel
_______________________________________________________________________________________
Introduction to Python
What is Python?
Python is a versatile, high-level programming language known for its readability and ease of use. Compared
to other languages, it often requires fewer lines of code to achieve the same results. This focus on simplicity
makes it ideal for beginners or rapid prototyping.
General-purpose: Python can be used for various tasks, including web development, data analysis,
automation, and scientific computing.
Interpreted: Python code is executed line by line, making it easy to test and debug your programs.
Dynamically typed: You don't need to declare variable types beforehand, offering more flexibility.
Large standard library: Python comes with a rich library of pre-written code for common tasks,
saving you time and effort.
Easy to learn: Python's syntax is clear and concise, making it easier to pick up compared to some
other languages.
Versatile: Python's wide range of applications makes it a valuable skill for many fields.
Large and supportive community: With a vast online community and numerous resources
available, you'll find plenty of help when needed.
1. History of Python
It was initially designed by Guido van Rossum in 1991 and developed by Python
Software Foundation.
There are two major Python versions- Python 2 and Python 3.
On 16 October 2000, Python 2.0 was released with many new features.
On 3rd December 2008, Python 3.0 was released with more testing and includes new features.
2. Python Features.
General-Purpose:
Python isn't limited to a specific domain. You can use it for web development (frameworks like
Django), data science (libraries like NumPy, Pandas), automation (libraries like Selenium), and even
scientific computing.
Interpreted Language:
Unlike compiled languages (C++, Java), Python code doesn't need compilation into machine code
before running. Instead, it's translated line by line during execution, making development faster and
debugging easier.
PREPARED BY: B.P.PATEL
Dynamically Typed:
You don't need to explicitly declare variable types (like int or string) beforehand. Python infers the
type based on the assigned value, offering more flexibility during development.
Python comes with a rich collection of built-in modules and functions for common tasks, saving you
time and effort. Examples include file handling, networking, and working with regular expressions.
Python supports object-oriented concepts like classes, objects, inheritance, and polymorphism. This
allows you to structure your code in a modular and reusable way.
Readability:
Python's syntax is known for its clarity, resembling natural language. It emphasizes indentation for
code blocks, making it easier to read and maintain compared to languages relying on curly braces or
semicolons.
Python Applications
1 .Web Applications: We can use Python to develop web applications. It provides libraries to
handle internet protocols such as HTML and XML, JSON, Email processing, request, etc. One
of Python web-framework named Django is used on Instagram. Python provides many useful
frameworks, and these are given below:
2.Desktop GUI Applications:The GUI stands for the Graphical User Interface, which provides
a smooth interaction to any application. Python provides a Tk GUI library to develop a user
interface.
4. Software Development: Python is useful for the software development process. It works as a
support language and can be used to build control and management, testing, etc.
5. Scientific and Numeric: Python language is the most suitable language for Artificial
intelligence or machine learning. It consists of many scientific and mathematical libraries,
which makes easy to solve complex calculations.
7. Audio or Video-based Applications : Python is flexible to perform multiple tasks and can
be used to create multimedia applications. Some multimedia applications which are made by
PREPARED BY: B.P.PATEL
using Python are TimPlayer, cplay, etc.
9. Enterprise Applications: Python can be used to create applications that can be used
within an Enterprise or an Organization. Some real-time applications are OpenERP, Tryton,
Picalo, etc.
10.Image Processing Application: Python contains many libraries that are used to work with
the image. The image can be manipulated according to our requirements. Examples of image
processing libraries are: OpenCV, Pillow
Python Features
Simple Syntax: Python's syntax is known for its readability, resembling plain English in many ways.
This makes it easier to learn and write code, even for those new to programming.
Focus on Clarity: Python emphasizes code readability with features like indentation (defining code
blocks) and meaningful variable names, reducing the cognitive load for developers.
2. Interpreted Language:
No Explicit Compilation: Unlike compiled languages (C++, Java), Python code doesn't need a
separate compilation step before execution. The interpreter reads and executes the code line by line,
making development faster and more iterative.
Immediate Feedback: Errors are identified during execution, allowing for quicker debugging and
adjustments to the code.
3. Dynamically Typed:
No Strict Type Declarations: Unlike statically typed languages, you don't need to explicitly declare
the data type of a variable in Python. The interpreter infers the type based on the assigned value,
offering more flexibility during development.
Flexibility: This dynamic nature allows you to write code without worrying about upfront type
declarations, but it can introduce potential runtime errors if type mismatches occur.
4. High-Level Language:
Abstraction: Python provides a higher level of abstraction compared to low-level languages. You
don't need to manage memory allocation or deal with low-level machine details, making development
more focused on problem-solving.
Focus on Logic: This abstraction allows developers to concentrate on the core logic of their program
rather than getting bogged down in intricate machine-specific details.
Rich Set of Modules: Python boasts a vast standard library that includes modules for various
functionalities like file I/O, networking, web development (with frameworks like Django and Flask),
scientific computing (NumPy, SciPy, Matplotlib), and more. This reduces the need to write code from
scratch for common tasks.
Pre-built Functionalities: The extensive standard library offers a treasure trove of pre-written
functions and modules, saving developers time and effort.
Supportive Community: Python has a large and active community of developers worldwide. This
translates to ample resources, tutorials, and forums for learning and troubleshooting, making it easier
to find help and support.
Continuous Development: With an active development team and a thriving community, Python is
constantly evolving with new features and improvements.
8. Cross-Platform Compatibility:
Runs on Multiple Systems: Python code can be executed on various operating systems (Windows,
macOS, Linux) without major modifications. This portability makes it a versatile language for
different development environments.
Write Once, Run Anywhere: Once you write Python code, it can potentially run on different
platforms without extensive rewriting, simplifying development for multi-platform applications.
Integration with Other Languages: Python can be embedded within C or C++ applications,
allowing you to leverage Python's scripting capabilities within larger systems.
Extending Functionality: C or C++ libraries can be integrated into Python to access functionalities
not readily available in pure Python.
Readability and Maintainability: Python's design choices prioritize code readability and
maintainability, making it easier for developers to work on projects collaboratively and reduce long-
term maintenance costs.
Rapid Prototyping: The ease of use and flexibility make Python ideal for rapid prototyping,
allowing developers to quickly test and refine ideas before diving into complex development cycles.
All the scripting languages are All the programming languages are not
programming languages. scripting languages.
There is less maintenance cost. There is the high maintenance cost.
Installing Python
There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software from
http://python.org/downloads/
Steps to be followed and remembered:
Step 1: Select Version of Python to
Install. Step 2: Download Python
Executable Installer. Step 3: Run
Executable Installer.
Step 4: Verify Python Was Installed On
Windows. Step 5: Verify Pip Was Installed.
1. Comments (Optional): Lines starting with # are ignored by the interpreter and used for explaining
the code. (PHP also uses // and /* */ for comments)
2. Imports (Optional): Lines using import statements bring in functionalities from external modules.
(PHP uses require or include statements for similar functionality)
Example (Python):
print(message)
Keywords and Identifiers
Identifiers
Identifier is a name given to various programming elements such as a variable,
function, class,module or any other object.
Following are the rules to create an identifier.
1. The allowed characters are a-z, A-Z, 0-9 and underscore (_)
2. It should begin with an alphabet or underscore
3. It should not be a keyword
4. It is case sensitive
5. No blank spaces are allowed.
6. It can be of any size
Valid identifiers examples : si, rate_of_interest, student1, ageStudent
Invalid identifier examples : rate of interest, 1student, @age
Descriptive: Identifiers should clearly reflect the purpose of the variable, function, class, etc., they
represent.
Meaningful: Using names that make sense improves code readability and maintainability.
Example:-
# Good identifiers
message = "Hello, world!"
def greet(name):
print("Hello, " + name + "!")
Predefined words: Keywords hold special meanings within the Python language itself. They
cannot be used for any other purpose like variable names or function names.
Fixed set: The set of keywords is predefined and cannot be changed by the programmer. There
are about 35 keywords in Python 3 (excluding False, True, and None).
Examples: def, if, else, for, while, class, return
Data types define the kind of data a variable can hold and the operations that can be performed on that data.
Python has various built-in data types to represent different types of information:
1. Numeric Types:
o Integers (int): Represent whole numbers (positive, negative, or zero). (e.g., 42, -100, 0)
o Floats (float): Represent decimal numbers. (e.g., 3.14, -9.25, 1.0)
o Complex Numbers (complex): Represent numbers with a real and imaginary part (a + bi).
(e.g., 3+5j, 1.2-4.7j)
2. Boolean Type (bool): Represents logical values - True or False.
3. String Type (str): Represents sequences of characters enclosed in single or double quotes. (e.g.,
"Hello, world!", 'This is a string')
PREPARED BY: B.P.PATEL
'hello' is the same as "hello".
Strings can be output to screen using the print function.
4. Sequence Types:
o Lists (list): Ordered, mutable collections of items enclosed in square brackets []. Elements can
be of different data types. (e.g., [1, 2.5, "apple", True])
o Tuples (tuple): Ordered, immutable collections of items enclosed in parentheses (). Elements
can be of different data types. (e.g., (1, "Monday", 3.14))
5. Set Type (set): Unordered collections of unique elements enclosed in curly braces {}. (e.g., {1, 2,
"apple"})
6. Dictionary Type (dict): Unordered collections of key-value pairs enclosed in curly braces {}. Keys
must be unique and immutable (often strings), while values can be of any data type. (e.g., {"name":
"Alice", "age": 30, "city": "New York"})
7. None Type: Represents the absence of a value.
Variable
Variables are names that refer to memory locations where data is stored. You can assign values of
specific data types to variables using the assignment operator (=).
Creating Variables:
Variable names must start with a letter or underscore (_).
Can contain letters, numbers, and underscores after the first character.
Case-sensitive (e.g., age and Age are different variables).
Every variable has a name and memory location where it is stored.
It Can be of any size
Variable name Has allowed characters, which are a-z, A-Z, 0-9 and underscore (_)
Variable name should begin with an alphabet or underscore
Variable name should not be a keyword
Variable name should be meaningful and short
Generally, they are written in lower case letters
A type or datatype which specify the nature of variable (what type of values can be stored in
We can check the type of the variable by using type command
>>> type(variable_name)
Example:
Type Casting
PHP provides various casting operators that explicitly convert a variable to a specific data type:
Example:
$num = "123";
$int_num = (int) $num; // Converts string "123" to integer 123
$decimal = 3.14;
$string_decimal = (string) $decimal; // Converts float 3.14 to string "3.14"
PHP can also perform implicit type juggling in certain contexts. This means it automatically attempts to
convert a variable's type to another type when needed during an operation. However, implicit type juggling
can sometimes lead to unexpected results, so it's generally recommended to use explicit casting for clarity
and control.
Example:
$num_string = "10";
$sum = $num_string + 5; // Implicitly converts "10" to integer 10, then performs addition (sum = 15)
While less common, PHP offers a few functions for specific type conversions:
These functions generally behave similarly to the casting operators but may provide additional functionalities
in certain cases.
Takes user input: The input() function pauses your program's execution and waits for the user to
enter some data from the keyboard.
Returns a string: Whatever the user types in is captured as a string, even if the user enters a number.
Optional prompt: You can provide a message inside the parentheses of input() to display a prompt to
the user, guiding them on what kind of input to provide.
Example:
Outputs data: The print() function displays the provided values on the console or output screen.
Can print multiple arguments: You can pass multiple arguments (separated by commas) to print()
to display them in a single line, optionally separated by spaces or custom delimiters.
Newline by default: By default, print() inserts a newline character (\n) at the end, moving the cursor
to the next line after printing. You can suppress this newline with the end argument (e.g.,
print("Hello", end=" ")).
Example:
age = 30
print("My name is bhavika and I am", age, "years old.") # Prints with custom separation
Operators
Operators are the workhorses of any programming language, and Python offers a robust set of operators to
perform various calculations, comparisons, and manipulations on data. Here's a breakdown of some common
Python operators:
1. Arithmetic Operators:
These operators perform basic mathematical computations on numeric operands (integers, floats):
+: Addition (e.g., 5 + 3 = 8)
-: Subtraction (e.g., 10 - 2 = 8)
*: Multiplication (e.g., 4 * 5 = 20)
/: Division (e.g., 12 / 3 = 4.0) - Returns a float for floating-point division. For integer division, use //
//: Floor division (e.g., 10 // 3 = 3) - Quotient obtained by discarding the remainder (integer result)
%: Modulo (remainder) (e.g., 14 % 3 = 2) - Remainder after division
These operators compare values and return boolean results (True or False):
These operators assign values to variables, and some can combine assignment with an operation:
4. Logical Operators:
and: Returns True if both operands are True (e.g., x > 0 and y < 10)
PREPARED BY: B.P.PATEL
or: Returns True if at least one operand is True (e.g., is_logged_in or is_admin)
not: Inverts the truth value of an operand (e.g., not (age < 18))
5. Bitwise Operators:
&
0100
= 0000
= 0 (Decimal)
~a = ~1010
= -(1010 + 1)
= -(1011)
= -11 (Decimal)
Bitwise xor operator: Returns 1 if one of the bits is 1 and the other is 0 else returns false.
PREPARED BY: B.P.PATEL
Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a ^ b = 1010
^
0
1
0
0
= 1110
= 14 (Decimal)
Bitwise left shift: Shifts the bits of the number to the left and fills 0 on right as a result. Example:
Example
a = 5 = 0000 0101 (Binary)
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20
Bitwise right shift: Shifts the bits of the number to the right and fills 0 on left( fills 1 in the case of a
negative number) as a result.
Example:
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5
6. Membership Operators:
These operators check if a value is present within a sequence (list, tuple, string):
in: Returns True if the value is found in the sequence (e.g., "apple" in fruits)
not in: Returns True if the value is not found in the sequence (e.g., "banana" not in fruits)
Example:1
x = ["apple",
"orange"]
print("apple" in x)
PREPARED BY: B.P.PATEL
output:
true
Example:2
x = ["apple",
"orange"]
print("pineapple" not
in x)
output:
true
7. Identity Operators:
is: Returns True if two variables refer to the same object in memory
is not: Returns True if two variables do not refer to the same object
Examples:
# Check if they refer to the same object (may or may not be true)
print(x is y) # Possible output: True or False
# Modify list1
list1.append(4)