Introduction to Python
Python is a high-level, interpreted programming language created by Guido van Rossum in 1991. It is widely used by engineers because:
- - It has simple and easy-to-read syntax (like English)
- - It supports multiple programming styles (procedural, object-oriented, functional)
- - It has a huge collection of libraries for engineering applications (NumPy, SciPy, Pandas, Matplotlib)
- - It works on different platforms (Windows, Mac, Linux)
- - It is free and open-source
Python is used in many engineering fields like:
- Data analysis and visualization
- Machine learning and AI
- Scientific computing
- Automation and scripting
- Web development
Key Features:
- Dynamically typed (no need to declare variable types)
- Automatic memory management
- Large standard library
- Supports integration with other languages
Python Variables
Variables are containers for storing data values in Python. Unlike other languages, Python variables don't need explicit declaration.
Variable Rules:
- Must start with a letter or underscore
- Can only contain letters, numbers, and underscores
- Are case-sensitive (age, Age, and AGE are different)
- Cannot be Python keywords (like if, else, for)
Example:
x = 5
(integer variable)
y = 3.14
(float variable)
name = "John"
(string variable)
Variable Types:
- int: whole numbers (10, -5)
- float: decimal numbers (3.14, -0.001)
- str: text ("hello", 'engineer')
- bool: True or False
- list: ordered collection [1, 2, 3]
- tuple: ordered unchangeable collection (1, 2, 3)
- dict: key-value pairs {"name": "John", "age": 25}
Important Points:
- Variables are created when first assigned a value
- Type is automatically determined
- Can change type by assigning new value
- Multiple assignment is possible: a, b = 5, 10
Python Basic Operators
Operators are special symbols in Python that perform operations on variables and values.
a) Arithmetic Operators
- + Addition (5 + 3 gives 8)
- - Subtraction (5 - 3 gives 2)
- * Multiplication (5 * 3 gives 15)
- / Division (5 / 2 gives 2.5)
- % Modulus (remainder after division, 5 % 2 gives 1)
- ** Exponentiation (5 ** 2 gives 25)
- // Floor division (5 // 2 gives 2)
b) Comparison Operators
- == Equal (5 == 5 gives True)
- != Not equal (5 != 3 gives True)
- > Greater than (5 > 3 gives True)
- < Less than (5 < 3 gives False)
- >= Greater than or equal to
- <= Less than or equal to
c) Logical Operators
- and Returns True if both statements are true
- or Returns True if one of statements is true
- not Reverse the result (not True gives False)
d) Assignment Operators
- = Simple assignment (x = 5)
- += Add and assign (x += 3 same as x = x + 3)
- -= Subtract and assign
- *= Multiply and assign
- /= Divide and assign
Understanding Python Blocks
Blocks are sections of Python code that are grouped together.
a) What are Blocks?
- - Blocks are used to group statements in Python
- - They are created using indentation (spaces or tabs)
- - Commonly used in control structures (if, for, while, functions)
- - All statements in a block must have the same indentation level
b) Block Structure Example
if x > 5: print("x is greater than 5") # This is a block y = x * 2 # Also part of same block print(y) # Still in the block print("This is outside the block") # Outside because different indentation
c) Importance of Blocks
- - Determines the scope of variables and functions
- - Controls the flow of program execution
- - Makes code more readable and organized
- - Essential for defining function bodies and control structures
d) Block Rules
- - Blocks start with a colon (:) at the end of control statements
- - Standard indentation is 4 spaces (can be tabs but must be consistent)
- - All statements in block must align vertically
- - Empty blocks use 'pass' keyword
Python Data Types
Data types define what kind of value a variable can hold and what operations can be performed on it. Python has several built-in data types:
- Numeric Types: int, float, complex
- Sequence Types: str, list, tuple
- Mapping Type: dict
- Boolean Type: bool
- Set Types: set, frozenset
Numeric Data Types in Detail
a) Integer (int)
Integers are whole numbers (positive or negative) without decimals.
- Declaration:
x = 10
ory = -5
- Size: Unlimited length (limited by available memory)
- Base Systems:
- Decimal (base 10):
a = 50
- Binary (base 2):
b = 0b1101
(prefix with 0b) - Octal (base 8):
c = 0o17
(prefix with 0o) - Hexadecimal (base 16):
d = 0x1F
(prefix with 0x)
- Decimal (base 10):
- Operations: +, -, *, /, //, %, **
- Type Conversion:
int(3.14)
→ 3,int("10")
→ 10
b) Float (float)
Floats are real numbers with decimal points.
- Declaration:
x = 3.14
ory = -0.001
orz = 2e3
(2000.0) - Precision: Typically 15 decimal places
- Special Values:
float('inf')
- Positive infinityfloat('-inf')
- Negative infinityfloat('nan')
- Not a Number
- Operations: Same as int but with decimal results
- Type Conversion:
float(5)
→ 5.0,float("3.14")
→ 3.14
c) Complex (complex)
Complex numbers with real and imaginary parts.
- Declaration:
x = 3 + 4j
(where j is √-1) - Access Parts:
x.real
→ 3.0,x.imag
→ 4.0 - Operations: Support basic arithmetic operations
Working with Numeric Data Types
a) Type Checking
Use type()
function to check data type:
x = 5 print(type(x)) # Output: <class 'int'> y = 3.14 print(type(y)) # Output: <class 'float'>
b) Type Conversion
Convert between numeric types using constructor functions:
a = 5 # int b = float(a) # 5.0 (float) c = int(3.9) # 3 (truncates decimal) d = complex(2) # (2+0j)
c) Numeric Operations
- Division:
/
always returns float,//
returns integer - Power:
**
operator (2**3 → 8) - Modulo:
%
returns remainder (7%3 → 1)
d) Built-in Numeric Functions
abs()
: Absolute valueround()
: Round to nearest integerpow()
: Power function (alternative to **)min()
,max()
: Find smallest/largest valuesum()
: Sum of all items
Important Considerations
- - Python automatically converts int to float when mixed in operations
- - Division between integers returns float in Python 3 (unlike Python 2)
- - Floating-point arithmetic may have precision issues (0.1 + 0.2 ≠ 0.3 exactly)
- - For precise decimal arithmetic, use
decimal
module - - For advanced math, use
math
module (import math)
No comments:
Post a Comment