Py Unit1
Py Unit1
History of Python:
1.Creation: Developed by Guido van Rossum in the late 1980s; first released in
1991.
2. Name Origin: Named after the comedy series "Monty Python's Flying
Circus."
4.Python 3.0: Launched in 2008; a major update that improved consistency but
was not backward compatible with Python 2.
6. Current Status: Python continues to evolve, with ongoing updates; Python 3.x
is the standard version today.
Features of Python:
10. Integration Capabilities: Easily integrates with other languages and tools.
Literal:
2. No Built-in Type: Python does not enforce constants; they are regular
variables meant to remain unchanged.
Example:
PI = 3.14159
MAX_USERS = 50
Variables:
What is a Variable?
A variable is a named storage location in memory that holds a value. You can
change the value stored in a variable throughout your program.
1. Declaration: You create a variable by assigning a value using the equals sign
(`=`).
- Example: age = 25
4. Case Sensitivity: Variable names are case-sensitive. For example, `age` and
`Age` are different variables.
Identifier:
What is an Identifier?
- Naming Rules:
- Must start with a letter or underscore (`_`).
- Can include letters, numbers, and underscores.
- Cannot start with a number or contain spaces/special characters.
Example:
user_name = "Alice" # Valid
1st_number = 10 # Invalid (starts with a number)
Keywords:
- Definition: Reserved words that have special meaning in Python and cannot be
used as identifiers (variable names, function names, etc.).
- Characteristics:
- Keywords are case-sensitive (e.g., if is different from IF).
- Used to define the syntax and structure of the Python language.
- Common Keywords:
- Control Flow: if, else, elif, for, while
- Function Definition: def`, return
- Data Types: True, False,None
- Exception Handling: try, except, finally
- Class Definition: class
- Total Count: There are 35 keywords in Python 3.x (e.g., `import`, `in`, `is`,
`with`).
Example:
if condition:
print("Hello") # 'if' is a keyword
1. Numeric Types:
o int: Integer values (e.g., 42)
o float: Floating-point values (e.g., 3.14)
o complex: Complex numbers (e.g., 1 + 2j)
2. Sequence Types:
o str: String (e.g., "Hello")
o list: Ordered, mutable collection (e.g., [1, 2, 3])
o tuple: Ordered, immutable collection (e.g., (1, 2, 3))
3. Mapping Type:
o dict: Key-value pairs (e.g., {"name": "Alice", "age": 25})
4. Set Types:
o set: Unordered collection of unique items (e.g., {1, 2, 3})
o frozenset: Immutable version of a set (e.g., frozenset([1, 2, 3]))
5. Boolean Type:
o bool: Represents truth values (True or False)
6. None Type:
o NoneType: Represents the absence of a value (e.g., None)
Output Statements
print("Hello, World!")
print("The answer is:", 42)
2. Formatted Output: You can format strings using f-strings (Python 3.6+)
or the format() method.
o Example with f-strings:
name = "Alice"
age = 30
print(f"{name} is {age} years old.")
Input Statements
1. input() Function: Used to take user input from the console. Returns the
input as a string.
o Example:
2. Type Conversion: Since input() returns a string, you may need to convert
it to other data types.
o Example:
Comments:
- Multi-Line Comments: Use triple quotes (''' or """) for longer comments.
- Example:
"""
This is a multi-line comment.
"""
Indentation:
- Conventions: Use four spaces per indentation level (no tabs). Inconsistent
indentation can lead to errors.
Operators:
1. Arithmetic Operators
+ : Addition
- : Subtraction
* : Multiplication
/ : Division (returns float)
// : Floor Division (returns integer)
% : Modulus (remainder)
** : Exponentiation
2. Comparison Operators
== : Equal to
!= : Not equal to
< : Less than
> : Greater than
<= : Less than or equal to
>= : Greater than or equal to
3. Logical Operators
Combine Boolean expressions:
4. Assignment Operators
= : Simple assignment
+= : Add and assign
-= : Subtract and assign
*= : Multiply and assign
/= : Divide and assign
%= : Modulus and assign
5. Bitwise Operators
6. Identity Operators
7. Membership Operators
Expression:
What is an Expression?
Types of Expressions
Type Conversions:
x = 10 # int
y = 3.5 # float
result = x + y # x is converted to float
Python Arrays:
In Python, arrays are typically handled using the array module or NumPy, a
popular library for numerical computations. Here’s how to work with both:
1. Defining an Array:
- Import the array module and create an array.
- Example:
2. Processing Arrays:
- Example:
print(arr[0]) # Output: 1
arr.append(5)
arr.remove(2)
- extend(iterable): Adds elements from an iterable (like a list) to the end of the
array.
arr.extend([6, 7])
- index(value): Returns the index of the first occurrence of a value.
index_of_3 = arr.index(3)
arr.reverse()
arr.sort()
- Example:
import numpy as np