Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python

The document provides an overview of algorithms and flowcharts, emphasizing their importance in programming and problem-solving. It introduces Python as a high-level programming language, detailing its data types, input/output operations, arithmetic operators, and conditional statements. Additionally, it covers concepts like immutability in Python and the use of random numbers for simulations.

Uploaded by

akshayorbgkapapa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python

The document provides an overview of algorithms and flowcharts, emphasizing their importance in programming and problem-solving. It introduces Python as a high-level programming language, detailing its data types, input/output operations, arithmetic operators, and conditional statements. Additionally, it covers concepts like immutability in Python and the use of random numbers for simulations.

Uploaded by

akshayorbgkapapa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

1.

Algorithm

An algorithm is a step-by-step procedure or formula for solving a problem. It defines a clear


sequence of operations that need to be carried out in a specific order to achieve the desired result.
Algorithms are fundamental in programming and computer science because they provide a
structured way to solve problems efficiently.

Example in Python (Implementation of the Algorithm)

def find_maximum(numbers):

max_num = numbers[0] # Step 3: Initialize the maximum

for num in numbers: # Step 4: Loop through the list

if num > max_num:

max_num = num # Update the maximum

return max_num # Step 5: Return the maximum

2. Flowchart

A flowchart is a graphical representation of an algorithm or a process. It uses various shapes and


symbols to show the steps in the process and the flow of control from one step to the next.
Flowcharts are very helpful in planning and designing algorithms because they provide a visual way
to represent logic.

Visual Flowchart Representation

+-------------------+

| Start |

+-------------------+

+-------------------+

| Input the list |

+-------------------+

+-------------------+

| Initialize max |

+-------------------+

v
+-------------------+

| Loop through list |

+-------------------+

+-------------------+

| Is num > max? |

+-------------------+

/ \

Yes No

/ \

+-----------+ +-------------+

| Update max | | Continue |

+-----------+ +-------------+

+-------------------+

| Output the max |

+-------------------+

+-------------------+

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

5. Set and Dictionary Types:

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:

o Arrays (numpy.ndarray): Efficient arrays for numerical data, widely used in


simulations or scientific calculations.

o DataFrames (pandas.DataFrame): Table-like structures for managing and analyzing


structured data, such as sensor logs or experimental results.

7. None Type:

o None: Represents a null or missing value, used to indicate uninitialized data or


placeholders.

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:

1. Random Numbers in Python


Random numbers are numbers generated in a way that the next number is not predictable. They are
essential for tasks like Monte Carlo simulations, random sampling, and testing.

Generating Random Numbers:

Python provides the random module to generate random numbers. You can generate random
numbers in different forms:

 Random Integer (randint):

o Generates a random integer within a specified range.

 import random

 rand_int = random.randint(1, 10) # Generates a random integer between 1 and 10

 print(rand_int)

 Random Float (uniform):

o Generates a random float (real number) within a specified range.

 rand_float = random.uniform(0, 1) # Generates a random float between 0 and 1

 print(rand_float)

 Random Choice from a List (choice):

o Selects a random item from a list or sequence.

 rand_choice = random.choice([10, 20, 30, 40])

 print(rand_choice)

 Random Sample (sample):

o Selects a random sample of unique elements from a population.

 rand_sample = random.sample([1, 2, 3, 4, 5], 3) # Selects 3 random elements

 print(rand_sample)

2. Real Numbers in Python

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.

Characteristics of Real Numbers in Python:

 Floating-Point Numbers (float):

o Represent real numbers, including those with a decimal point.

o Example: 3.14159, 0.007, -2.5, 1.0e4 (which is 10000.0 in scientific notation).

o Python's float type is based on the IEEE 754 double-precision standard.

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.

Types of Immutable Variables in Python

Here are the most common types of immutable objects in Python:

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

3. Frozen Sets (frozenset):

o A frozenset is an immutable version of a set. You cannot add or remove elements


from a frozenset after it is created.

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 y = y + 1.0 # Creates a new float object with value 4.14

6. Complex Numbers (complex):

o Complex numbers, like integers and floats, are immutable.

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.

 Immutability provides benefits such as safety, efficiency, hashability, and facilitates a


functional programming approach.

 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

print("Hello, " + name) # Output the user's 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:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

 objects: The items to be printed. Multiple objects can be separated by commas.

 sep: The separator between multiple objects (default is a space).

 end: The string to append at the end (default is a newline \n).

 file: The file where the output will be written (default is the console).

 flush: Whether to forcibly flush the output buffer (default is False).

Basic Examples:

 Simple output:

 print("Hello, world!") # Outputs: Hello, world!

 Output multiple items:

 name = "Alice"

 age = 25

 print("Name:", name, "Age:", age) # Outputs: Name: Alice Age: 25

 Custom separator and end:

 print("Hello", "World", sep="-", end="!\n") # Outputs: Hello-World!

 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

 print(f"Name: {name}, Age: {age}") # Outputs: Name: Bob, Age: 30

Alternatively, you can use the older str.format() method:

print("Name: {}, Age: {}".format(name, age)) # Outputs: 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.

Arithmetic Operators and Expressions in Python

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:

Python supports the following arithmetic operators:

Operator Description Example Result

