0% found this document useful (0 votes)
4 views3 pages

Python Basics for Beginners

This document provides beginner notes on Python, covering strings, numbers, lists, tuples, and sets, along with examples and common functions. It includes basic string operations, arithmetic operations, and methods for manipulating lists and sets. Additionally, it presents exercises to reinforce learning through practical application.

Uploaded by

benbibilbabu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

Python Basics for Beginners

This document provides beginner notes on Python, covering strings, numbers, lists, tuples, and sets, along with examples and common functions. It includes basic string operations, arithmetic operations, and methods for manipulating lists and sets. Additionally, it presents exercises to reinforce learning through practical application.

Uploaded by

benbibilbabu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Beginner Notes with Examples & Exercises

1. Strings - Working with Text

Strings are used to store text.

Examples:

message = "Hello World"

print(message) # Hello World

Common String Functions:

- len("Hello") => 5

- "Hello".lower() => "hello"

- "hello".upper() => "HELLO"

- "hello".count("l") => 2

- "hello world".find("world") => 6

- "hello world".replace("world", "Python") => "hello Python"

Formatted String:

name = "John"

greeting = f"Hello, {name}!" # f-string

print(greeting) # Hello, John!

2. Numbers - Integers and Floats

Numbers in Python are either integers (whole) or floats (decimals).

Examples:

num = 3.14

print(type(num)) # <class 'float'>

Arithmetic Operations:

- 3 + 2 => 5

- 3 - 2 => 1

- 3 * 2 => 6
Python Beginner Notes with Examples & Exercises

- 3 / 2 => 1.5

- 3 // 2 => 1 (floor division)

- 3 ** 2 => 9 (exponent)

- 3 % 2 => 1 (modulus)

Useful Functions:

- abs(-5) => 5

- round(3.75) => 4

- round(3.75, 1) => 3.8

3. Lists, Tuples, and Sets

Lists:

courses = ["Math", "History", "Art"]

[Link]("Physics")

[Link](0, "Biology")

[Link]("Math")

[Link]() # Removes last

[Link]()

[Link]()

Tuple:

