0% found this document useful (0 votes)
2 views13 pages

Python by Tivan

python pamphlet

Uploaded by

tivan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views13 pages

Python by Tivan

python pamphlet

Uploaded by

tivan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

What are Variables in Python?

Variables in Python store data, acting like labeled boxes to hold information for later use.

Example:

name = "Tivan" # Stores the name "Pirooz"

age = "16" # Stores the age "Tivan"

print(name, age) # Outputs: Pirooz Tivan

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:

greeting = "Hello, Tivan!" # A string

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"

message = "Hello, " + name # Concatenates the strings

print(message) # Outputs: Hello, 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:

text = "hello, tivan!"

formatted_text = text.title()

print(formatted_text) # Outputs: Hello, Tivan!

This function is useful when you want to ensure that each word in a title or sentence begins with a capital letter.

Lower and Upper :

In Python, the lower() and upper() functions are used to convert all the characters in a string to lowercase or uppercase,
respectively.

lower(): Converts all characters of the string to lowercase.

text = "Hello, Tivan!"

lower_text = text.lower()

print(lower_text) # Outputs: hello, tivan!


upper(): Converts all characters of the string to uppercase.

text = "Hello, Tivan!"

upper_text = text.upper()

print(upper_text) # Outputs: HELLO, TIVAN!

Using Variables in Strings:

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

greeting = f"Hello, {name}! You are {age} years old."

print(greeting) # Outputs: Hello, Tivan! You are 2 years old.

Adding Whitespace to strings with tabs or newlines:


In Python, you can add whitespace to strings using special characters like tab (\t) and newline (\n). These characters help
format the text by adding indentation or moving to a new line.

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

text = " Hello, Tivan! \n"

clean_text = text.strip()

print(clean_text) # Outputs: "Hello, Tivan!"

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:

# Removing leading whitespace (left side)

text = " Hello, Tivan!"

clean_text = text.lstrip()

print(clean_text) # Outputs: "Hello, Tivan!"

# Removing trailing whitespace (right side)

text = "Hello, Tivan! "

clean_text = text.rstrip()

print(clean_text) # Outputs: "Hello, Tivan!"

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:

text = "Mr. Tivan"

new_text = text.removeprefix("Mr. ")

print(new_text) # Outputs: Tivan


Integers :

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:

x=5 # A positive integer

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

quot_result = 8 // 3 # 2 (integer division)

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:

a = 3.14 # A float representing Pi

b = -0.001 # A negative float

c = 10.0 # Another float (can also be written as just 10)

You can perform various operations on floats, such as:

sum_result = 3.5 + 4.5 # 8.0

diff_result = 5.6 - 1.1 # 4.5

prod_result = 2.5 * 4 # 10.0

quot_result = 9.0 / 2 # 4.5

Floats and integers :

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

result = integer_value + float_value # 5 + 3.2 = 8.2 (float result)

print(result) # Outputs: 8.2


Comments:

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

x = 10 # This comment is next to code

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

# which explains the code below

‘’’

This is another way to write

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 :

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:

1. "Beautiful is better than ugly."

2. "Explicit is better than implicit."

3. "Simple is better than complex."

4. "Readability counts."

5. "There should be one—and preferably only one—obvious way to do it."

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:

my_list = [1, 2, 3, "hello", True]

print(my_list) # Outputs: [1, 2, 3, "hello", True]

Accessing Elements in a list:

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:

my_list = [10, 20, 30, 40, 50]

Accessing the first element:

print(my_list[0]) # Outputs: 10

Accessing the last element (using negative indexing):

print(my_list[-1]) # Outputs: 50

Index Positions Start at 0, not 1 :

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:

my_list = [10, 20, 30, 40]

print(my_list[0]) # Outputs: 10

print(my_list[1]) # Outputs: 20

Using Individual Values from a List:

Do this by ur self lil nigga : Page 35


Modifying, adding and removing elements :

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:

my_list = [10, 20, 30]

my_list[1] = 25 # Modifies the second element (index 1)

print(my_list) # Outputs: [10, 25, 30]

2. Adding Elements:

You can add elements to a list using methods like .append(), .insert(), or .extend().

 .append() adds an element to the end of the list:

