0% found this document useful (0 votes)
6 views24 pages

Python Notes

The document explains the concept of variables in programming, including naming conventions, the importance of descriptive names, and the use of comments. It also covers string data types, string methods, and how to manipulate strings through concatenation, indexing, and slicing. Additionally, it discusses multiline strings and provides guidelines for writing effective comments in code.

Uploaded by

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

Python Notes

The document explains the concept of variables in programming, including naming conventions, the importance of descriptive names, and the use of comments. It also covers string data types, string methods, and how to manipulate strings through concatenation, indexing, and slicing. Additionally, it discusses multiline strings and provides guidelines for writing effective comments in code.

Uploaded by

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

VARIABLES.

Variable is a memory location that holds some data or information in a program.


Variable names are case sensitive, so a variable named greeting is
not the same as a variable named Greeting. For instance, the following
code produces a NameError:

>>> greeting = "Hello, World"

>>> print(Greeting)

Traceback (most recent call last): File "", line 1, in NameError: name 'Greeting' is not defined.

Rules for Valid Variable Names:


Variable names can be as long or as short as you like, but there are a
few rules that you must follow.
Variable names may contain uppercase and lowercase letters (A–Z, a–z), digits (0–9), and
underscores
(_), but they cannot:
a) begin with a digit.
b) Begin with a special symbol.
c) Contain spaces in between
d) Be a reserved word.
For example, each of the following is a valid Python variable name:
• string1
• _a1p4a
• list_of_names
The following aren’t valid variable names because they start with a
digit:
• 9lives
• 99_balloons
• 2beOrNot2Be
NB: variables are used to effectively manage data in a program.
Descriptive Names Are Better Than Short Names
Descriptive variable names are essential, especially for complex
programs. Writing descriptive names often requires using multiple
words. Don’t be afraid to use long variable names.
In the following example, the value 3600 is assigned to the variable s:
s = 3600
The name s is totally ambiguous. Using a full word makes it a lot easier
to understand what the code means:
seconds = 3600.
seconds is a better name than s because it provides more context. But
it still doesn’t convey the full meaning of the code. Is 3600 the number
of seconds it takes for a process to finish, or is it the length of a movie?
There’s no way to tell.
The following name leaves no doubt about what the code means:
seconds_per_hour = 3600
When you read the above code, there’s no question that 3600 is the
number of seconds in an hour. seconds_per_hour takes longer to type
than both the single letter s and the word seconds, but the payoff in
clarity is massive.
Although naming variables descriptively means using longer variable
names, you should avoid using excessively long names. A good rule
of thumb is to limit variable names to three or four words maximum.

Review Exercises
1. Using the interactive window, display some text using print().
2. Using the interactive window, assign a string literal to a variable.
Then print the contents of the variable using the print() function
COMMENTS:
Comments are lines of text that don’t affect the way a program runs.
They document what code does or why the programmer made certain
decisions.
How to Write a Comment
The most common way to write a comment is to begin a new line in
your code with the # character. When you run your code, Python ignores lines starting with #.
Comments that start on a new line are called block comments. You
can also write inline comments, which are comments that appear
on the same line as the code they reference. Just put a # at the end of
the line of code, followed by the text in your comment.
Here’s an example of a program with both kinds of comments:
# This is a block comment.
greeting = "Hello, World"
print(greeting) # This is an inline comment.
Of course, you can still use the # symbol inside a string. For instance,
Python won’t mistake the following for the start of a comment:
>>> print("#1")
#1
In general, it’s a good idea to keep comments as short as possible, but
sometimes you need to write more than reasonably fits on a single line.
In that case, you can continue your comment on a new line that also
begins with the # symbol:
# This is my first program.
# It prints the phrase "Hello, World"
# The comments are longer than the code!
greeting = "Hello, World"
print(greeting)
You can also use comments to comment out code while you’re testing a program. Putting a # at
the beginning of a line of code lets you run your program as if that line of code didn’t exist, but it
doesn’t actually delete the code.
To comment out a section of code in IDLE, highlight one or more lines to be commented and
press:
• Windows: Alt + 3.
To remove comments, highlight the commented lines and press:
Windows: Alt + 4

Strings and String Methods:


