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

Unit 1

The document provides an introduction to the Python programming language. It discusses what Python is, why it is popular, its history and key features such as being general purpose, interpreted, dynamically typed, and having a large standard library. It also outlines some common applications of Python like web development, desktop applications, scientific computing, and more.

Uploaded by

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

Unit 1

The document provides an introduction to the Python programming language. It discusses what Python is, why it is popular, its history and key features such as being general purpose, interpreted, dynamically typed, and having a large standard library. It also outlines some common applications of Python like web development, desktop applications, scientific computing, and more.

Uploaded by

Bhavika Patel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Unit-1: Fundamentals of Python

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

Here are some key features of Python:

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

Why learn Python?

There are many reasons why Python is a popular choice:

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

Large Standard Library:

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

Object-Oriented Programming (OOP):

 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:

 Django and Pyramid framework(Use for heavy applications)


 Flask and Bottle (Micro-framework)

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.

3. Console-based Application: Console-based applications run from the command-line or shell.


These applications are computer program which are used commands to execute.Python can
develop this kind of application very effectively.

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.

6. Business Applications: E-commerce and ERP are an example of a business application.


This kind of application requires extensively, scalability and readability, and Python provides
all these features.

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.

8. 3D CAD Applications: The CAD (Computer-aided design) is used to design engineering


related architecture. It is used to develop the 3D representation of a part of a system. Python
can create a 3D CAD application

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

1. Easy to Learn and Read:

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

5. Object-Oriented Programming (OOP):

 Object-Oriented Paradigm: Python fully supports object-oriented programming (OOP) concepts


like classes, objects, inheritance, and polymorphism. This allows for modular code organization,
reusability, and efficient program design.

PREPARED BY: B.P.PATEL


 Structured Approach: OOP principles promote code reusability and maintainability, especially for
larger projects.

6. Extensive Standard Library:

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

7. Large and Active Community:

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

9. Embeddable and Extensible:

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

10. Focus on Developer Productivity:

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

Differences between Compiler and Interpreter


Compiler Interprete
r
The compiler scans the whole program in one Translates the program one statement at a
go. time.
As it scans the code in one go, the errors (if Considering it scans code one line at a time,
any) are shown at the end together. errors are shown line by line.
It converts the source code into object code. It does not convert source code into object
code
instead it scans it line by line
PREPARED BY: B.P.PATEL
It does not require source code for later It requires source code for later execution.
execution.
Execution of the program takes place only Execution of the program happens after every
after line is checked or evaluated.
the whole program is compiled.
C, C++, C#, etc are programming Python, Ruby, Perl, SNOBOL, MATLAB,
languages that are compiler-based. etc are programming languages that are
interpreter-
based.
Differences between Scripting Language and Programming Language:

Scripting Language Programming Language


A scripting language is a type of A programming language is a computer
programming language designed for a runtime language that is used to communicate with
system to computers using
automate the execution of tasks. a set of instructions.
It uses an interpreter to convert source code It uses a compiler to convert source code
into into
machine code. machine code.
It is interpreted language or interpreter- It is compiled language or compiler-
based based
language language
Examples include Perl, PHP,Python, Examples include C, C++, Java, Python, etc.
JavaScript,etc.
Execution of a script takes less time as scripts Execution of a program takes more time since
are generally short. they are compiled.
Do not create a .exe file. These generate .exe files.

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.

PREPARED BY: B.P.PATEL


Step 6: Add Python Path to Environment Variables (Optional)

There are two modes for using the Python interpreter:


 Interactive Mode
 Script Mode
Running Python in interactive mode:
 Without passing python script file to the interpreter, directly execute code to Python prompt.
 Once you’re inside the python interpreter, then you can start.
 >>> print("Ami
Patel") Output:
Ami Patel

Running Python in script mode:


 Alternatively, programmers can store Python script source code in a file
with the .py extension, and use the interpreter to execute the contents of
the file.
 To execute the script by the interpreter, you have to tell the interpreter the name of the file.

Basic Structure of Python program

Python Program Structure:

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)

PREPARED BY: B.P.PATEL


3. Variable Declarations (Optional): Variables are declared with a name and assigned a value. Python
is dynamically typed, so no type declaration is required. (PHP can have type declarations using
$variableName: type;)
4. Functions (Optional): Reusable blocks of code defined with the def keyword. (PHP uses function
keyword for functions)
5. Main Program Body: The core logic of the program written using statements and control flow
structures (if/else, for loops, etc.).

Conceptual Equivalents in PHP:

1. Comments: Use // for single-line comments and /* */ for multi-line comments.


2. Includes: Use require (fatal error if file not found) or include (warning if file not found) to include
external code from PHP files.
3. Variable Declarations: Declare variables with $ followed by the name. Type declarations are
optional (default to mixed).
4. Functions: Similar to Python, use function keyword to define functions.
5. Main Script: The PHP script itself acts as the main program body. Code within the script executes
sequentially.

