Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views27 pages

CH 1 of Optical Communication Engineering

This document provides an introduction to Python, highlighting its characteristics as a high-level programming language, including its readability, simplicity, and extensive standard library. It covers key concepts such as variables, operators, and data types, as well as the differences between interactive and script modes for executing Python code. The document concludes by emphasizing Python's versatility and suitability for various applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views27 pages

CH 1 of Optical Communication Engineering

This document provides an introduction to Python, highlighting its characteristics as a high-level programming language, including its readability, simplicity, and extensive standard library. It covers key concepts such as variables, operators, and data types, as well as the differences between interactive and script modes for executing Python code. The document concludes by emphasizing Python's versatility and suitability for various applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Unit No: 1

Introduction to Python

Mr. Suhas R. Desai


Content
• Introduction to Python: Why high level language, Scope of python,
interactive mode and script mode.
• Variables, Operators and Operands in Python.
• Arithmetic, relational and logical operators, Operator precedence,
• Taking input using raw_input() and input() method and displaying
output - print statement
• Comments in Python.
Why Python is a High Level
Language
• Python is categorized as a high-level programming language because
of several key characteristics and features that distinguish it from
lower-level languages ​such as assembly language or machine code.
• Low-level programming languages operate close to the hardware,
offering minimal abstraction and direct interaction with system
components like memory, CPU registers, and I/O devices. These
languages are essential for tasks requiring precise control, such as
operating system development, embedded systems, and device
drivers.
What Does High-Level Language
Mean?
• High-level languages ​are programming languages ​designed to be without problems understood and
written by way of people, absorbing the complexity of low-level gadget functions These languages ​
cognizance of, expressing algorithms and information toward herbal language compliance, making it less
complicated for programmers to achieve this is software program development.
• High-degree languages ​offer numerous great benefits over low-stage languages ​such as assembly or
machine code. First, they provide abstraction from hardware, permitting programmers to write down code
that is independent of precise processor architectures or operating systems. This portability allows software
programs written in high-stage languages ​to run throughout systems without modification, increasing
flexibility and reducing development time.
• Second, excessive degree languages ​emphasize studying and expressiveness in their syntax and shape.
They use familiar constructs and key phrases that resemble human language, making the code easier to
apprehend and maintain. This clarity now not most effective reduces the possibility of mistakes however
additionally increases collaboration among builders running at the same challenge.
What Makes Python a High-level
Programming Language?
• Abstract Machine Description
• Readable & Transparent Syntax
• Extensive Standard Library
• Automated Memory Management
• Platform Independence
Why Developers are Fond of
Python?
• Simplicity and Readability
• Versatility
• Vast Ecosystem of Libraries & Frameworks
• Community and Support
• Cross-Platform Compatibility
• Ease of Learning and Teaching
Conclusion

• In conclusion, Python is considered a High Level programming


language because it strips away low-level information, emphasizes
readability and simplicity, provides a nice standard library, uses
automatic memory management, and is not platform-independent
Those characteristics this makes Python ideal for many application
applications.
Interactive mode and Script
mode
• Interactive Mode:- It also known as REPL (Read-Eval-Print Loop), allows you to execute
Python commands one at a time and see the results immediately. This mode is particularly
useful for testing small code snippets, debugging, and learning Python.
• To start the interactive mode, you can open a terminal or command prompt and type python.
You will see the >>> prompt, indicating that the Python shell is ready to accept commands.
• Example
• >>>print("Hello, World!")
• Hello, World!
• >>>a = 5
• >>>b = 10
• >>>a + b
• 15
Advantages
• Immediate Feedback: You get instant results for each command executed.
• Ease of Use: Ideal for beginners to experiment with Python commands and syntax.
• Quick Testing: Useful for testing small code snippets and functions.