Collections of text in Python are called strings. Special functions called string methods are used
to manipulate strings. There are string methods for changing a string from lowercase to
uppercase, removing whitespace from the beginning or end of a string, replacing parts of a string
with different text, and much more.
The String Data Type:
The term data type refers to what kind of data a value represents. Strings are used
to represent text.
The string data type has a special abbreviated name in Python: str.
You can see this by using type(), which is a function used to determine the data type of a given
value.
Type the following into IDLE’s interactive window:
>>> type("Hello, World")
<class 'str'>
The output <class 'str'> indicates that the value "Hello, World" is an instance of the str data type.
That is, "Hello, World" is a string.
Strings have three important properties:
1. Strings contain individual letters or symbols called characters.
2. Strings have a length, defined as the number of characters the string contains.
3. Characters in a string appear in a sequence, which means that each character has a numbered
position in the string.
String Literals:
As you’ve already seen, you can create a string by surrounding some
text with quotation marks:
string1 = 'Hello, World'
string2 = "1234"
You can use either single quotes (string1) or double quotes (string2)
to create a string as long as you use the same type at the beginning
and end of the string.
Whenever you create a string by surrounding text with quotation
marks, the string is called a string literal. The name indicates that
the string is literally written out in your code. All the strings you’ve
seen thus far are string literals.
The quotes surrounding a string are called delimiters because they
tell Python where a string begins and where it ends. When one type of
quotes is used as the delimiter, the other type can be used inside the
string:
string3 = "We're #1!"
string4 = 'I said, "Put it over by the llama."'
After Python reads the first delimiter, it considers all the characters
after it part of the string until it reaches a second matching delimiter.
This is why you can use a single quote in a string delimited by double
quotes, and vice versa.
If you try to use double quotes inside a string delimited by double
quotes, you’ll get an error:
>>> text = "She said, "What time is it?""
File "<stdin>", line 1
text = "She said, "What time is it?""
SyntaxError: invalid syntax
Python throws a SyntaxError because it thinks the string ends after the
second ", and it doesn’t know how to interpret the rest of the line. If you need to include a
quotation mark that matches the delimiter inside a string, then you can escape the character using
a backslash:
>>> text = "She said, \"What time is it?\""
>>> print(text)
She said, "What time is it?"
Determine the Length of a String:
The number of characters contained in a string, including spaces, is
called the length of the string. For example, the string "abc" has a
length of 3, and the string "Don't Panic" has a length of 11.
Python has a built-in len() function that you can use to determine the
length of a string. To see how it works, type the following into IDLE’s
interactive window:
>>> len("abc")
3
You can also use len() to get the length of a string that’s assigned to a
variable:
>>> letters = "abc"
>>> len(letters)
3
First, you assign the string "abc" to the variable letters. Then you use
len() to get the length of letters, which is 3.

Multiline Strings.
To deal with long strings, you can break them up across multiple lines
into multiline strings. For example, suppose you need to fit the
following text into a string literal:
This planet has—or rather had—a problem, which was
this: most of the people living on it were unhappy for
pretty much of the time. Many solutions were suggested
for this problem, but most of these were largely concerned with the movements of small green
pieces of
paper, which is odd because on the whole it wasn’t the
small green pieces of paper that were unhappy.
— Douglas Adams, The Hitchhiker’s Guide to the Galaxy

This paragraph contains far more than seventy-nine characters, so


