Python by Tivan
Python by Tivan
Variables in Python store data, acting like labeled boxes to hold information for later use.
Example:
Strings:
In Python, strings are sequences of characters (letters, numbers, or symbols) enclosed in quotation marks. They are used to
represent text in your program.
For example:
You can enclose strings in either single (') or double (") quotes. Strings are useful for working with text, and you can perform
operations like combining or slicing them.
Example:
name = "Tivan"
Title Function:
The title() function in Python is a string method that converts the first letter of each word in a string to uppercase and
the rest of the letters to lowercase. This is commonly used to format titles or headings.
Example:
formatted_text = text.title()
This function is useful when you want to ensure that each word in a title or sentence begins with a capital letter.
In Python, the lower() and upper() functions are used to convert all the characters in a string to lowercase or uppercase,
respectively.
lower_text = text.lower()
upper_text = text.upper()
In Python, you can use f-strings (formatted string literals) to easily insert variables inside strings. Here's how you can do
it:
Example:
name = "Tivan"
age = 2
1. Newline (\n):
The newline character (\n) adds a line break, moving the following text to the next line.
python
text = "Hello\nWorld!"
print(text)
Output:
Hello
World!
2. Tab (\t):
The tab character (\t) inserts a horizontal tab, which is like adding a fixed amount of space before the text.
python
text = "Hello\tWorld!"
print(text)
Output:
Copy code
Hello World!
(Note: The exact width of the tab space depends on the environment or editor settings, but it's usually equivalent to 4 or
8 spaces.)
In Python, you can use the strip() method to remove leading and trailing whitespace (spaces, tabs, newlines, etc.) from a
string.
Example:
Python
clean_text = text.strip()
The strip() method removes spaces, tabs, and newlines at the beginning and end of the string. If you only want to
remove whitespace from the beginning, you can use lstrip(), and to remove from the end, you can use rstrip().
Examples:
clean_text = text.lstrip()
clean_text = text.rstrip()
Removing Prefixes :
To remove a prefix (a specific starting string) from a string in Python, you can use the removeprefix() method, which was
introduced in Python 3.9.
Example:
In Python, integers are whole numbers without a decimal point. They can be positive, negative, or zero and are used for
performing mathematical operations. Python's int type is flexible, allowing large numbers to be represented without
overflow.
Example:
y = -3 # A negative
integer
z=0 # Zero
You can perform arithmetic operations like addition, subtraction, multiplication, and division with integers:
sum_result = 5 + 3 # 8
diff_result = 10 - 4 # 6
prod_result = 6 * 2 # 12
Floats:
In Python, floats are numbers that contain decimal points. They can represent real numbers (i.e., numbers that may have
fractional parts), and they are commonly used for precise calculations involving non-whole numbers, such as scientific
computations, financial calculations, and more.
Example:
When integers and floats are mixed in Python, the integer is automatically converted to a float for arithmetic operations.
This ensures that the result can accommodate decimal values. This behavior is known as implicit type conversion (or type
coercion).ex:
integer_value = 5
float_value = 3.2
In Python, comments are used to explain or annotate code. They are non-executable and are ignored during program
execution. Comments help make the code more readable and understandable, both for the programmer and others who
might work with the code later.
Types of Comments:
1. Single-line comments: Use the # symbol. Everything after the # on the same line is considered a comment.
# This is a single-line comment
2. Multi-line comments: While Python doesn't have a built-in multi-line comment syntax, you can use consecutive
single-line comments or use triple quotes (''' or """), though they are technically multi-line strings.
# This is a multi-line comment
‘’’
multi-line comments.
‘’’
Purpose:
Documentation: Comments are used to explain the purpose of the code, its logic, or any complex operation.
Debugging: Comments can be used to temporarily disable parts of code while testing or debugging.
Collaboration: In collaborative projects, comments help team members understand each other's code.
The Zen of Python is a collection of aphorisms that capture the philosophy of Python's design and programming style. It
emphasizes simplicity, readability, and elegance in code. Written by Tim Peters, it's presented in a playful and poetic
manner, promoting Python's core principles.
You can view the Zen of Python by entering import this in the Python interpreter. Some of the most well-known
principles are:
4. "Readability counts."
These principles guide Python developers toward writing clean, readable, and maintainable code. They encourage a
design that avoids unnecessary complexity and favors clear solutions that can be easily understood by other developers.
List:
A list in Python is a collection of items, which can be of different types (such as integers, strings, or even other lists). Lists
are ordered, changeable, and allow duplicate elements. They are one of the most common data structures in Python.
Example:
To access elements in a list in Python, you use indexing. Python lists are ordered, so each element is assigned a unique
index, starting from 0. You can use these indices to access, modify, or iterate over elements in the list.
Example:
print(my_list[0]) # Outputs: 10
print(my_list[-1]) # Outputs: 50
In Python, indexing starts at 0 for lists. This means the first element of a list is accessed using index 0, the second
element with index 1, and so on. This is a standard behavior in many programming languages, not just Python.
Example:
print(my_list[0]) # Outputs: 10
print(my_list[1]) # Outputs: 20
1. Modifying Elements:
To modify an element in a list, you can access it using its index and assign a new value to it.
Example:
2. Adding Elements:
You can add elements to a list using methods like .append(), .insert(), or .extend().
my_list.append(40)
3. Removing Elements:
You can remove elements using methods like .remove(), .pop(), or del.
In Python, the pop() method is used to remove and return the last element from a list. It is a mutable operation,
meaning it modifies the original list.
Example:
list = [1, 2, 3, 5]
ost = list.pop()
print(ost) # Outputs: 5
Explanation:
Before calling pop(), the list is [1, 2, 3, 5].
After calling pop(), the last element 5 is removed from the list and returned.
The list now becomes [1, 2, 3], and ost contains the value 5 that was removed.
You can also specify an index inside the pop() method to remove an element from a specific position. For example:
print(ost) # Outputs: 2
These operations allow you to dynamically manage the contents of a list in Python.
To remove an item by value from a list in Python, you can use the remove() method. This method removes the first
occurrence of the specified value from the list. If the value does not exist, it will raise a ValueError.
Example:
Explanation:
In this example, remove(20) removes the first 20 it finds in the list, and the list becomes [10, 30, 40, 20].
If there are multiple occurrences of the value, only the first one is removed.
Sorting a List Permanently with sort():
The sort() method sorts the list in place, meaning it modifies the original list. It doesn't return a new list.
Example:
my_list = [3, 1, 4, 1, 5, 9]
The sorted() function returns a new sorted list, leaving the original list unchanged.
Example:
my_list = [3, 1, 4, 1, 5, 9]
You can print a list in reverse order using either the reverse() method or slicing.
my_list = [3, 1, 4, 1, 5, 9]
To find the length of a list in Python, you can use the built-in len() function. This function returns the number of elements
in the list.
Example:
list_length = len(my_list)
print(list_length) # Outputs: 5
Explanation:
The len() function counts the number of items in the list and returns that count.
To loop through an entire list in Python, you can use a for loop. This allows you to access each element in the list one by
one and perform an action on it.
Example:
print(item)
Explanation:
The for item in my_list: loop goes through each element in the list my_list and assigns it to the variable item.
The print(item) statement outputs each element of the list one by one.
Output:
10
20
30
40
50
This is a simple way to iterate through all elements of a list. You can modify the print(item) part to perform other actions
based on your needs, such as performing calculations or checking conditions.
Read pages 51- 56 by urself, its nothing special but since ur dumb ass cannot
digest it in ur shitty ass brain u have to read it.
Using the range() function:
The range() function in Python is often used to generate a sequence of numbers, which is useful when you need to loop
through a set of values with a for loop. The function generates a series of numbers from a starting point up to, but not
including, an endpoint.
for i in range(5):
print(i)
Output:
0
2
3
Explanation:
range(5) generates numbers from 0 to 4. By default, the starting number is 0 and the step size is 1.
To skip numbers like even numbers in Python, you can use the range() function with a step size of 2. This will allow you to
loop through only the odd numbers in a given range, for example.
for i in range(1, 11, 2): # Starts from 1, ends before 11, step size is 2
print(i)
Output:
Explanation:
range(1, 11, 2) starts from 1 and increments by 2 each time, effectively skipping all even numbers and only
printing odd numbers.
Example:
# Minimum value
min_value = min(numbers)
print(f"Minimum: {min_value}")
# Maximum value
max_value = max(numbers)
print(f"Maximum: {max_value}")
# Sum of the list
total_sum = sum(numbers)
print(f"Sum: {total_sum}")
Output:
Minimum: 10
Maximum: 50
Sum: 150
Slicing a List :
Slicing a list in Python allows you to extract a specific portion (or slice) of a list by specifying a start, stop, and
step index.
Basic Syntax:
list[start:stop:step]
Explanation:
numbers[1:4] gives you the elements at indices 1, 2, and 3 (excluding 4).
numbers[2:] gives you all elements from index 2 to the end of the list.
numbers[:3] gives you the first three elements (from index 0 to 2).
numbers[::2] gives every second element in the list (starting from the first).
62 n 63 by urself
Defining a Tuple :
A tuple in Python is a collection of ordered, immutable elements. Once defined, the values in a tuple cannot
be changed. Tuples are typically used to store multiple related values in a single variable.
Defining a Tuple:
Output:
Key Points:
Ordered: The elements have a defined order, and you can access them via their index (starting from 0).
Immutable: Once a tuple is created, its elements cannot be modified.
Can contain different data types: A tuple can hold integers, strings, floats, or even other tuples.
66- 69 by urself.