Python
Python
Algorithm
def find_maximum(numbers):
2. Flowchart
+-------------------+
| Start |
+-------------------+
+-------------------+
+-------------------+
+-------------------+
| Initialize max |
+-------------------+
v
+-------------------+
+-------------------+
+-------------------+
+-------------------+
/ \
Yes No
/ \
+-----------+ +-------------+
+-----------+ +-------------+
+-------------------+
+-------------------+
+-------------------+
| End |
Introduction to Python
Python is a high-level, interpreted programming language that is known for its readability, simplicity,
and versatility. It is widely used in many fields such as web development, data science, artificial
intelligence, automation, and more. Python was created by Guido van Rossum and first released in
1991.
Python uses clear syntax and is designed to be easy to learn and use. It emphasizes readability and
reduces the complexity of writing code compared to other programming languages.
In Python, data types define the kind of data a variable can hold, and they are essential for handling
and processing data in engineering applications. Here's a summary of key Python data types
commonly used in engineering:
1. Numerical Types:
o Integers (int): Whole numbers (e.g., 5, -3), used for discrete quantities like counts or
iteration steps.
o Floats (float): Real numbers with decimals (e.g., 3.14, 0.007), used for continuous
data like measurements or simulation results.
o Complex Numbers (complex): Numbers with real and imaginary parts (e.g., 3 + 4j),
useful in electrical engineering and signal processing.
2. Textual Type:
o Strings (str): Sequences of characters (e.g., "sensor reading"), used for labels,
descriptions, or file paths.
3. Boolean Type:
o Booleans (bool): Represents True or False, often used for logical operations or
decision-making in engineering processes.
4. Sequence Types:
o Lists (list): Ordered, mutable collections (e.g., [1, 2, 3]), used for time series data or
sensor readings.
o Tuples (tuple): Ordered, immutable collections (e.g., (1, 2.5, 3)), used for fixed sets
of data (e.g., coordinates).
o Sets (set): Unordered collections of unique items (e.g., {1, 2, 3}), useful for managing
distinct components.
o Dictionaries (dict): Key-value pairs (e.g., {"voltage": 3.5}), ideal for mapping
parameters like sensor data or configurations.
6. Advanced Types:
7. None Type:
These data types are foundational for managing numerical, textual, and complex data structures in
engineering, aiding in tasks like data analysis, simulations, signal processing, and control systems.
In Python, random numbers and real numbers are frequently used in engineering applications for
simulations, statistical modeling, and data analysis. Here's an explanation of each:
Python provides the random module to generate random numbers. You can generate random
numbers in different forms:
import random
print(rand_int)
print(rand_float)
print(rand_choice)
print(rand_sample)
Real numbers refer to numbers that can have a fractional part. In Python, real numbers are
represented using the float data type, which is a subset of floating-point numbers.
In Python, immutable variables are variables that cannot be changed after they are created. This
means that once an immutable object is assigned a value, its state cannot be altered. This is
particularly important in programming as it provides safety, helps optimize performance, and ensures
that certain objects remain constant throughout the execution of a program.
1. Strings (str):
o Strings in Python are immutable. Once a string is created, its contents cannot be
modified.
o Example:
o text = "Hello"
o text[0] = "h" # This will raise an error: TypeError: 'str' object does not support item
assignment
2. Tuples (tuple):
o Tuples are immutable sequences, meaning that the elements inside a tuple cannot
be changed once the tuple is created.
o Example:
o t = (1, 2, 3)
o t[0] = 10 # This will raise an error: TypeError: 'tuple' object does not support item
assignment
o Example:
o fs = frozenset([1, 2, 3])
o fs.add(4) # This will raise an error: AttributeError: 'frozenset' object has no attribute
'add'
4. Integers (int):
o Integers are immutable in Python. When you "change" the value of an integer, you
are actually creating a new integer object.
o Example:
o x=5
o x += 1 # Creates a new integer object with value 6, original 'x' remains unchanged
5. Floats (float):
o Like integers, floats are also immutable. Any operation that seems to modify a float
will actually create a new object.
o Example:
o y = 3.14
o Example:
o z = 2 + 3j
o z = z + (1 - 2j) # This creates a new complex number object, the original 'z' is not
modified
Conclusion
Immutable variables are those whose state cannot be changed after creation. Common
immutable types in Python include strings, tuples, integers, floats, complex numbers, and
frozensets.
When working with immutable types, any operation that "modifies" the object will actually
create a new object, leaving the original object unchanged.
In Python, input and output operations are essential for interacting with users or external systems.
The Python console provides a straightforward way to accept input from the user and display output
on the screen. Below is an overview of how to handle input and output in Python using the console.
1. Input in Python
To get input from the user, Python provides the built-in input() function. The input() function allows
the program to pause and wait for the user to type something in the console, then return the
entered data as a string.
Syntax:
input(prompt)
prompt (optional): A string that is displayed to the user as a prompt. It’s not mandatory, but
it's helpful for guiding the user on what to input.
Example:
name = input("Enter your name: ") # The user is prompted to enter their name
When this code is run, the program will wait for the user to input their name. After entering it and
pressing Enter, it will print a greeting message.
2. Output in Python
To output data to the console, Python uses the print() function. The print() function is flexible and
can handle multiple types of data, such as strings, integers, lists, and more.
Syntax:
file: The file where the output will be written (default is the console).
Basic Examples:
Simple output:
name = "Alice"
age = 25
Formatted output (String formatting): You can format output using f-strings (formatted string
literals), which were introduced in Python 3.6. This makes it easier to embed variables inside
strings.
name = "Bob"
age = 30
Summary
Input: The input() function is used to get user input from the console. It always returns a
string, but can be converted to other types using functions like int() or float().
Output: The print() function is used to output data to the console. It supports multiple items,
custom separators, and end characters, as well as string formatting.
Formatted Output: Python supports f-strings (formatted string literals) for easy inline
formatting of strings.
Error Handling: When expecting specific types of input (e.g., integers or floats), it is
important to handle errors using try-except blocks to avoid crashes.
By understanding and using input/output in Python effectively, you can build interactive programs
and handle user data smoothly.
In Python, arithmetic operators are used to perform mathematical operations on numbers (integers
or floats). These operators are fundamental in creating expressions—combinations of operators and
operands (values or variables).
1. Arithmetic Operators:
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
x = 10
y=3
# Addition
result_add = x + y # 10 + 3 = 13
# Subtraction
result_sub = x - y # 10 - 3 = 7
# Multiplication
result_mul = x * y # 10 * 3 = 30
result_div = x / y # 10 / 3 = 3.333333...
# Floor Division
# Modulus (remainder)
# Exponentiation
result_exp = x ** y # 10 ** 3 = 1000
Operator Precedence:
In Python, operator precedence determines the order in which operators are evaluated in an
expression. Higher-precedence operators are evaluated before lower-precedence operators. For
example, multiplication and division have higher precedence than addition and subtraction.
For example:
To ensure the desired order of operations, you can use parentheses to change the precedence:
print(result) # Output: 16
In Python, conditional statements are used to execute certain blocks of code based on whether a
condition is true or false. The primary conditional statements are:
if
elif (optional)
else (optional)
1. if Statement:
The if statement evaluates a condition, and if the condition is True, it runs a block of code.
age = 20
Output: "You are an adult." because the condition age >= 18 is True.
2. else Statement:
The else statement provides a block of code that is executed when the condition in the if statement
is False.
age = 16
else:
Output: "You are a minor." because the condition age >= 18 is False.
The elif statement allows you to check multiple conditions. If the if condition is False, it evaluates
each elif condition in order. If one of them is True, the corresponding block of code will be executed.
age = 65
else:
Output: "You are a senior citizen." because age = 65, which satisfies the last else condition.
Comparison Operators:
In conditional statements, you often use comparison operators to compare values. These operators
return a True or False result.
== Equal to 5 == 5 True
a = 10
b=5
if a > b:
else:
Logical Operators:
and Returns True if both conditions are True True and False False
age = 25
citizen = True
else:
Conditions: Allow your program to make decisions with if, elif, and else.
Comparison Operators: Used for comparing values (==, !=, >, <, >=, <=).
1. is Operator
The is operator is used to check whether two variables point to the same object in memory. It's used
to test object identity, not equality. This is different from the == operator, which compares the values
of objects.
Syntax: a is b
Returns: True if both variables a and b reference the same object in memory, False
otherwise.
Example:
a = [1, 2, 3]
print(a is b) # True, because both 'a' and 'b' point to the same list object in memory
b = [1, 2, 3]
print(a is b) # False, because 'a' and 'b' now refer to different objects (even though their contents are
the same)
2. in Operator
The in operator is used to check whether a value exists within an iterable (e.g., a list, string, tuple, or
set). It tests for membership.
Example:
# List example
numbers = [1, 2, 3, 4]
Key Differences:
is checks if two variables refer to the same object in memory (object identity).
When to Use:
Use is when you want to check if two references point to the exact same object (useful for
comparing singletons like None).
Use in when you need to check if an item exists within a collection (list, string, etc.).
Control statements in Python are used to control the flow of execution of a program based on certain
conditions or repeat actions multiple times. These include if-else statements, nested if-else
statements, and loops (like for and while).
1. if-else Statement
The if-else statement is used to execute a block of code if a condition is True, and optionally execute
a different block of code if the condition is False.
Syntax:
if condition:
else:
Example:
x = 10
if x > 5:
else:
Output:
x is greater than 5
2. elif (Else-If) Statement
You can chain multiple conditions using elif (short for "else if"). It allows you to check for several
conditions, one after the other.
Syntax:
if condition1:
elif condition2:
else:
Example:
x = 15
if x < 10:
elif x == 15:
else:
Output:
x is exactly 15
You can place an if-else block inside another if-else block. This is useful when you need to check
multiple conditions in a hierarchical or dependent way.
Syntax:
if condition1:
if condition2:
else:
else:
# Execute block 3 if condition1 is False
Example:
x = 20
y = 10
if x > 15:
if y < 15:
else:
else:
print("x is 15 or less")
Output:
4. Loops in Python
Loops are used to execute a block of code multiple times. Python provides two types of loops: the for
loop and the while loop.
The for loop is used to iterate over a sequence (like a list, string, or range) and execute a block of
code for each item in the sequence.
Syntax:
Example:
numbers = [1, 2, 3, 4, 5]
print(num)
Output:
1
2
for i in range(5):
print(i)
Output:
The while loop executes a block of code as long as the specified condition remains True.
Syntax:
while condition:
Example:
x=1
while x <= 5:
print(x)
x += 1 # Increment x
Output:
4
5
Example with an infinite loop (useful in certain cases like user input):
while True:
if user_input == "exit":
print("Exiting...")
break: Exits the current loop and moves to the next statement after the loop.
continue: Skips the current iteration and moves to the next iteration of the loop.
Example of break:
for i in range(10):
if i == 5:
print(i)
Output:
Example of continue:
for i in range(10):
if i % 2 == 0:
print(i)
Output:
5
7
Key Points:
if-else: Used for decision making. Executes different blocks based on conditions.
break and continue: Control the flow within loops, allowing you to exit or skip iterations.
These control structures help you create logic and flow in your programs, making them more
dynamic and flexible.