my_list.append(40)

print(my_list) # Outputs: [10, 25, 30, 40]

 .insert() adds an element at a specific index:

my_list.insert(1, 15) # Adds 15 at index 1

print(my_list) # Outputs: [10, 15, 25, 30, 40]

3. Removing Elements:

You can remove elements using methods like .remove(), .pop(), or del.

 .remove() removes the first occurrence of a specific value:

my_list.remove(25) # Removes the first occurrence of 25

print(my_list) # Outputs: [10, 15, 30, 40, 50, 60]

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]

print(list) # Outputs: [1, 2, 3, 5]

# Using pop() to remove and return the last element

ost = list.pop()

print(list) # Outputs: [1, 2, 3]

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:

ost = list.pop(1) # Removes and returns the element at index 1

print(list) # Outputs: [1, 3, 5]

print(ost) # Outputs: 2

If no index is provided, pop() removes the last item by default.

 del removes an element by index or deletes the entire list:

del my_list[1] # Deletes the element at index 1

print(my_list) # Outputs: [10, 40, 50, 60]

These operations allow you to dynamically manage the contents of a list in Python.

Removing an item by Value:

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:

my_list = [10, 20, 30, 40, 20]

print(my_list) # Outputs: [10, 20, 30, 40, 20]

# Removing an item by value

my_list.remove(20) # Removes the first occurrence of 20

print(my_list) # Outputs: [10, 30, 40, 20]

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]

my_list.sort() # Sorts the list permanently

print(my_list) # Outputs: [1, 1, 3, 4, 5, 9]

Sorting Temporarily with sorted():

The sorted() function returns a new sorted list, leaving the original list unchanged.

Example:

my_list = [3, 1, 4, 1, 5, 9]

sorted_list = sorted(my_list) # Returns a sorted list, without modifying the original

print(sorted_list) # Outputs: [1, 1, 3, 4, 5, 9]

print(my_list) # Outputs: [3, 1, 4, 1, 5, 9] (Original list is unchanged)

Printing a List in Reverse Order:

You can print a list in reverse order using either the reverse() method or slicing.

 Using reverse() (modifies the list in place):

my_list = [3, 1, 4, 1, 5, 9]

my_list.reverse() # Reverses the list permanently

print(my_list) # Outputs: [9, 5, 1, 4, 1, 3]

Finding the Length of a list :

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:

my_list = [10, 20, 30, 40, 50]

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.

In the example above, my_list has 5 elements, so len(my_list) returns 5.


Looping through an entire list :

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:

my_list = [10, 20, 30, 40, 50]

# Looping through the entire list

for item in my_list:

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.

Basic Usage of range():

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.

Using Range() to make a list of numbers :

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.

Skipping Even Numbers (Printing Odd Numbers):

# Skipping even numbers (printing only odd numbers)

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.

Read Page 58*

Simple Statistics with a list of numbers:


To calculate the minimum, maximum, and sum of a list of numbers in Python, you can use the built-in functions min(),
max(), and sum().

Example:

numbers = [10, 20, 30, 40, 50]

# 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

Read list comprehensions by urself

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]

 start: The index where the slice begins (inclusive).


 stop: The index where the slice ends (exclusive).
 step: The interval between each index (optional, defaults to 1).
Example:

numbers = [10, 20, 30, 40, 50, 60]


# Slicing from index 1 to 4 (20, 30, 40)
slice1 = numbers[1:4]
print(slice1) # Output: [20, 30, 40]

# Slicing from index 2 to the end (30, 40, 50, 60)


slice2 = numbers[2:]
print(slice2) # Output: [30, 40, 50, 60]
# Slicing from the beginning to index 3 (10, 20, 30)
slice3 = numbers[:3]
print(slice3) # Output: [10, 20, 30]

# Slicing with a step of 2 (10, 30, 50)


slice4 = numbers[::2]
print(slice4) # Output: [10, 30, 50]

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:

# Example of defining a tuple


my_tuple = (1, 2, 3, "hello", 5.6)
print(my_tuple)

Output:

(1, 2, 3, 'hello', 5.6)

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.

You might also like