Immutable list (can't change)

tup = ("Math", "Art")

Set:

No duplicates, unordered

subjects = {"Math", "Art", "Math"} # Only one "Math"

Set Functions:

- intersection()

- difference()
Python Beginner Notes with Examples & Exercises

- union()

4. Exercises

1. Create a string variable called `greeting` with value "Hi There", and print its uppercase version.

2. Use math operators to calculate: (4 + 5) * 3

3. Create a list of 3 fruits. Add one more fruit and remove the second fruit.

4. Create a set with duplicates. Print the set.

5. Write a formatted string to say "Welcome, Alex!" using variable `name = "Alex"`.

6. What is the output of: "hello".find("e") ?

Common questions

Powered by AI

Python string methods offer versatile ways to manipulate text and extract information. The len() function returns the count of characters in a string, providing a quick insight into its length. Case transformations are accomplished using .lower() and .upper(), converting strings to lowercase or uppercase, respectively. The .count() method is useful for determining the frequency of a substring, as in 'hello'.count('l'), which returns 2 . Searching within strings can be executed with .find(), which returns the index of the first occurrence of a substring, such as 'hello world'.find('world') producing 6 . Replacing text portions can be done with .replace(), for example, 'hello world'.replace('world', 'Python') yields 'hello Python' . These methods empower users to perform a range of operations for various text processing needs.

The mutability of Python lists allows for dynamic changes to collections of items, which is particularly useful for managing datasets that require frequent updates. Lists can have elements appended, inserted, or removed without recreating the entire list . This is accomplished through methods like append(), insert(), and remove(). In contrast, tuples are immutable, meaning once created, their contents cannot be changed, which offers stability and security for data that should remain constant, but requires creating new tuples for any alterations . This immutability makes tuples less flexible but ensures data integrity.

Operations on Python sets are invaluable in practical applications due to their ability to handle unique data items efficiently and perform fast membership tests. The lack of duplicates significantly reduces complexities in operations like unions, intersections, or differences, which are computationally more efficient compared to list operations due to hash-based implementations. For instance, analyzing datasets to find common items across different sets uses the intersection(), improving clarity and speed compared to manual iteration . Real-world uses include network topology analysis, de-duplication tasks, and even operations in relational databases handling joins. By minimizing data redundancies and optimizing comparison operations, Python sets greatly enhance computational efficiency and performance in large-scale data processing tasks.

Formatted strings in Python, also known as f-strings, allow for the inclusion of expressions inside string literals, using curly braces. This feature streamlines string creation and improves readability when combining static strings with dynamic content. An example is using a variable within a greeting message: if name = "John", then the formatted string greeting = f"Hello, {name}!" produces the output 'Hello, John!' when printed, personalizing the message with the variable's value .

Math operators in Python, such as addition (+), subtraction (-), multiplication (*), and division (/), lay the groundwork for constructing complex expressions that can be used in various scenarios. They operate in conjunction with functions like abs() to determine absolute values or round() to round numbers, crucial for numerical analysis. For example, calculating an expression like (4 + 5) * 3 involves both arithmetic operations and order of operations (PEMDAS/BODMAS) to yield 27 . Advanced calculations can be enhanced by employing ** for exponentiation and % for modulus, like 3 ** 2 yielding 9, and 3 % 2 resulting in 1. These tools enable developers to implement intricate calculations programmatically, supporting tasks ranging from simple math to dynamic scientific computations.

In Python, arithmetic operations can involve integers and floats, which are handled differently. With division, using '/' will always yield a float, so 3 / 2 will return 1.5 . However, the '//' operator performs floor division, which returns the largest integer less than or equal to the division result, like 3 // 2 yielding 1 . In modulus operations, which return the remainder of division, integers yield integer results, such as 3 % 2 resulting in 1 . Floats are also handled similarly, but the results maintain floating-point precision.

Python handles text strings using a class called 'str' which provides various methods to manipulate and analyze text data. Common string functions include obtaining the length of a string with len(), converting strings to lower or upper case using .lower() and .upper(), counting occurrences of a substring with .count(), finding a substring with .find(), and replacing parts of a string with .replace(). For example, 'Hello'.lower() returns 'hello', and 'hello'.count('l') returns 2 .

Python set operations enhance data analysis tasks by providing efficient ways to handle collections without duplicates and support various mathematical set operations. Set functions like intersection(), difference(), and union() allow for the comparison and combination of datasets, which can be particularly useful for identifying common elements, unique items, or combining datasets. For instance, intersection() retrieves common elements between sets, difference() finds elements present in one set but not the other, and union() combines all elements from involved sets . These operations streamline data analysis by offering straightforward methods to manage and reduce data complexity.

Lists, tuples, and sets are different types of data structures in Python with distinct characteristics. Lists are mutable and ordered, meaning you can change their contents and their elements maintain a specific order. For instance, a list of courses can have elements added or removed using methods like append() or remove(). Tuples, on the other hand, are immutable and ordered, which means once they are created, their contents cannot be changed; they are ideal for storing data that should not be altered . Sets are mutable but unordered, so they automatically eliminate duplicates and do not retain any particular order of elements, making them useful for operations such as union or difference calculations .

Formatted strings in Python, particularly through f-strings, are pivotal for dynamically generating content that interacts with users or adjusts based on context. They allow developers to seamlessly integrate variable content into strings, fostering personalization and adaptability, which is key in applications requiring individualized feedback or adaptable output. For example, constructing a message with a user's name can be effortlessly done with name = 'Alex'; greeting = f'Welcome, {name}!' produces 'Welcome, Alex!' . This capability enhances user engagement by providing context-aware responses and simplifies code readability, making maintenance and updates easier, especially in applications that require frequent modifications or internationalization.

You might also like