Unit 1
Unit 1
_______________________________________________________________________________________
Teaching hours :07 Total marks :
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.
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 intelligenceor
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
kindof 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 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
9. Enterprise Applications: Python can be used to create applications that can be used
within anEnterprise 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
Differences between Compiler and Interpreter
Compiler Interpreter
The compiler scans the whole program in one Translates the program one statement at a time.
go.
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
It does not require source code for later It requires source code for later execution.
execution.
Execution of the program takes place only after Execution of the program happens after every
the whole program is compiled. line is checked or evaluated.
C, C++, C#, etc are programming languages Python, Ruby, Perl, SNOBOL, MATLAB, etc
that are compiler-based. are programming languages that are interpreter-
based.
Differences between Scripting Language and Programming Language:
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.
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)
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.).
Example (Python):
# This program prints a hello message
print(message)
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.
• 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 + "!")
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')
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.
• Numeric:
o int: Represents whole numbers (e.g., 10, -5, 0)
age = 30 # Integer
print(type(age)) # Output: <class 'int'>
o float: Represents numbers with decimal points (e.g., 3.14, -2.5, 0.0)
pi = 3.14159 # Float
print(type(pi)) # Output: <class 'float'>
c = 2 + 3j # Complex number
print(type(c)) # Output: <class 'complex'>
• Sequence:
o str: Represents a sequence of characters (e.g., "Hello", 'world')
o list: An ordered, mutable collection of items (e.g., [1, 2, 3], ["apple", "banana"])
o tuple: An ordered, immutable collection of items (e.g., (1, 2, 3), ("apple", "banana"))
o dict: An unordered collection of key-value pairs (e.g., {"name": "Alice", "age": 30})
• Set:
o set: An unordered collection of unique items (e.g., {1, 2, 3}, {"apple", "banana"})
• Boolean:
o bool: Represents truth values (True or False)
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
Type Casting is the method to convert the variable data type into a certain data type in order to the
operation required to be performed by users.
print(type(b))
• 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:
print("Hello,", name)
Example:
age = 30
print("My name is bhavika and I am", age, "years old.") # Prints with custom separation
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
Literals
Literals are the raw data that you directly use within your Python code. They represent fixed values.
Here are some common types of literals:
1. Numeric Literals:
2. String Literals:
docstring = """This is a
multi-line string."""
• Raw Strings: Prevent special characters like backslashes (\) from being interpreted.
o Example: r"C:\path\to\file"
3. Boolean Literals:
4. Special Literals:
Example:
Literals are fundamental building blocks of any Python program. They provide the basic data that you
use to create variables, perform calculations, and build more complex data structures.
Constants
In Python, we don't have a strict keyword like const to define constants as in some other languages
(like C++). Values that cannot be changed or updated during a program's normal execution. When a
constant is associated with an identifier, it's called a "named" constant.
• If you need to define constants within a class, you can use a property with a @property decorator and a
@<property name>.setter decorator that raises an exception.
class MyClass:
_constant_value = 42
@property
def constant_value(self):
return self._constant_value
@constant_value.setter
def constant_value(self, value):
raise AttributeError("Cannot modify constant value")
Examples:-
Using print & input function
Write a program to read your name, contact number, email, and birthdate and print those
details on the screen.
print("Enter your name: ", end="")
name=input()
print("Enter your birthdate (format: dd-mm-yyyy): ", end="")
birthdate=input()
print("Enter your contact number: ", end="")
contact=input()
print("Enter your email: ", end="")
email=input()
print("The details you entered: ")
print("Name: ", name)
print("Birthdate: ", birthdate)
print("Contact Number: ", contact)
print("Email: ", email)
output:-
Or
output:-