Disadvantages
• Not Suitable for Large Programs: Managing and editing large code blocks is
cumbersome.
• No Code Persistence: Once you close the session, the code is lost unless saved manually.
• Limited Editing Capabilities: Editing previously entered commands can be tedious
Script Mode
• Script Mode involves writing your Python code in a file with a .py extension and
then executing the entire file. This mode is more suitable for developing larger
applications and scripts that require multiple lines of code.
• To run a Python script, you can save your code in a file (e.g., script.py) and execute
it using the command python script.py in the terminal or command prompt.
• Example
• Create a file named script.py with the following content:
• print("Hello, World!")
• a=5
• b = 10
• print(a + b)
Advantages
• Code Persistence: The code is saved in a file and can be reused and modified
later.
• Suitable for Large Programs: Easier to manage and edit large code blocks.
• Better Editing Tools: You can use text editors or IDEs with advanced features for
writing and debugging code.

Disadvantages
• No Immediate Feedback: You need to run the entire script to see the results.
• Requires File Management: You need to create and manage files for your
scripts.
Key Differences & Conclusion
• Execution: Interactive mode executes code line by line, while script mode
executes the entire file at once.
• Use Case: Interactive mode is ideal for short, quick tests, whereas script
mode is better for larger, more complex programs.
• Editing: Script mode offers better editing capabilities and code persistence,
while interactive mode is limited in this regard.

In conclusion, both interactive and script modes have their own strengths and
are suited for different scenarios. Beginners may find interactive mode more
accessible, while experienced developers often prefer script mode for its
flexibility and efficiency in handling larger projects.
Variables, Operators and Operands in Python

1. Variables
• Definition: Variables are containers for storing data values. They act as labels
for data in memory.

• Example:
• Copy the code
x = 10 # 'x' is a variable storing the value 10
name = "Alice" # 'name' is a variable storing the string "Alice“

