0% found this document useful (0 votes)
23 views13 pages

Unit 1

This document provides an introduction to Python programming, covering its features, history, and applications. It explains the differences between compilers and interpreters, as well as scripting and programming languages. Additionally, it outlines the basic structure of a Python program, data types, and rules for creating identifiers and variables.

Uploaded by

sahalghanchi7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views13 pages

Unit 1

This document provides an introduction to Python programming, covering its features, history, and applications. It explains the differences between compilers and interpreters, as well as scripting and programming languages. Additionally, it outlines the basic structure of a Python program, data types, and rules for creating identifiers and variables.

Uploaded by

sahalghanchi7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Unit-1: Introduction and Syntax of Python Programming:

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

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.

PREPARED BY: B.P.PATEL


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

PREPARED BY: B.P.PATEL


CAD application

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:

Scripting Language Programming Language


A scripting language is a type of A programming language is a computer
programminglanguage designed for a runtime languagethat 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
aregenerally 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.

PREPARED BY: B.P.PATEL


Installing Python
There are many interpreters available freely to run Python scripts like IDLE (Integrated
DevelopmentEnvironment) 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.
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 withthe
.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.

PREPARED BY: B.P.PATEL


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

PREPARED BY: B.P.PATEL


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.
• 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 + "!")

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')

✓ '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.

Declaration and use of data types


Data types in Python specify the kind of value a variable can hold. Python is dynamically typed,
meaning you don't explicitly declare the data type of a variable; the interpreter infers it at runtime.

PREPARED BY: B.P.PATEL


Common Data Types:

• 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'>

o complex: Represents complex numbers (e.g., 2+3j)

c = 2 + 3j # Complex number
print(type(c)) # Output: <class 'complex'>

• Sequence:
o str: Represents a sequence of characters (e.g., "Hello", 'world')

name = "Alice" # String


print(type(name)) # Output: <class 'str'>

o list: An ordered, mutable collection of items (e.g., [1, 2, 3], ["apple", "banana"])

fruits = ["apple", "banana", "orange"] # List


print(type(fruits)) # Output: <class 'list'>

o tuple: An ordered, immutable collection of items (e.g., (1, 2, 3), ("apple", "banana"))

coordinates = (10, 20) # Tuple

PREPARED BY: B.P.PATEL


print(type(coordinates)) # Output: <class 'tuple'>

o dict: An unordered collection of key-value pairs (e.g., {"name": "Alice", "age": 30})

person = {"name": "Alice", "age": 30} # Dictionary


print(type(person)) # Output: <class 'dict'>

• Set:
o set: An unordered collection of unique items (e.g., {1, 2, 3}, {"apple", "banana"})

unique_numbers = {1, 2, 2, 3, 3} # Set (duplicates removed)


print(type(unique_numbers)) # Output: <class 'set'>

• Boolean:
o bool: Represents truth values (True or False)

is_valid = True # Boolean


print(type(is_valid)) # Output: <class 'bool'>

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

PREPARED BY: B.P.PATEL


There can be two types of Type Casting in Python –
✔ Implicit Type Casting
✔ Explicit Type Casting
Implicit Type Casting: In this, methods, Python converts data type into another data type
automatically. In this process, users don’t have to involve in this process
Example:
a=7
print(type(a))
b=3.0

print(type(b))

c = a + b #Python automatically converts c to float as it is a float addition print(c)


print(type(c))
Output:
<class 'int'>
<class 'float'> 10.0
<class 'float'>
Explicit Type Casting: In this method, Python need user involvement to convert the variable data
type into certain data type in order to the operation required.
Mainly in type casting can be done with these data type function:
● Int() : Int() function take float or string as an argument and return int type object.
● float() : float() function take int or string as an argument and return float type object.
● str() : str() function take float or int as an argument and return string type object.
a=5
n = float(a)
print(n)
print(type(n))
Output:
5.0
<class 'float'>

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: ")

print("Hello,", name)

Print Function (print())

PREPARED BY: B.P.PATEL


• 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

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:

PREPARED BY: B.P.PATEL


• Integers: Represent whole numbers.
o Examples: 10, -5, 0, 0b1010 (binary), 0o77 (octal), 0xFF (hexadecimal)
• Floating-point Numbers: Represent numbers with decimal points.
o Examples: 3.14, -2.5, 1.0e3 (scientific notation)
• Complex Numbers: Represent numbers with both real and imaginary parts.
o Example: 2+3j

2. String Literals:

• Single Quotes: Enclose strings within single quotes.


o Example: 'Hello, world!'
• Double Quotes: Enclose strings within double quotes.
o Example: "This is a string"
• Triple Quotes: Used for multi-line strings.
o Example:

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:

• True: Represents the truth value "true."


• False: Represents the truth value "false."

4. Special Literals:

• None: Represents the absence of a value.

Example:

age = 30 # Integer literal


price = 9.99 # Float literal
name = "Alice" # String literal
is_valid = True # Boolean literal

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.

1. Using All-Caps Naming Convention:

• This is the most common and recommended approach.


• By convention, variables named in all capital letters are treated as constants.
• This is a self-documenting way to indicate that the value of the variable should not be changed.

PREPARED BY: B.P.PATEL


PI = 3.14159
GRAVITY = 9.8

2. Using a Read-Only Property (for Classes):

• 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

PREPARED BY: B.P.PATEL


print("bhavika Patel")
print("1234567890")
print("[email protected]")
print("21-03-2005")

output:-

PREPARED BY: B.P.PATEL

You might also like