1-Basics-Of Python
1-Basics-Of Python
1-Basics-Of Python
Overview of Python:
Python is a high-level, interpreted programming language known for its simplicity and
readability.
It was developed by Guido van Rossum and first released in 1991.
Python emphasizes code readability with its notable use of significant whitespace.
Why Learn Python?
Simplicity: Easy to read and write.
Versatility: Used in web development, data analysis, AI, scientific computing, and
more.
Large Community: Extensive libraries and frameworks available.
Career Opportunities: High demand in various industries.
Real-world Applications:
Web Development (e.g., Django, Flask)
Data Science and Machine Learning (e.g., Pandas, scikit-learn)
Automation and Scripting
Game Development (e.g., Pygame)
Embedded Systems
⬛ Installing Python
Step-by-Step Installation:
Windows:
1. Download the installer from the official Python website.
2. Run the installer and check the box to add Python to your PATH.
3. Click “Install Now” and follow the prompts.
macOS:
1. Download the installer from the Python website.
2. Open the .pkg file and follow the instructions.
3. Verify installation by opening the terminal and typing python3 --version .
Linux:
1. Open your terminal.
2. Update your package list: sudo apt update .
3. Install Python 3: sudo apt install python3 .
Verifying Installation:
Open a terminal or command prompt.
Type python --version or python3 --version to check the installed version.
⬛ Install Pycharm
PyCharm is a popular Integrated Development Environment (IDE) for Python development.
Here's a step-by-step guide to installing PyCharm on your computer:
For Windows:
1. Once the download is complete, open the installer ( pycharm-community-*.exe for the
Community edition).
2. Follow the installation wizard:
Click "Next" to continue.
Choose the installation location and click "Next."
Select the installation options you prefer, such as creating a desktop shortcut or
associating .py files with PyCharm.
Click "Install" to begin the installation process.
3. After the installation is complete, click "Finish" to exit the installer. You can choose to run
PyCharm immediately if you wish.
print("Hello, World!")
Running the Program:
print("Hello, World!")
# greeting.py
Steps Involved:
⬛ Python Comments
Single-line Comments: Use the # symbol.
"""
This is a multi-line comment
that spans multiple lines.
"""
Best Practices:
⬛ Python Variables
Definition:
Assigning Values:
x = 5
name = "Alice"
is_student = True
Naming Conventions:
Descriptive Names: Use meaningful and descriptive names to make your code self-
explanatory. For example, use total_cost instead of tc .
Lowercase with Underscores: Variable names should be written in lowercase letters and
words should be separated by underscores for readability. For example, student_name
instead of studentName .
Avoid Reserved Words: Do not use Python reserved keywords as variable names, such
as class , for , if , etc.
Start with a Letter or Underscore: Variable names must start with a letter (a-z, A-Z) or an
underscore (_). They cannot start with a number.
No Special Characters: Variable names should only contain letters, numbers, and
underscores. Avoid using special characters like ! , @ , # , etc.
Case Sensitivity: Remember that variable names are case-sensitive. For example,
myVariable and myvariable are two different variables.
Short but Meaningful: While being descriptive, try to keep variable names reasonably
short. For example, num_students is better than number_of_students_in_the_class .
Use Singular Nouns: Use singular nouns for variables that hold a single value, and plural
nouns for variables that hold collections. For example, student for a single student, and
students for a list of students.
Consistency: Be consistent with your naming conventions throughout your code to
maintain readability and ease of understanding.
Avoid Double Underscores: Do not use double underscores at the beginning and end of
variable names, as these are reserved for special use in Python (e.g., __init__ ,
__main__ ).
Basic Operations:
a = 10
b = 20
sum = a + b
print(sum) # Output: 30
x = 5 # int
y = 3.14 # float
z = 1 + 2j # complex
int : Whole numbers without decimal points. Used for counting and indexing.
float : Numbers with decimal points. Used for precise calculations and measurements.
complex : Numbers with real and imaginary parts. Used for advanced mathematical
computations.
String Type
str: A sequence of characters, e.g., "hello" , 'world' .
Collect and Store Feedback: Gather customer feedback and store it in a list of strings.
Extract Useful Information: Identify key phrases or sentiments to understand customer
opinions.
Format Responses: Prepare feedback data for reporting or display, enhancing readability.
Sequence Types
list: Ordered, mutable collection of items, e.g., [1, 2, 3] , ['a', 'b', 'c'] .
tuple: Ordered, immutable collection of items, e.g., (1, 2, 3) , ('a', 'b', 'c') .
# has index
print(coordinates[0])
range: Represents an immutable sequence of numbers, commonly used in loops, e.g.,
range(5) , range(1, 10, 2) .
# Using Loop
numbers = range(1, 10)
for number in numbers:
print(number)
# Converting List
print(list(numbers))
# Use Star
print(*numbers)
List: Used for storing a collection of items that can be modified. Ideal for tasks where you
need to add, remove, or change items frequently.
Tuple: Used for storing a collection of items that should not be changed. Perfect for read-
only data or fixed collections of items, like coordinates or configuration settings.
Range: Used for generating a sequence of numbers. Commonly used in loops for iterating
a specific number of times or creating sequences of numbers efficiently.
Mapping Type
dict: Unordered, mutable collection of key-value pairs, e.g., {'name': 'Alice', 'age':
25}
Storing Employee Data: Use dictionaries to store employee information with unique IDs
as keys and details (name, position, salary) as values.
Accessing Employee Data: Retrieve specific employee details quickly using their unique
ID as the key.
Updating Employee Records: Easily update or modify employee information in the
dictionary by accessing the relevant key.
Set Types
set: Unordered, mutable collection of unique items, e.g., {1, 2, 3} , {'a', 'b', 'c'} .
Set: Used for storing a collection of unique items. Ideal for tasks that require eliminating
duplicates or performing mathematical set operations like unions, intersections, and
differences.
Frozenset: An immutable version of a set. Suitable for scenarios where a set of unique
items needs to be hashable, such as using sets as dictionary keys or elements of another
set.
Boolean Type
is_active = True
None Type
result = None
Function with No Return Value: Use None to indicate that a function does not return a
value. This is useful for functions that perform actions rather than calculations.
Default Parameter Values: Use None as a default parameter value to signify that no
argument was passed, allowing for flexible function definitions and behavior.
Placeholder for Optional Data: Use None as a placeholder for optional or missing data,
making it clear when a variable is intentionally left unset or waiting for a value.
y = 3.14
print(type(y)) # Output: <class 'float'>
message = "Hello"
print(type(message)) # Output: <class 'str'>
is_valid = True
print(type(is_valid)) # Output: <class 'bool'>
Input Validation: Ensure that user inputs are of the expected type before processing
them.
Function Arguments: Validate function arguments to prevent type errors and ensure
correct operation.
Data Processing: Confirm data types during processing to apply appropriate operations
and avoid errors.
Configuration Loading: Verify the types of configuration settings loaded from files or
environment variables.
Dynamic Data Handling: Handle data that can come in various types (e.g., JSON
parsing) by checking types before processing.
b = 3.14
initial_id = id(b)
b = 2.71 # Creates a new float object with value 2.71
new_id=id(b)
s = "hello"
initial_id = id(s)
s = "world" # Creates a new string object with value "world"
new_id=id(s)
t = (1, 2, 3)
initial_id = id(t)
t = (4, 5, 6) # Creates a new tuple object with different values
new_id=id(t)
fs = frozenset([1, 2, 3])
initial_id = id(fs)
fs = frozenset([4, 5, 6]) # Creates a new frozenset object with different
values
new_id=id(fs)
Configuration Settings: Store application settings in tuples to ensure they are not
accidentally modified.
User Roles: Define fixed user roles (e.g., admin, editor, viewer) using tuples for security
and integrity.
API Endpoints: Use tuples to store API endpoints, ensuring the URLs remain constant.
Coordinates: Store geographical coordinates as tuples to maintain their integrity
throughout the application.
Cache Keys: Use frozensets for cache keys to ensure that key combinations remain
consistent and hashable.
l = [1, 2, 3]
initial_id = id(l)
l[0] = 4 # Modifies the existing list object
new_id = id(l)
d = {'a': 1, 'b': 2}
initial_id = id(d)
d['a'] = 3 # Modifies the existing dictionary object
new_id = id(d)
s = {1, 2, 3}
initial_id = id(s)
s.add(4) # Modifies the existing set object
new_id = id(s)
User Sessions: Use dictionaries to store session data, allowing dynamic updates of user-
specific information.
Shopping Cart: Implement shopping carts using lists to add, remove, or modify items
based on user actions.
Form Data: Collect and modify form inputs using dictionaries, making it easy to validate
and process user submissions.
Real-time Notifications: Maintain a list of notifications for users, allowing additions and
deletions as new events occur.
Dynamic UI Elements: Use lists or dictionaries to manage dynamic elements like user-
generated content or interactive components that change based on user interaction.
⬛ Type Conversion
Explicit Type Conversion: The programmer manually converts a data type using functions like
int(), float(), or str().
x = "123"
y = int(x) # Convert string to integer
z = float(x) # Convert string to float
a = str(456) # Convert integer to string
Implicit Type Conversion: Python automatically converts one data type to another during
operations without explicit instruction from the programmer.
x = 10
y = 3.14
z = x + y # x is converted to float
print(z) # Output: 13.14
try:
x = "abc"
y = int(x)
except Exception as e:
print(f"An error occurred: {e}")
User Input Handling: Convert string inputs from forms into integers or floats for
calculations.
Data Processing: Convert data types when reading from or writing to files to ensure
correct data formats.
Mathematical Operations: Convert data to appropriate numeric types for accurate
mathematical operations.
JSON Parsing: Convert data types when parsing JSON to ensure correct types for further
processing.
Database Interaction: Convert data types to match database schema requirements when
inserting or retrieving data.
# Calculate Fahrenheit
fahrenheit = (celsius * 9/5) + 32