Python Basics For Beginers
Python Basics For Beginers
1
Basics of Python for beginers
4. Conditional Statements
a. If statements
b. If-else statements
c. If-elif-else statements
5. Loops
a. While loops
b. For loops
c. Loop control statements (break, continue)
6. Dictionaries
a. Creating and manipulating dictionaries
b. Accessing values in a dictionary
c. Dictionary methods
7. Functions
a. Defining and calling functions
b. Parameters and arguments
c. Return values
9. File Input/Output
a. Reading from files
b. Writing to files
c. Using the "with" statement
2
Basics of Python for beginers
1. What is Python?
Python is a popular high-level programming language that is widely used in various domains such as
web development, data science, artificial intelligence, and automation. It was created by Guido van
Rossum and released in 1991. Python is known for its simplicity, readability, and ease of use. It is an
open-source language, which means that its source code is freely available for anyone to use and
modify.
Python supports multiple programming paradigms such as procedural, object-oriented, and functional
programming. It has a large standard library that provides pre-built modules and functions for various
tasks, which makes development faster and easier.
Ex-1:
print("Hello, World!")
Output:
Hello, World!
Description:
This code simply prints the string "Hello, World!" to the console. It's a traditional first program to write
in any programming language. The print() function in Python is used to print the specified message to
the console.
Ex-2:
num1 = 5
num2 = 7
Output:
Description:
This code demonstrates the use of variables in Python. We declare two integer variables num1 and
num2 and assign them the values 5 and 7, respectively. We then add the two variables and store the
result in a third variable sum. Finally, we use the print() function to display a message along with the
value of sum. Note that we can concatenate strings and variables using commas in the print() function.
3
Basics of Python for beginers
Programming is all about manipulating data. Data comes in different types, and it's important to
understand these types so that you can use them correctly in your programs. Three of the most
fundamental data types in Python are integers, floats, and strings.
Integers
An integer is a whole number. In Python, you can define an integer variable simply by assigning a
whole number to it. For example:
x=5
This creates a variable named x and assigns it the value of 5. You can perform arithmetic operations
on integers, such as addition, subtraction, multiplication, and division. For example:
x=5
y=3
z=x+y
print(z)
Output: 8
In this example, we define two integer variables, x and y, and then assign their sum to another integer
variable named z. Finally, we print out the value of z, which is 8.
a = 10
b=5
c=a+b
print(c)
Output: 15
In this example, we define two integer variables, a and b, and then assign their sum to another integer
variable named c. Finally, we print out the value of c, which is 15.
x=8
y=3
z=x*y
print(z)
Output: 24
4
Basics of Python for beginers
In this example, we define two integer variables, x and y, and then assign their product to another
integer variable named z. Finally, we print out the value of z, which is 24.
Floats
A float is a number with a decimal point. In Python, you can define a float variable by including a
decimal point in the number. For example:
x = 3.14
This creates a variable named x and assigns it the value of 3.14, which is a float. You can perform
arithmetic operations on floats just like you can with integers. For example:
x = 3.14
y = 2.5
z=x*y
print(z)
Output: 7.85
In this example, we define two float variables, x and y, and then assign their product to another float
variable named z. Finally, we print out the value of z, which is 7.85.
a = 3.14
b = 2.5
c=a+b
print(c)
Output: 5.64
In this example, we define two float variables, a and b, and then assign their sum to another float
variable named c. Finally, we print out the value of c, which is 5.64.
Addition
Addition is represented by the + symbol. Here's an example of adding two numbers together:
Ex-1 x=5
y=3
result = x + y
print(result)
Output: 8
5
Basics of Python for beginers
In the code above, we define two variables x and y, which are both integers. We then add them
together using the + operator and assign the result to a new variable called result. Finally, we print the
value of result.
Ex-2
x = 5.0
y = 3.2
result = x + y
print(result)
Output: 8.2
In the medium example, we define two variables x and y, which are both floating-point numbers. We
then add them together using the + operator and assign the result to a new variable called result.
Finally, we print the value of result.
Subtraction
Subtraction is represented by the - symbol. Here's an example of subtracting one number from
another:
Ex-1
x=5
y=3
result = x - y
print(result)
Output: 2
In the easy example, we define two variables x and y, which are both integers. We then subtract y
from x using the - operator and assign the result to a new variable called result. Finally, we print the
value of result.
Ex-2
x = 5.0
y = 3.2
result = x - y
print(result)
Output: 1.8
In the medium example, we define two variables x and y, which are both floating-point numbers. We
then subtract y from x using the - operator and assign the result to a new variable called result. Finally,
we print the value of result.
6
Basics of Python for beginers
Multiplication
Ex-1
x=5
y=3
result = x * y
print(result)
Output: 15
In the easy example, we define two variables x and y, which are both integers. We then multiply them
together using
Variables in Python
Variables are an essential part of programming. In Python, variables are used to store values that can
be used later in the program. The value of a variable can be changed as the program runs, making it a
useful tool for storing and manipulating data. In this lesson, we will learn the basics of variables in
Python, including how to declare and assign values to variables, and how to use them in your
programs.
x=5
In this example, we have declared a variable named "x" and assigned it a value of 5. Now we can use
the variable "x" in our program.
It's essential to note that in Python, you don't need to specify the data type of the variable when you
declare it. Python automatically determines the data type based on the value you assign to the
variable.
Assigning Values to Variables You can assign any value to a variable in Python, including strings,
integers, and floats. Here is an example:
x=5
y = "Hello, world!"
z = 3.14
In this example, we have assigned an integer value (5) to the variable "x," a string value ("Hello,
world!") to the variable "y," and a float value (3.14) to the variable "z"
Using Variables in Python Programs Once you have declared and assigned values to your variables,
you can use them in your Python programs. Here are a few examples:
7
Basics of Python for beginers
Ex-1
x=5
y=2
print(x + y)
Output: 7
In this example, we have declared two variables, "x" and "y," and assigned them integer values. We
then use these variables to perform a simple arithmetic operation (addition) and print the result to
the console.
Ex-2
x=5
y=2
z=x+y
print(z)
Output: 7
In this example, we have declared three variables, "x," "y," and "z," and assigned them integer values.
We then use "x" and "y" to perform an arithmetic operation (addition) and assign the result to "z."
Finally, we print the value of "z" to the console.
Conclusion Variables are an essential part of programming, and Python makes it easy to declare and
assign values to them. In this tutorial, we covered the basics of variables in Python, including how to
declare and assign values to variables, and how to use them in your programs. Remember that the
value of a variable can be changed as the program runs, making it a useful tool for storing and
manipulating data.
Lists and tuples are two of the most commonly used data structures in Python. Both of them are used
to store collections of items, but they have some differences in their behaviour. Lists are mutable,
which means that you can change their contents after they are created. Tuples are immutable,
which means that once you create them, you cannot change their contents. In this tutorial, we will
learn how to create and manipulate lists and tuples in Python.
Creating a List:
For example:
my_list = [1, 2, 3, 4, 5]
In this example, we have created a list named my_list that contains the integers 1 through 5.
8
Basics of Python for beginers
Creating a Tuple:
For example:
my_tuple = (1, 2, 3, 4, 5)
In this example, we have created a tuple named my_tuple that contains the integers 1 through 5.
You can access individual elements of a list or tuple by using indexing. The first element in the list or
tuple is at index 0, the second element is at index 1, and so on.
For example:
my_list = [1, 2, 3, 4, 5]
print(my_list[0])
Output: 1
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1])
Output: 2
You can also access a range of elements from a list or tuple by using slicing. Slicing is done by specifying
a start index and an end index separated by a colon (:). For example:
my_list = [1, 2, 3, 4, 5]
print(my_list[1:3])
Output: [2, 3]
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[2:])
Output: (3, 4, 5)
In this example, we have sliced my_list to get the second and third elements and sliced my_tuple to
get all the elements starting from the third element.
Modifying a List:
Lists are mutable, which means that you can change their contents after they are created. You can
add elements to a list using the append() method and remove elements from a list using the pop()
method.
For example:
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
9
Basics of Python for beginers
print(my_list)
Output: [1, 2, 3, 4, 5, 6]
my_list.pop(2)
print(my_list)
Output: [1, 2, 4, 5, 6]
In this example, we have added an element to my_list using the append() method and removed an
element from my_list using the pop() method.
Manipulating a Tuple: Tuples are immutable, which means that you cannot change their contents after
they are created. However, you can perform some operations on tuples like concatenation and
repetition. For example:
To access an element in a list or tuple, you need to use its index. The index of the first item in a list or
tuple is always 0, the second item is at index 1, and so on. You can access an item in a list or tuple by
enclosing the index of the item in square brackets [] immediately after the list or tuple.
Example 1
print(fruits[0])
Output: 'apple'
In this example, we have defined a list of fruits, and we are printing the first fruit in the list by accessing
it using its index, which is 0.
Example 2
Now let's move on to a slightly more complex example that demonstrates accessing elements in a
tuple:
t = (1, 2, 3, 4, 5)
print(t[2])
Output: 3
In this example, we have defined a tuple of integers, and we are printing the third element in the tuple
by accessing it using its index, which is 2.
10
Basics of Python for beginers
In addition to accessing individual elements in a list or tuple, you can also access a range of elements
using slicing. Slicing allows you to extract a subset of the items in a list or tuple, specified by a range
of indices.
To slice a list or tuple, you need to specify the starting index, the ending index (exclusive), and the step
size (optional). The slice will include all the elements from the starting index up to, but not including,
the ending index.
Example 1
print(fruits[1:3])
In this example, we have defined a list of fruits, and we are printing a slice of the list that includes the
second and third fruits, which are at indices 1 and 2, respectively.
Example 2
print(days_of_week[5])
Output: Saturday
Explanation: In this example, we have a tuple that contains the days of the week. We are accessing
the sixth element in the tuple using its index, which is 5. The output will be the string "Saturday".
In conclusion, understanding how to access elements within a list or tuple using indexing is an
important fundamental skill in Python programming. With practice, you will be able to manipulate and
access data more effectively in your programs.
In Python, there are built-in methods that you can use to manipulate lists and tuples. These methods
are functions that can be called on a list or tuple object and perform a specific task. In this tutorial, we
will go over some of the most commonly used list and tuple methods in Python.
fruits.append('orange')
print(fruits)
11
Basics of Python for beginers
Code 2: count()
The count() method returns the number of times a specified element appears in a list.
numbers = [1, 2, 3, 4, 2, 2, 3]
count = numbers.count(2)
print(count)
Output: 3
Code 3: index()
The index() method returns the index of the first occurrence of a specified element in a list.
index = fruits.index('banana')
print(index)
Output: 1
The extend() method adds the elements of a list (or any iterable) to the end of another list.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
Output: [1, 2, 3, 4, 5, 6]
Code 2: sort()
numbers = [4, 1, 6, 3, 9, 2]
numbers.sort()
print(numbers)
Output: [1, 2, 3, 4, 6, 9]
Code 3: reverse()
fruits.reverse()
print(fruits)
12
Basics of Python for beginers
If Statements in Python
The if statement is used to execute a block of code only if a certain condition is true. Here is the basic
syntax for an if statement in Python:
if condition:
Note that the code block to be executed if the condition is true is indented by four spaces.
Example 1:
Let's start with a simple example. In this program, we'll ask the user to input their age, and then we'll
tell them if they're old enough to vote.
Explanation:
We start by asking the user to enter their age. We use the input function to get the user's input, and
then convert it to an integer using the int function.
We use an if statement to check if the user's age is greater than or equal to 18. If the user's age is
greater than or equal to 18, we print a message telling them they're old enough to vote. If the user's
age is less than 18, we don't do anything.
Introduction
In programming, you may often need to perform different actions based on different conditions. This
is where conditional statements come into play. In Python, you can use if-else statements to execute
code based on certain conditions. An if-else statement allows you to execute a block of code if a
condition is true, and another block of code if the condition is false.
Syntax
13
Basics of Python for beginers
Example 1:
Let's start with a simple example to understand how if-else statements work in Python.
num = 5
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Explanation
In this example, we first define a variable num and assign it the value of 5. We then use an if-else
statement to check if the value of num is greater than or equal to 0. Since 5 is a positive number, the
condition is true and the program prints "Positive or Zero".
Example 2: Medium
age = 17
else:
Explanation
In this example, we first define a variable age and assign it the value of 17. We then use an if-else
statement to check if the value of age is greater than or equal to 18. Since 17 is less than 18, the
condition is false and the program prints "Sorry, you are not eligible to vote yet."
Conclusion
In conclusion, if-else statements are an important part of programming and can be used to execute
different blocks of code based on different conditions. They allow you to make your program more
flexible and adaptable to different situations.
14
Basics of Python for beginers
If-elif-else Statements
In programming, conditional statements are used to execute specific blocks of code based on certain
conditions. In Python, we can use if, if-else, and if-elif-else statements to achieve this.
The if-elif-else statement is used when there are more than two conditions to be evaluated. The if
statement evaluates a single condition and executes the code block if the condition is true. The if-else
statement evaluates a single condition and executes one code block if the condition is true and
another if it is false. The if-elif-else statement evaluates multiple conditions in a hierarchical manner
and executes the code block corresponding to the first condition that is true.
Example 1:
num = 15
Explanation: In this example, we have assigned the value 15 to the variable num. We then use an if-
else statement to evaluate whether num is greater than 10. Since 15 is greater than 10, the if condition
is true and the code block under the if statement is executed, which prints the message "The number
is greater than 10." If the condition had been false, the code block under the else statement would
have been executed instead, which prints the message "The number is less than or equal to 10."
else:
Explanation: In this example, we use the input() function to allow the user to enter a number. We
then use an if-elif-else statement to evaluate whether the number is positive, negative, or zero. The if
condition checks if the number is greater than 0. If it is, the code block under the if statement is
executed, which prints the message "The number is positive." If the first condition is false, the elif
condition checks if the number is less than 0. If it is, the code block under the elif statement is
executed, which prints the message "The number is negative." If both the if and elif conditions are
false, the else statement is executed, which prints the message "The number is zero."
15
Basics of Python for beginers
5. Introduction to Loops
Loops are an essential part of any programming language as they allow us to execute a set of
instructions multiple times, without having to write the same code repeatedly. There are two types of
loops in Python: the “while loop” and “for loop”
The while loop executes a set of instructions repeatedly as long as the given condition is true. It
continues to execute the code block until the condition becomes false. The syntax for the while loop
is as follows:
The condition is evaluated at the beginning of each iteration, and if it's true, then the statement(s)
inside the loop are executed. The loop continues until the condition becomes false.
Sample Code 1:
Easy Let's start with an easy example that prints numbers from 1 to 5 using a while loop:
count = 1
print(count) count += 1
In this code, we've initialized a variable count to 1, and the while loop runs as long as count is less than
or equal to 5. The print statement inside the loop prints the current value of count, and the count +=
1 statement increments the value of count by 1 at the end of each iteration.
Sample Code 2: Use a while loop to find the factorial of a number entered by the user. The factorial
of a number is the product of all positive integers less than or equal to that number. For example, the
factorial of 5 (written as 5!) is 5 * 4 * 3 * 2 * 1 = 120.
In this code, we're taking input from the user and storing it in the variable num. We've also initialized
a variable fact to 1. The while loop runs as long as num is greater than 0. Inside the loop, we're
multiplying the current value of fact by the current value of num and storing it back in fact. We're also
decrementing the value of num by 1 at the end of each iteration. Finally, we're printing the value of
fact, which gives us the factorial of the number entered by the user.
16
Basics of Python for beginers
For loops are used to iterate over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string) and execute a block of code for each element in the sequence. for variable in sequence: # code
to execute for each element. Here, the variable represents the current element in the sequence, and
the block of code that follows the colon (:) is executed for each element in the sequence.
Example 1
Let's start with an example. In this example, we will use a for loop to iterate over a list of numbers and
print out each number.
numbers = [1, 2, 3, 4, 5]
print(num)
Output: 1 2 3 4 5
In this example, we first define a list of numbers. We then use a for loop to iterate over each number
in the list, and print out the number.
Example - 2
Now let's move on to a medium example. In this example, we will use a for loop to iterate over a string
and count the number of vowels in the string.
vowels = "aeiou"
if char.lower() in vowels:
count += 1
In this example, we first define a string and a string of vowels. We then use a for loop to iterate over
each character in the string. For each character, we check if it is a vowel (using the in keyword to check
if it is in the vowels string), and if it is, we increment the count variable. Finally, we print out the total
number of vowels in the string.
Loop Control Statements are a set of statements that help control the flow of loops in Python. They
allow you to break out of a loop prematurely or skip certain iterations of a loop based on some
condition. The two most commonly used Loop Control Statements are break and continue.
break statement: The break statement is used to terminate the loop abruptly and transfer control to
the statement immediately following the loop.
17
Basics of Python for beginers
continue statement: The continue statement is used to skip over certain iterations of a loop based on
some condition, and proceed with the next iteration of the loop.
Sample Codes-1
Here are some examples of how you can use Loop Control Statements in Python. This program prints
the numbers from 1 to 5, but stops at 3 using the break statement.
for i in range(1,6):
if i == 4:
print(i)
Output: # 1 # 2 # 3
Sample Codes-2
This program prints the even numbers from 1 to 10, skipping odd numbers using the continue
statement.
for i in range(1,11):
if i % 2 == 1:
print(i)
# Output: # 2 # 4 # 6 # 8 # 10
6. Dictionaries
Introduction to Dictionaries:
A dictionary is a collection of key-value pairs. Each key is linked to a value, and you can use the key to
access the corresponding value. The keys in a dictionary must be unique, but the values can be
duplicated. Dictionaries are enclosed in curly braces {} and each key-value pair is separated by a colon
:.
Creating dictionaries is a fundamental skill in Python programming. Dictionaries allow us to store key-
value pairs and retrieve values based on their associated keys
Ex-1
In this level, we will create a simple dictionary with three key-value pairs.
# Creating a dictionary
18
Basics of Python for beginers
print(person)
Output:
Explanation: Here, we created a dictionary called person with three key-value pairs: "name" with a
value of "John", "age" with a value of 30, and "city" with a value of "New York". We printed the
dictionary using the print() function, which shows us the dictionary in curly braces with the key-value
pairs separated by commas.
Ex-2
In this level, we will create a dictionary with nested dictionaries as its values.
print(countries)
Output:
Explanation: Here, we created a dictionary called countries with three key-value pairs. The values of
each key are themselves dictionaries with two key-value pairs each. We printed the dictionary using
the print() function, which shows us the entire nested dictionary.
I hope this tutorial helps you understand the basics of creating dictionaries in Python. Dictionaries are
a powerful data structure that allow for efficient data retrieval and manipulation in Python
programming.
Dictionaries are an important data structure in Python. They are used to store key-value pairs, where
each key is associated with a value. In this tutorial,
Creating a Dictionary
Before we can manipulate a dictionary, we need to create one. Here's how to create a dictionary in
Python:
# Creating a dictionary
print(my_dict)
19
Basics of Python for beginers
This creates a dictionary called my_dict that contains three key-value pairs: 'apple': 1, 'banana': 2, and
'orange': 3.
To access the value associated with a particular key in a dictionary, we can use square brackets ([])
with the key name. Here's an example:
print(my_dict['apple'])
Output: 1
This code prints the value associated with the key 'apple', which is 1.
If the key does not exist in the dictionary, a KeyError will be raised. To avoid this, we can use the get()
method instead. The get() method returns None if the key is not found in the dictionary.
print(my_dict.get('pear'))
Output: None
This code attempts to access the value associated with the key 'pear', which does not exist in the
dictionary. The get() method returns None in this case.
To add a new key-value pair to a dictionary, we can simply assign a value to a new key:
my_dict['pear'] = 4
print(my_dict)
To update the value associated with an existing key, we can simply reassign the value to that key:
my_dict['banana'] = 4
print(my_dict)
20
Basics of Python for beginers
This code updates the value associated with the key 'banana' to 4.
To remove a key-value pair from a dictionary, we can use the del statement:
del my_dict['banana']
print(my_dict)
7. Functions
Introduction
Functions are a key concept in programming that allow you to encapsulate a piece of code and reuse
it whenever you need it. Functions take input arguments, perform a specific task, and then return
output results. They help to make your code more modular, organized, and easier to read and
maintain.
Defining a Function
To define a function in Python, you use the def keyword followed by the function name and any input
parameters in parentheses. Then you indent the code block that defines what the function does. Here
is the basic structure:
def function_name(param1, param2, ...): # function code goes here return result
The function name should be descriptive of what the function does. The input parameters are optional
and you can have as many as you need. The code block inside the function should perform a specific
task or set of tasks, and the return keyword is used to send the result of the function back to the caller.
Calling a Function
To call a function in Python, you simply use the function name followed by any input arguments in
parentheses. Here is the basic structure:
The arguments you pass to the function should match the parameters defined in the function
definition. When the function is called, it will execute the code inside the function and return the
result, which can be stored in a variable or used in further calculations.
Now let's look at some examples of defining and calling functions in Python.
21
Basics of Python for beginers
Ex-1
In this easy example, we will define a function that takes two numbers as input and returns their sum.
print(result)
Output: 7
Explanation: We define a function called add_numbers that takes two input parameters num1 and
num2. The function computes their sum and returns the result. Then we call the function with the
arguments 3 and 4 and store the result in a variable called result. Finally, we print the value of result,
which is 7.
Ex-2
In this medium example, we will define a function that takes a list of numbers as input and returns the
average of those numbers.
def compute_average(numbers):
total = sum(numbers)
result = compute_average(data)
print(result)
Output: 5.6
Explanation: We define a function called compute_average that takes a list of numbers as input
parameter numbers. The function computes the sum of the numbers using the sum function, and then
divides by the length of the list to get the average. The result is returned by the function. Then we
create a list of numbers called data and call the function with data as the argument. The returned
result is stored in a variable called result. Finally, we print the value of result, which is 5.6.
Introduction: Functions are one of the most important concepts in programming, and they allow you
to write reusable code. Parameters and arguments are an essential part of functions, and they allow
you to pass data to the function or receive data from the function.
Parameters and arguments are related concepts, but they have different meanings. A parameter is a
variable in the function definition, whereas an argument is the actual value passed to the function
when it is called.
22
Basics of Python for beginers
Example:1
Let's start with a simple example of a function with a parameter. In this example, we will create a
function that takes a name as a parameter and returns a greeting message.
def greet(name):
print(greet("Alex"))
Explanation: Here, we have defined a function named greet which takes a parameter called name.
The function returns a greeting message which includes the name of the person passed as an
argument.
In the print statement, we have called the greet function and passed the argument "Alex". The
function has returned the greeting message "Hello, Alex! Welcome to Python Programming.".
Example:2
In this example, we will create a function that takes two numbers as parameters and returns their
sum.
Explanation: In this example, we have defined a function named add_numbers that takes two
parameters num1 and num2. Inside the function, we have added num1 and num2 and stored the
result in a variable called sum. Then, we have returned the value of sum.
In the print statement, we have called the add_numbers function and passed the arguments 10 and
20. The function has returned the sum of the two numbers, which is 30.
Return a value
Introduction: Functions are blocks of code that perform specific tasks and return results. Return
statement is used to return a value from a function. This value can be used in other parts of the
program.
23
Basics of Python for beginers
return statement is used to return a value from the function. If there is no value to return, it can be
omitted.
Example:1
sum = a + b
return sum
print(result)
Output: 15
In this example, we define a function add_numbers that takes two parameters a and b. The function
adds the values of a and b and stores the result in a variable sum. The function then returns the value
of sum. We call this function by passing the values 5 and 10 to it, and store the returned value in a
variable result. We then print the value of result, which is 15.
Example:2
def find_max(numbers):
result = find_max(numbers)
print(result)
Output: 10
In this example, we define a function find_max that takes a list of numbers as a parameter numbers.
The function initializes a variable max with the first number in the list. It then iterates over the
remaining numbers in the list and checks if each number is greater than the current value of max. If it
is, then the value of max is updated. Finally, the function returns the value of max. We call this function
by passing a list of numbers to it, and store the returned value in a variable result. We then print the
value of result, which is the maximum number in the list.
24
Basics of Python for beginers
print(math.sqrt(25))
Output: 5.0
print(math.pow(2, 3))
Output: 8.0
Explanation: In this code, we imported the math module using the import keyword. After that, we
used the functions sqrt() and pow() from the math module to calculate the square root of 25 and 2
raised to the power of 3, respectively.
Example : 2
import random
print(random.randint(1, 10))
Explanation: In this code, we imported the random package using the import keyword. The random
package provides various functions for generating random numbers. We used the randint() function
from the random package to generate a random number between 1 and 10 (inclusive).
In this part, we will learn about creating our own modules and packages in Python. A module is a file
containing Python definitions and statements, while a package is a collection of modules placed in a
directory hierarchy.
Creating a module is simple. We can create a file with a .py extension and add Python code to it. Here's
an example:
def greet(name):
print(f"Hello, {name}!")
import mymodule
mymodule.greet("Alice")
25
Basics of Python for beginers
Explanation: We have created a module named mymodule that contains a single function named
greet. This function takes a parameter name and prints a greeting message to the console. To use this
module, we import it using the import statement and call the greet function with a name parameter.
Creating a package is similar to creating a module. We can create a directory with an __init__.py file
and add one or more module files to it. Here's an example:
Example:
mypackage/__init__.py:
mypackage/mymodule.py:
def greet(name):
print(f"Hello, {name}!")
import mypackage
mypackage.greet("Alice")
Explanation: We have created a package named mypackage that contains a single module named
mymodule. The __init__.py file imports the greet function from the mymodule module, making it
available when we import the package. To use this package, we import it using the import statement
and call the greet function with a name parameter.
Python comes with a standard library, which includes a variety of modules and packages that can be
imported and used in your programs. However, there are also many external modules and packages
available that can be installed and used in your Python programs. In this tutorial, we will explore how
to use external modules and packages in your Python programs.
The "math" module is a built-in module that provides access to a variety of mathematical functions
and constants in Python. In this example, we will use the "math" module to calculate the square root
of a number.
import math
x = 16 sqrt_
x = math.sqrt(x)
26
Basics of Python for beginers
Explanation:
The "requests" module is an external module that allows you to send HTTP/1.1 requests using Python.
In this example, we will use the "requests" module to retrieve the HTML content of a web page.
response = requests.get(url)
print(response.content)
9. File Input/Output
File Input/Output (I/O) operations are essential for any programming language. In Python, I/O
operations can be performed on files using built-in functions like open(), read(), write(), and close().
Python supports various file types, including text, binary, and JSON files. In this tutorial, we will learn
about basic file I/O operations and different modes used for file handling.
Sample Code 1
The first sample code is a simple program that reads a file and displays its contents on the console.
makefileCopy code
contents = file.read()
print(contents)
file.close()
Explanation:
27
Basics of Python for beginers
We first use the open() function to open the file sample.txt in read mode ("r"). We then read the
contents of the file using the read() function and store them in the contents variable. Finally, we print
the contents of the file on the console and close the file using the close() function.
Sample Code 2
The second sample code is a program that reads a text file, makes some modifications, and writes the
modified content to a new file.
contents = file.read()
file.close()
file.write(new_contents)
file.close()
Explanation:
We first use the open() function to open the file sample.txt in read mode ("r").
We then read the contents of the file using the read() function and store them in the contents
variable.
We close the file using the close() function.
We modify the contents of the file by replacing the word "random" with "sample" and store
it in a new variable new_contents.
We use the open() function to open a new file new_sample.txt in write mode ("w").
We write the modified contents of the file to the new file using the write() function.
We close the file using the close() function.
Finally, we print a success message on the console.
28
Basics of Python for beginers
Introduction: File input/output (I/O) is an important part of programming in Python. The "with"
statement provides a simpler way to work with files than the traditional method. It ensures that a file
is closed when the block inside the "with" statement is exited. This is helpful in preventing errors and
in ensuring that resources are not wasted.
Example: 1
In this example, we'll create a new file and write some text to it using the "with" statement.
f.write('Hello, world!')
Explanation:
with open('newfile.txt', 'w') as f: creates a new file called "newfile.txt" and opens it in write mode. It
also creates a file object called "f" that we can use to write to the file.
f.write('Hello, world!') writes the string "Hello, world!" to the file using the file object "f".
This code will create a new file called "newfile.txt" in the current directory (where the Python file is
located) and write the string "Hello, world!" to it.
Example:2
In this example, we'll read the contents of a file using the "with" statement.
file_contents = f.read()
print(file_contents)
Explanation:
with open('example.txt', 'r') as f: opens the file "example.txt" in read mode and creates a file
object called "f".
file_contents = f.read() reads the contents of the file using the file object "f" and stores it in
the variable "file_contents".
print(file_contents) prints the contents of the file to the console.
Output:
Assuming the file "example.txt" contains the text "This is an example file.", the output of this
code will be:
This is an example file.
29