• Rules:
• Must start with a letter or an underscore (_).
• Cannot start with a number.
• Can only contain alphanumeric characters and underscores.
2. Operators
• Definition: Operators are symbols or keywords used to perform
operations on variables and values.
• Types of Operators:-
• A) Arithmetic Operators
• B) Relational operators / Comparison Operators
• C) Logical Operators
• D) Identity Operators
• E) Membership Operators
• F) Bitwise Operators
A) Arithmetic (+, -, *, /, %, //, **)
Symbol Operator Name and Operation E.g.
+ Addition 2+3= 5
- Subtraction 3-2 = 1
* Multiplication 2*3 = 6
/ Division 6/3 = 2
% mod operator (it gives remainder) 7%3 = 1
// floor division 10//3= 3
** exponential/ power of operator 2**3 = 8
= Assignment operator A=2
B=A
+= Addition Assignment (Adds and assigns the result) a= 5
a += 100 # a = a + 100 (ans- a= 105)
-= Subtraction Assignment Subtracts and assigns the result a= 500
a -= 100 # a = a - 100 (ans- a= 400)
*= Multiplication Assignment (Multiplies and assigns the result.) a= 3
a *= 5 # a = a * 5 (ans- a=15)
/= Division Assignment (Divides and assigns the result) a= 6
a/=2 # a = a / 2 (ans- a= 3)
%= Modulus Assignment (Takes modulus and assigns the result) a%=2

**= Exponentiation Assignment (Raises to power and assigns the result.) a**=2
Relational operators / Comparison Operators : ==, !=,
<, >, <=, >=
Symbol Operator name and operation E.g.
== Equal Checks if two values are equal. Example 3 == 5 o/p- False
!= Not Equal: Checks if two values are not equal. 3 != 5 o/p True
< Less Than: Checks if one value is less than another. 3<5 o/p True
> Greater Than: Checks if one value is greater than another. 3 > 5 o/p False

<= Less Than or Equal To: Checks if one value is less than or 3 <= 5 o/p True
equal to another.

>= Greater Than or Equal To: Checks if one value is greater 3 >= 5 o/p False
than or equal to another.
Logical Operators: and, or, not
Symbol Operator name and operation E.g.
& AND (and): Returns True if both statements are true. x < 5 and x < 10
x < 5 & x < 10

| OR (or): Returns True if one of the statements is true. x < 5 or x < 4


x<5|x<4

~ NOT (not): Reverses the result, returns False if the not (x < 5 and x < 10)
result is true. Example: ~ (x < 5 and x < 10)
Identity Operators: is, is not
Symbol Operator name and operation E.g.

is IS (is): Returns True if both variables are the x is y


same object. Example:

is not IS NOT (is not): Returns True if both x is not y


variables are not the same object.
Membership Operators: in, not
in
Symbol Operator name and operation E.g.

in IN (in): Returns True if a sequence with the specified x in y


value is present in the object.

not in NOT IN (not in): Returns True if a sequence with the x not in y
specified value is not present in the object.
Bitwise Operators: &, |, ^, ~, <<, >>
Symbol Operator name and operation E.g.

& AND (&): Sets each bit to 1 if both bits are 1. x&y

| OR (|): Sets each bit to 1 if one of two bits is 1. x|y

~ NOT (~): Inverts all the bits. ~x

^ XOR (^): Sets each bit to 1 if only one of two bits is 1. x^y

<< Zero Fill Left Shift (<<): Shifts left by pushing zeros in x << 2
from the right.

>> Signed Right Shift (>>): Shifts right by pushing copies of x >> 2
the leftmost bit in from the left.
raw_input() and input()
• In Python, you can use both raw_input() (Python 2) and input() (Python 3) to
take user input, and the print() function to display output. Here's a concise
explanation and example for both

Python 2: Using raw_input()


• raw_input() reads input as a string.
• Use print (without parentheses) to display output.

Python 3: Using input()


• input() reads input as a string.
• Use print() (with parentheses) to display output.
Displaying output - print
statement
1. Basic Output
print("Hello, World!")
Output:
Hello, World!
2. Printing Variables
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
Output:
Name: Alice Age: 25
3. Using f-strings for Formatting
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Output:
4. Printing with Separator and End Parameters
# Custom separator
print("Python", "is", "fun", sep="-")
# Custom end
print("This is the first line.", end=" ")
print("This is the second line.")
Output:
Python-is-fun
This is the first line. This is the second line.
5. Printing Multi-line Strings
print("""This is a
multi-line
string.""")
Output:
Copy the codeThis is a
multi-line
string.
Comments in Python in python
• 1. Single-line Comments :- Use the # symbol to start a single-line
comment
• 2. Multi-line Comments: - Python does not have a specific syntax for
multi-line comments. However, you can use triple quotes (''' or """) to
create multi-line strings that act as comments if they are not assigned
to a variable
Data Types
In Python, data types define the kind of value a variable can hold. Python is dynamically typed,
meaning you don’t need to declare the type explicitly. Here’s an overview of the main data types:
1. Numeric Types
• int: Integer values (e.g., 5, -10, 1000).
• float: Floating-point numbers (e.g., 3.14, -0.001).
• complex: Complex numbers with real and imaginary parts (e.g., 3+4j).
2. Sequence Types
• str: Strings, a sequence of characters (e.g., "Hello", 'Python').
• list: Ordered, mutable collection (e.g., [1, 2, 3], ['a', 'b', 'c']).
• tuple: Ordered, immutable collection (e.g., (1, 2, 3), ('x', 'y', 'z')).
3. Set Types
• set: Unordered collection of unique elements (e.g., {1, 2, 3}, {'a', 'b', 'c'}).
• frozenset: Immutable version of a set.
4. Mapping Type
• dict: Key-value pairs (e.g., {'name': 'Alice', 'age': 25}).
5. Boolean Type
• bool: Represents True or False.
6. Binary Types
• bytes: Immutable sequence of bytes (e.g., b'hello').
• bytearray: Mutable sequence of bytes.
• memoryview: Provides memory access to binary data without
copying.
7. None Type
• NoneType: Represents the absence of a value (e.g., None).

These data types allow Python to handle a wide variety of

You might also like