Example (Python):

# This program prints a hello message

message = "Hello, World!"

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

Rules for creating identifiers:


o Must start with a letter (uppercase or lowercase) or an underscore (_).
o Can contain letters, numbers, and underscores after the first character.
o Case-sensitive (e.g., age and Age are different identifiers).
o Cannot be a keyword.

Choosing good identifiers:

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

PREPARED BY: B.P.PATEL


 Avoid using abbreviations or overly generic names unless their meaning is very clear within the
context.

Example:-
# Good identifiers
message = "Hello, world!"
def greet(name):
print("Hello, " + name + "!")

# Not ideal (less descriptive)


msg = "Hello, world!"
f(n):
print("Hello, " + n + "!")
Keywords
 Keywords are the identifiers which have a specific meaning in python, there are 33
keywords in python. These may vary from version to version

 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 and Variables

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:

# Assigning values to variables of different data types


message = "Hello, world!" # String
age = 30 # Integer
pi = 3.14159 # Float
is_active = True # Boolean
fruits = ["apple", "banana", "cherry"] # List

Type Casting

Using Casting Operators(Explicit):

PHP provides various casting operators that explicitly convert a variable to a specific data type:

 (int): Casts to integer


 (float): Casts to float
 (string): Casts to string
PREPARED BY: B.P.PATEL
 (bool): Casts to boolean (True or False)
 (array): Casts to array
 (object): Casts to object (less commonly used)
 (unset): Casts to NULL

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"

$bool_value = (bool) 0; // Casts 0 (integer) to boolean False

Implicit Type Juggling:

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)

Using Built-in Functions:

While less common, PHP offers a few functions for specific type conversions:

 intval(): Converts a value to an integer.


 floatval(): Converts a value to a float.
 strval(): Converts a value to a string.
 boolval(): Converts a value to a boolean.

These functions generally behave similarly to the casting operators but may provide additional functionalities
in certain cases.

Input-Output functions: input, print

Input Function (input())

 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:

name = input("Enter your name: ")

PREPARED BY: B.P.PATEL


print("Hello,", name)

Print Function (print())

 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:

message = "Hello, world!"

print(message) # Prints "Hello, world!" on a new line

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

PREPARED BY: B.P.PATEL


2. Comparison Operators(relational operator)

These operators compare values and return boolean results (True or False):

 ==: Equal to (e.g., 7 == 7 is True)


 !=: Not equal to (e.g., 10 != 20 is True)
 >: Greater than (e.g., 5 > 3 is True)
 <: Less than (e.g., 2 < 7 is True)
 >=: Greater than or equal to (e.g., 4 >= 4 is True)
 <=: Less than or equal to (e.g., 1 <= 5 is True)

PREPARED BY: B.P.PATEL


3. Assignment Operators:

These operators assign values to variables, and some can combine assignment with an operation:

 =: Simple assignment (e.g., age = 30)


 +=: Add and assign (e.g., count += 5) - Equivalent to count = count + 5
 -=: Subtract and assign (e.g., balance -= 100) - Equivalent to balance = balance - 100
 *=: Multiply and assign (e.g., total *= 2) - Equivalent to total = total * 2
 /=: Divide and assign (e.g., distance /= 3) - Equivalent to distance = distance / 3
 //=: Floor divide and assign (e.g., shares //= 2) - Equivalent to shares = shares // 2

4. Logical Operators:

These operators combine boolean expressions and control program flow:

 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:

These operators perform bit-level operations on integers (less common):

 &: Bitwise AND


 |: Bitwise OR
 ^: Bitwise XOR
 ~: Bitwise NOT
 <<: Left shift
 >>: Right shift

Bitwise and operator:


a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a & b = 1010

&
0100
= 0000
= 0 (Decimal)

Bitwise or operator: Returns 1 if either of the bit is 1 else 0.


Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
Bitwise not operator: Returns one’s complement of the number.
Example:
a = 10 = 1010 (Binary)

~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:

These operators check object identity (advanced):

 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:

1. Comparing simple data types (immutable):


x=5
y=5

# Check if they refer to the same object (may or may not be true)
print(x is y) # Possible output: True or False

# Safer way to compare values for immutables


print(x == y) # Output: True (always true if values are the same)
2.Comparing mutable data types (lists):
list1 = [1, 2, 3]
list2 = [1, 2, 3]

# Check if they refer to the same object in memory


print(list1 is list2) # Output: False (usually different objects)

# Check if they have the same value


print(list1 == list2) # Output: True (same values)
3.Modifying a list:
list1 = [1, 2, 3]
list2 = list1 # Here, list2 refers to the same object in memory as list1

# Modify list1
list1.append(4)

# Now, both list1 and list2 refer to the modified object


print(list1 is list2) # Output: True (points to the same modified object)

PREPARED BY: B.P.PATEL


PREPARED BY: B.P.PATEL

You might also like