+ Addition 5+3 8

- Subtraction 5-3 2

* Multiplication 5*3 15

/ Division (float result) 5/2 2.5

// Floor Division (integer result) 5 // 2 2

% Modulus (remainder after division) 5 % 2 1

** Exponentiation (power) 5 ** 3 125

Examples of Arithmetic Expressions:

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

# Division (float result)

result_div = x / y # 10 / 3 = 3.333333...

# Floor Division

result_floor = x // y # 10 // 3 = 3 (integer division)

# Modulus (remainder)

result_mod = x % y # 10 % 3 = 1 (remainder of division)

# 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:

result = 5 + 3 * 2 # Multiplication is performed first

print(result) # Output: 11 (not 16)

To ensure the desired order of operations, you can use parentheses to change the precedence:

result = (5 + 3) * 2 # Addition is performed first

print(result) # Output: 16

Conditions in Python (Conditional Statements)

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

if age >= 18:

print("You are an adult.")

 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

if age >= 18:

print("You are an adult.")

else:

print("You are a minor.")

 Output: "You are a minor." because the condition age >= 18 is False.

3. elif (Else-If) Statement:

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

if age < 18:

print("You are a minor.")

elif age >= 18 and age < 60:

print("You are an adult.")

else:

print("You are a senior citizen.")

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

Operator Description Example Result

== Equal to 5 == 5 True

!= Not equal to 5 != 3 True


Operator Description Example Result

> Greater than 5>3 True

< Less than 5<3 False

>= Greater than or equal to 5 >= 5 True

<= Less than or equal to 5 <= 3 False

Example of using comparison operators:

a = 10

b=5

if a > b:

print("a is greater than b")

else:

print("a is not greater than b")

 Output: "a is greater than b" because 10 > 5.

Logical Operators:

Logical operators are used to combine multiple conditions in conditional statements.

Operator Description Example Result

and Returns True if both conditions are True True and False False

or Returns True if at least one condition is True True or False True

not Reverses the boolean value not True False

Example using logical operators:

age = 25

citizen = True

if age >= 18 and citizen:

print("You can vote.")

else:

print("You cannot vote.")

 Output: "You can vote." because both conditions are True.


Summary

 Arithmetic Operators: Used for mathematical operations (+, -, *, /, //, %, **).

 Conditions: Allow your program to make decisions with if, elif, and else.

 Comparison Operators: Used for comparing values (==, !=, >, <, >=, <=).

 Logical Operators: Combine multiple conditions (and, or, not).

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]

b = a # b references the same object as a

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.

 Syntax: value in iterable

 Returns: True if the value is present in the iterable, False otherwise.

Example:

# List example

numbers = [1, 2, 3, 4]

print(3 in numbers) # True, because 3 is in the list


# String example

sentence = "Python is great"

print("great" in sentence) # True, because "great" is a substring of the sentence

Key Differences:

 is checks if two variables refer to the same object in memory (object identity).

 in checks if an element is present in an iterable (membership).

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

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:

# Execute this block of code if condition is True

else:

# Execute this block of code if condition is False

Example:

x = 10

if x > 5:

print("x is greater than 5")

else:

print("x is less than or equal to 5")

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:

# Execute block 1 if condition1 is True

elif condition2:

# Execute block 2 if condition2 is True

else:

# Execute this block if neither condition1 nor condition2 are True

Example:

x = 15

if x < 10:

print("x is less than 10")

elif x == 15:

print("x is exactly 15")

else:

print("x is greater than 10 but not 15")

Output:

x is exactly 15

3. Nested if-else Statements

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:

# Execute block 1 if condition1 and condition2 are True

else:

# Execute block 2 if condition1 is True but condition2 is False

else:
# Execute block 3 if condition1 is False

Example:

x = 20

y = 10

if x > 15:

if y < 15:

print("x is greater than 15 and y is less than 15")

else:

print("x is greater than 15 but y is not less than 15")

else:

print("x is 15 or less")

Output:

x is greater than 15 and y is less than 15

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.

4.1 for 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:

for item in sequence:

# Execute this block of code for each item in the sequence

Example:

# Iterate over a list of numbers

numbers = [1, 2, 3, 4, 5]

for num in numbers:

print(num)

Output:

1
2

Example with range():

# Using range() to loop through numbers 0 to 4

for i in range(5):

print(i)

Output:

4.2 while Loop

The while loop executes a block of code as long as the specified condition remains True.

Syntax:

while condition:

# Execute this block of code as long as condition is True

Example:

# Print numbers from 1 to 5 using while loop

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:

user_input = input("Type 'exit' to stop: ")

if user_input == "exit":

print("Exiting...")

break # Breaks the loop if 'exit' is typed

5. Break and Continue Statements in Loops

 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:

break # Exit the loop when i equals 5

print(i)

Output:

Example of continue:

for i in range(10):

if i % 2 == 0:

continue # Skip even numbers

print(i)

Output:

5
7

Key Points:

 if-else: Used for decision making. Executes different blocks based on conditions.

 elif: Allows you to check multiple conditions in sequence.

 while loop: Repeats a block of code while a condition is true.

 for loop: Iterates over a sequence like a list, string, or range.

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

You might also like