any line of code containing the paragraph as a string literal violates
PEP 8. So, what do you do?
There are a couple of ways to tackle this. One way is to break the string
up across multiple lines and put a backslash (\) at the end of all but the last line. To be PEP 8
compliant, the total length of the line, including
the backslashes, must be seventy-nine characters or fewer.
Here’s how you could write the paragraph as a multiline string using
the backslash method:
paragraph = "This planet has—or rather had—a problem, which was \
this: most of the people living on it were unhappy for pretty much \
of the time. Many solutions were suggested for this problem, but \
most of these were largely concerned with the movements of small \
green pieces of paper, which is odd because on the whole it wasn't \
the small green pieces of paper that were unhappy."
Notice that you don’t have to close each line with a quotation mark.
Normally, Python would get to the end of the first line and complain
that you didn’t close the string with a matching double quote. With a
backslash at the end, you can keep writing the same string on the next
line.
When you print() a multiline string that’s broken up by backslashes,
the output is displayed on a single line:
>>> long_string = "This multiline string is \
displayed on one line"
>>> print(long_string)
This multiline string is displayed on one line
You can also create multiline strings using triple quotes (""" or ''') as
delimiters. Here’s how to write a long paragraph using this approach:
paragraph = """This planet has—or rather had—a problem, which was
this: most of the people living on it were unhappy for pretty much
of the time. Many solutions were suggested for this problem, but
most of these were largely concerned with the movements of small
green pieces of paper, which is odd because on the whole it wasn't
the small green pieces of paper that were unhappy."""
Triple-quoted strings preserve whitespace, including newlines. This
means that running print(paragraph) would display the string on multiple lines, just as it appears
in the string literal. This may or may not
be what you want, so you’ll need to think about the desired output
before you choose how to write a multiline string.
To see how whitespace is preserved in a triple-quoted string, type the
following into IDLE’s interactive window:
>>> print("""An example of a
... string that spans across multiple lines
... and also preserves whitespace.""")
An example of a string that spans across multiple lines
and also preserves whitespace.
Notice how the second and third lines in the output are indented in
exactly the same way as the string literal.
REVIEW QUESTIONS:
1. Print a string that uses double quotation marks inside the string.
2. Print a string that uses an apostrophe inside the string.
3. Print a string that spans multiple lines with whitespace preserved.
4. Print a string that is coded on multiple lines but gets printed on a
single line.
Concatenation, Indexing, and Slicing.
1. Concatenation, which joins two strings together
2. Indexing, which gets a single character from a string
3. Slicing, which gets several characters from a string at once.
String Concatenation
You can combine, or concatenate, two strings using the + operator:
>>> string1 = "abra"
>>> string2 = "cadabra"
>>> magic_string = string1 + string2
>>> magic_string
'abracadabra'
In this example, the string concatenation occurs on the third line. You
concatenate string1 and string2 using +, and then you assign the result to the variable
magic_string. Notice that the two strings are joined
without any whitespace between them.
You can use string concatenation to join two related strings, such as
joining a first name and a last name into a full name:
>>> first_name = "Arthur"
>>> last_name = "Dent"
>>> full_name = first_name + " " + last_name
>>> full_name
'Arthur Dent'
Here, you use string concatenation twice on the same line. First, you
concatenate first_name with " " to ensure a space appears after the
first name in the final string. This produces the string "Arthur ", which
you then concatenate with last_name to produce the full name "Arthur
Dent".
String Slicing.

Suppose you need a string containing just the first three letters of the
string "fig pie". You could access each character by index and concatenate them like this:
>>> first_three_letters = flavor[0] + flavor[1] + flavor[2]
>>> first_three_letters
'fig'
If you need more than just the first few letters of a string, then getting each character individually
and concatenating them together is
clumsy and long-winded. Fortunately, Python provides a way to do
this with much less typing.
You can extract a portion of a string, called a substring, by inserting
a colon between two index numbers set inside square brackets like
this:
flavor = "fig pie"
print(flavor[0:3])
'fig'
flavor[0:3] returns the first three characters of the string assigned to
flavor, starting with the character at index 0 and going up to but not including the character at
index 3. The [0:3] part of flavor[0:3] is called
a slice. In this case, it returns a slice of "fig pie". Yum!
String slices can be confusing because the substring returned by
the slice includes the character whose index is the first number but
doesn’t include the character whose index is the second number.
To remember how slicing works, you can think of a string as a sequence of square slots. The left
and right boundaries of each slot are
numbered sequentially from zero up to the length of the string, and
each slot is filled with a character in the string.
Here’s what this looks like for the string "fig pie":
|f|i|g||p|i|e|
01234567
So, for "fig pie", the slice [0:3] returns the string "fig", and the slice
[3:7] returns the string " pie".
If you omit the first index in a slice, then Python assumes you want to
start at index 0:
>>> flavor[:3]
'fig'
The slice [:3] is equivalent to the slice [0:3], so flavor[:3] returns the
first three characters in the string "fig pie".
Similarly, if you omit the second index in the slice, then Python assumes you want to return the
substring that begins with the character whose index is the first number in the slice and ends with
the last character in the string:
>>> flavor[3:]
' pie'
For "fig pie", the slice [3:] is equivalent to the slice [3:7]. Since the
character at index 3 is a space, flavor[3:9] returns the substring that
starts with the space and ends with the last letter: " pie".
If you omit both the first and second numbers in a slice, you get a
string that starts with the character at index 0 and ends with the last
character. In other words, omitting both numbers in a slice returns
the entire string:
>>> flavor[:]
'fig pie'
It’s important to note that, unlike with string indexing, Python won’t
raise an IndexError when you try to slice between boundaries that fall
outside the beginning or ending boundaries of a string:
>>> flavor[:14]
'fig pie'
>>> flavor[13:15]
''
In this example, the first line gets the slice from the beginning of the
string up to but not including the fourteenth character. The string
assigned to flavor has a length of seven, so you might expect Python
to throw an error. Instead, it ignores any nonexistent indices and returns the entire string "fig
pie".
The third line shows what happens when you try to get a slice in which
the entire range is out of bounds. flavor[13:15] attempts to get the
thirteenth and fourteenth characters, which don’t exist. Instead of
raising an error, Python returns the empty string ("").
Note
The empty string is called empty because it doesn’t contain any
characters. You can create it by writing two quotation marks
with nothing between them:
empty_string = ""
A string with anything in it—even a space—is not empty. All the
following strings are non-empty:
non_empty_string1 = " "
non_empty_string2 = " "
non_empty_string3 = " "
Even though these strings don’t contain any visible characters,
they are non-empty because they do contain spaces.
Review Exercises
You can пnd the solutions to these exercises and many other bonus
resources online at [Link]/python-basics/resources
1. Create a string and print its length using len().
2. Create two strings, concatenate them, and print the resulting
string.
3. Create two strings, use concatenation to add a space between them,
and print the result.
4. Print the string "zing" by using slice notation to specify the correct
range of characters in the string "bazinga".
Review Exercises
1. Write a program that converts the following strings to lowercase:
"Animals", "Badger", "Honey Bee", "Honey Badger". Print each lowercase string on a separate
line.
2. Repeat exercise 1, but convert each string to uppercase instead of
Lowercase.
3. Write a program that removes whitespace from the following
strings, then print out the strings with the whitespace removed:
string1 = " Filet Mignon"
string2 = "Brisket "
string3 = " Cheeseburger "
4. Write a program that prints out the result of .startswith("be") on
each of the following strings:
string1 = "Becomes"
string2 = "becomes"
string3 = "BEAR"
string4 = " bEautiful"
5. Using the same four strings from exercise 4, write a program that
uses string methods to alter each string so that .startswith("be")
returns True for all of them.
4.4 Interact With User Input (as at 7th 02/2024)
In this section, you’ll learn how to get some input from a user with
input(). You’ll write a program that asks a user to input some text and
then displays that text back to them in uppercase.
Enter the following into IDLE’s interactive window:
>>> input()
>>> input()
Hello there!
'Hello there!'
To make input() a bit more user-friendly, you can give it a prompt to
display to the user. The prompt is just a string that you put between
the parentheses of input(). It can be anything you want: a word, a
symbol, a phrase—anything that is a valid Python string.
input() displays the prompt and waits for the user to type something.
When the user hits Enter , input() returns their input as a string that
can be assigned to a variable and used to do something in your program.
To see how input() works, type the following code into IDLE’s editor
window:
prompt = "Hey, what's up? "
user_input = input(prompt)
print("You said: " + user_input)
Press F5 to run the program. The text Hey, what's up? displays in the
interactive window with a blinking cursor.
The single space at the end of the string "Hey, what's up? " makes sure
that when the user starts to type, the text is separated from the prompt
with a space. When the user types a response and presses Enter , their
response is assigned to the user_input variable.
Once you have input from a user, you can do something with it. For
example, the following program takes user input, converts it to uppercase with .upper(), and
prints the result:
response = input("What should I shout? ")
shouted_response = [Link]()
print("Well, if you insist..." + shouted_response)
Review Exercises.
1. Write a program that takes input from the user and displays that
input back.
2. Write a program that takes input from the user and displays the
input in lowercase.
3. Write a program that takes input from the user and displays the
number of characters in the input.
Challenge: Pick Apart Your User’s Input
Write a program named first_letter.py that prompts the user for input with the string "Tell me
your password:". The program should then determine the first letter of the user’s input, convert
that letter to uppercase, and display it back.
For example, if the user input is "no", then the program should display the following output:
The first letter you entered was: N
For now, it’s okay if your program crashes when the user enters nothing as input—that is, when
they just hit Enter instead of typing something. You’ll learn a couple of ways to deal with this
situation in an upcoming chapter.
Review Exercises
You can пnd the solutions to these exercises and many other bonus
resources online at [Link]/python-basics/resources
1. Create a string containing an integer, then convert that string into
an actual integer object using int(). Test that your new object is
a number by multiplying it by another number and displaying theresult.
2. Repeat the previous exercise, but use a floating-point number and
float().
3. Create a string object and an integer object, then display them side
by side with a single print statement using str().
4. Write a program that uses input() twice to get two numbers from
the user, multiplies the numbers together, and displays the result.
If the user enters 2 and 4, then your program should print the
following text:
The product of 2 and 4 is 8.0.
Streamline Your Print Statements.
Suppose you have a string, name = "Zaphod", and two integers, heads
= 2 and arms = 3. You want to display them in the string "Zaphod has
2 heads and 3 arms". This is called string interpolation, which is
just a fancy way of saying that you want to insert some variables into
specific locations in a string.
One way to do this is with string concatenation:
>>> name + " has " + str(heads) + " heads and " + str(arms) + " arms"
'Zaphod has 2 heads and 3 arms'
This code isn’t the prettiest, and keeping track of what goes inside or
outside the quotes can be tough.

Python reserved words.


In Python, there are certain words that are reserved for specific purposes and cannot be used as
identifiers (such as variable names or function names) in your code. Here's a list of Python
reserved words:

These keywords have specific meanings in Python syntax and are used for control flow, defining
functions and classes, handling exceptions, and other language constructs. Trying to use any of
these words as variable names will result in a syntax error.
BASIC OPERATIONS AND BUILT IN FUNCTIONS IN PYTHON.
In Python, there are various basic operations and built-in functions that you can use for common
tasks. Here's a summary of some of the basic operations and commonly used built-in functions:

### Basic Operations:


1. **Arithmetic Operations**:
- Addition: `+`
- Subtraction: `-`
- Multiplication: `*`
- Division: `/`
- Floor Division: `//` (Returns the floor value of division)
- Modulus (Remainder): `%`
- Exponentiation: `**`
2. **Comparison Operators**:
- Equal to: `==`
- Not equal to: `!=`
- Greater than: `>`
- Less than: `<`
- Greater than or equal to: `>=`
- Less than or equal to: `<=`
3. **Assignment Operators**:
- Assignment: `=`
- Addition assignment: `+=`
- Subtraction assignment: `-=`
- Multiplication assignment: `*=`
- Division assignment: `/=`
- Modulus assignment: `%=`
- Exponentiation assignment: `**=`
- Floor division assignment: `//=`
4. **Logical Operators**:
- Logical AND: `and`
- Logical OR: `or`
- Logical NOT: `not`
5. **Membership Operators**:
- `in`: Evaluates to `True` if it finds a variable in the specified sequence.
- `not in`: Evaluates to `True` if it does not find a variable in the specified sequence.
6. **Identity Operators**:
- `is`: Evaluates to `True` if the variables on either side of the operator point to the same object.
- `is not`: Evaluates to `True` if the variables on either side of the operator do not point to the
same object.
### Built-in Functions:
1. **`print()`**: Print values to the standard output.
2. **`input()`**: Read a line from the input and returns it as a string.
3. **`Len()`**: Returns the length of an object (number of items in the object).
4. **`type()`**: Returns the type of an object.
5. **`int()`**, **`float()`**, **`str()`**, **`bool()`**: Convert values to integers, floating-point
numbers, strings, and Booleans respectively.
6. **`abs()`**: Returns the absolute value of a number.
7. **`max()`**, **`min()`**: Returns the maximum or minimum value among the arguments
passed.
8. **`sum()`**: Returns the sum of all elements in an iterable.
9. **`range()`**: Generates a sequence of numbers.
10. **`sorted()`**: Returns a new sorted list from the elements of any iterable.

CONTROL STRUCTURES IN PYTHON.


IF STAEMENTS IN PYTHON. (8TH, 02, 2024)
The if statement is a fundamental control flow structure in Python, allowing you to execute
different blocks of code based on conditions. It is used to make decisions in your code, enabling
you to control the flow of execution based on whether certain conditions are true or false.
1. **Basic Structure**:
- `if` statement checks a condition and executes a block of code if the condition is true.
- `else` statement is optional and executes a block of code if the condition in the `if` statement
is false.
2. **Syntax**:
The `if` statement is a fundamental control flow structure in Python, allowing you to execute
different blocks of code based on conditions. It is used to make decisions in your code, enabling
you to control the flow of execution based on whether certain conditions are true or false.
Key Points:
1. **Conditional Execution**:
- With the `if` statement, you can execute a block of code only if a specified condition is true.
If the condition evaluates to false, the code block is skipped.
2. **Syntax**:
- The basic syntax of the `if` statement consists of the `if` keyword followed by a condition,
which is an expression that evaluates to either `True` or `False`.
- The code block associated with the `if` statement is indented, typically by four spaces or a
tab.
3. **Optional `else` Clause**:
- In addition to the `if` statement, Python also provides an optional `else` clause, allowing you
to specify a block of code to execute if the condition in the `if` statement evaluates to false.
4. **Multiple Conditions with `elif`**:
- Python supports the `elif` (else if) statement, which allows you to check multiple conditions
sequentially after the initial `if` statement.
- This enables you to handle more complex decision-making scenarios where there are multiple
possible outcomes.
5. **Indentation**:
- Python uses indentation to define blocks of code. The code block following an `if`, `elif`, or
`else` statement must be indented consistently to be considered part of that statement.
6. **Nested `if` Statements**:
- You can nest `if` statements within each other to handle even more intricate decision-making
logic.
- However, excessive nesting can make code harder to read and understand, so it should be
used judiciously.
FOR LOOPS IN PYTHON. (12th ,02, 2024)

Syntax:

Iterable: An iterable is an object that can be iterated over, meaning it can be used in a for loop.
Common iterables include lists, tuples, dictionaries, strings, sets, and generators.
Iteration: During each iteration of the loop, the variable item (or whatever name you choose)
takes on the value of the next item in the iterable.
Range: The range() function is often used to generate a sequence of numbers that can be iterated
over. It takes parameters for the start, stop, and step values (with stop being exclusive). If only
one parameter is provided, it's treated as the stop value, with default start being 0 and default step
being 1.
Loop Control Statements:
break: Terminates the loop prematurely. It jumps out of the loop entirely, regardless of the
iteration.
continue: Skips the rest of the code inside the loop for the current iteration and proceeds to the
next iteration.
else clause: The else block in a for loop is executed if the loop completes normally (i.e., without
encountering a break statement).
EXAMPLES:
1. Write a python program that prints characters in a string one by one.
Solution:
message = “python coding is awesome”
for char in message:
print(char)

2. Write a python program that prompts user to enter a sting and the program then prints the
characters on that string sequentially.
In this program:

 The user is prompted to enter a string using the input() function.


 A for loop iterates over each character in the input string.
 Inside the loop, each character is printed individually.
3. Write a program that prints numbers from 1-10 using for loops.

Example 2 incase you want to print numbers without a restricted range.

Printing even numbers between 1-20

In this program:
The range () function generates a sequence of numbers from 2 to 20 (inclusive), with a step size
of 2. This ensures that only even numbers are included.
The for loop iterates over each even number generated by range (2, 21, 2).
Inside the loop, each even number is printed individually.
This program prints even numbers from 2 to 20.
Printing even numbers between 1-20 using for loop and if statement.

In this program:
The for loop iterates over each number in the range from 1 to 20 (inclusive).
Inside the loop, an if statement checks if the current number num is even. This is done by
checking if num modulo 2 equals 0, indicating that the number is divisible by 2 without a
remainder.
If the number is even, it is printed.
This program also prints even numbers from 2 to 20.
Assignment:
Write a python program that prints odd numbers between 0-50 using for loop.

FILE HANDLING.
File handling in Python involves operations such as opening files, reading from them, writing to
them, and closing them. Python provides built-in functions and methods to perform these
operations efficiently. Here's a basic overview of file handling in Python:

Opening Modes
When opening a file in Python, you specify a mode that determines how the file can be used.
'r': Open for reading (default).
'w': Open for writing, truncating the file first (creates the file if it doesn't exist).
'a': Open for writing, appending to the end of the file if it exists.
'b': Binary mode.
't': Text mode (default).
'+': Open for updating (reading and writing)
Opening a File
You can open a file using the open() function. It takes two arguments: the file name and the
mode in which you want to open the file (read, write, append, etc.).

Reading from a File


You can read from a file using various methods like read(), readline(), or readlines().
readline(): Reads a single line from the file.
readlines(): Reads all lines from the file and returns them as a list.

NB: Using Context Managers.


Using the with statement (context managers) is recommended as it ensures that the file is
properly closed, even if an exception occurs.
Writing to a File
You can write to a file using the write() method.

Closing a File
It's important to close the file after you've finished working with it to free up system resources.

Best Practices
Always close files after you're done with them.
Use context managers (with statement) for file operations to ensure proper resource
management.
Handle file operations within a try-except block to handle potential errors gracefully.

You might also like