0% found this document useful (0 votes)
147 views

Python Basics For Beginers

The document provides an overview of basic Python concepts for beginners. It covers topics like installing Python, basic data types like integers and strings, arithmetic operations, variables, lists and tuples, conditional statements, loops, dictionaries, functions, modules, file input/output, and mini projects. The document contains examples to demonstrate concepts like defining variables, performing arithmetic, accessing list elements, and using conditional and loop statements.

Uploaded by

jjsalam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
147 views

Python Basics For Beginers

The document provides an overview of basic Python concepts for beginners. It covers topics like installing Python, basic data types like integers and strings, arithmetic operations, variables, lists and tuples, conditional statements, loops, dictionaries, functions, modules, file input/output, and mini projects. The document contains examples to demonstrate concepts like defining variables, performing arithmetic, accessing list elements, and using conditional and loop statements.

Uploaded by

jjsalam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Basics of Python for beginers

1
Basics of Python for beginers

Basics of Python Program


1. Introduction to Python
a. What is Python?
b. Installing Python on your computer
c. Your first Python program

2. Basic Data Types in Python


a. Integers, floats, and strings
b. Basic arithmetic operations
c. Variables

3. Lists and Tuples


a. Creating and manipulating lists and tuples
b. Accessing elements in a list or tuple
c. List and tuple methods

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

8. Modules and Packages


a. Importing modules and packages
b. Creating your own modules and packages
c. Using external modules and packages

9. File Input/Output
a. Reading from files
b. Writing to files
c. Using the "with" statement

10. Mini Projects


a. Simple programs that incorporate the concepts learned in the previous lessons.

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.

Now, let's take a look at some sample code snippets in Python:

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

sum = num1 + num2

print("The sum of", num1, "and", num2, "is:", sum)

Output:

The sum of 5 and 7 is: 12

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

2. Basic Data Types in Python


Introduction

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.

Ex-1 # easy example

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.

Ex-2 # medium example

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.

Ex-1 # easy example

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.

Basic arithmetic operations.


Python has a number of built-in arithmetic operators that you can use to perform basic calculations.
These include addition, subtraction, multiplication, division, and modulus.

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

Multiplication is represented by the * symbol. Here's an example of multiplying two numbers


together:

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.

Declaring Variables in Python Declaring a variable in Python is a straightforward process. To declare a


variable, you simply need to give it a name and assign a value to it using the equals (=) operator. Here
is an example:

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.

3. Lists and tuples


Introduction:

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:

A list is created by enclosing a comma-separated sequence of elements in square brackets ([]).

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:

A tuple is created by enclosing a comma-separated sequence of elements in parentheses ().

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.

Accessing Elements in a List or Tuple:

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

Slicing a List or Tuple:

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:

Accessing elements in a list or tuple


A list or tuple is a collection of items in Python. Each item in a list or tuple is assigned a unique index
starting from 0, which can be used to access the item. In this tutorial, we will learn how to access
elements in a list or tuple.

Accessing Elements by Index

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

Let's start with an easy example to demonstrate accessing elements in a list:

fruits = ['apple', 'banana', 'cherry', 'orange']

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

Accessing Elements by Slicing

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

Let's start with an easy example to demonstrate slicing a list:

fruits = ['apple', 'banana', 'cherry', 'orange']

print(fruits[1:3])

Output: ['banana', 'cherry']

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

# Accessing elements in a tuple

days_of_week = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday",


"Saturday", "Sunday")

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.

List and Tuple Methods

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.

Ex-1 : Code 1: append()

The append() method adds an element to the end of a list.

fruits = ['apple', 'banana', 'cherry']

fruits.append('orange')

print(fruits)

11
Basics of Python for beginers

Output: ['apple', 'banana', 'cherry', 'orange']

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.

fruits = ['apple', 'banana', 'cherry']

index = fruits.index('banana')

print(index)

Output: 1

Ex-2- Code 1: extend()

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()

The sort() method sorts the elements of a list in ascending order.

numbers = [4, 1, 6, 3, 9, 2]

numbers.sort()

print(numbers)

Output: [1, 2, 3, 4, 6, 9]

Code 3: reverse()

The reverse() method reverses the order of the elements in a list.

fruits = ['apple', 'banana', 'cherry']

fruits.reverse()

print(fruits)

12
Basics of Python for beginers

Output: ['cherry', 'banana', 'apple']

4. What are Conditional Statements?


Conditional statements, also known as decision-making statements, allow us to execute different sets
of instructions depending on whether a certain condition is true or false. The most common
conditional statement in Python is the if statement.

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:

# code to execute if condition is true

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.

age = int(input("Please enter your age: "))

if age >= 18:

print("You are 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.

If-else Statements in Python

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

The syntax for an if-else statement in Python is as follows:

if condition: # code to execute if the condition is true

else: # code to execute if the condition is false

13
Basics of Python for beginers

Example 1:

Let's start with a simple example to understand how if-else statements work in Python.

# Program to check if a number is positive or negative

num = 5

if num >= 0:

print("Positive or Zero")

else:

print("Negative number")

Output : Positive or Zero

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

# Program to check if a person is eligible to vote

age = 17

if age >= 18:

print("You are eligible to vote!")

else:

print("Sorry, you are not eligible to vote yet.")

Output : Sorry, you are not eligible to vote yet.

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.

Now let's look at some examples of if-elif-else statements in Python.

Example 1:

num = 15

if num > 10:

print("The number is greater than 10.")

else: print("The number is less than or equal to 10.")

Output: The number is greater than 10.

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."

Example 2: num = int(input("Enter a number: "))

if num > 0: print("The number is positive.")

elif num < 0: print("The number is negative.")

else:

print("The number is zero.")

Output: Enter a number: 7 The number is positive.

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

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:

while condition: statement(s)

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

while count <= 5:

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.

num = int(input("Enter a number: "))

fact = 1 while num > 0:

fact *= num num -= 1

print("Factorial of the number:", fact)

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

Introduction to For Loops

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]

for num in numbers:

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.

string = "Hello, World!"

vowels = "aeiou"

count = 0 for char in string:

if char.lower() in vowels:

count += 1

print("Number of vowels:", count)

Output: Number of vowels: 3

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.

Introduction to Loop Control Statements

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.

# using break statement

for i in range(1,6):

if i == 4:

break # stop loop when i is equal to 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.

# using continue statement

for i in range(1,11):

if i % 2 == 1:

continue # skip odd numbers

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

person = {"name": "John", "age": 30, "city": "New York"}

18
Basics of Python for beginers

# Printing the dictionary

print(person)

Output:

{'name': 'John', 'age': 30, 'city': 'New York'}

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.

# Creating a dictionary with nested dictionaries

countries = { "USA": {"capital": "Washington, D.C.", "population": 328.2}, "China":


{"capital": "Beijing", "population": 1393}, "India": {"capital": "New Delhi",
"population": 1366} }

# Printing the dictionary

print(countries)

Output:

{'USA': {'capital': 'Washington, D.C.', 'population': 328.2}, 'China': {'capital': 'Beijing',


'population': 1393}, 'India': {'capital': 'New Delhi', 'population': 1366}}

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.

Manipulating Dictionaries in Python

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

my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

print(my_dict)

Output: {'apple': 1, 'banana': 2, 'orange': 3}

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.

Accessing Values in a Dictionary

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:

# Accessing values in a dictionary

my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

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.

# Using the get() method to access values

my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

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.

Adding and Updating Items in a Dictionary

To add a new key-value pair to a dictionary, we can simply assign a value to a new key:

# Adding a new key-value pair to a dictionary

my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

my_dict['pear'] = 4

print(my_dict)

Output: {'apple': 1, 'banana': 2, 'orange': 3, 'pear': 4}

This code adds a new key-value pair, 'pear': 4, to the dictionary.

To update the value associated with an existing key, we can simply reassign the value to that key:

# Updating the value of a key in a dictionary

my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

my_dict['banana'] = 4

print(my_dict)

Output: {'apple': 1, 'banana': 4, 'orange': 3}

20
Basics of Python for beginers

This code updates the value associated with the key 'banana' to 4.

Removing Items from a Dictionary

To remove a key-value pair from a dictionary, we can use the del statement:

# Removing a key-value pair from a dictionary

my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

del my_dict['banana']

print(my_dict)

Output: {'apple': 1, 'orange': 3}

This code removes the key

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:

function_name(arg1, arg2, ...)

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.

def add_numbers(num1, num2):

sum = num1 + num2

return sum result = add_numbers(3, 4)

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)

average = total / len(numbers)

return average data = [2, 5, 8, 10, 3]

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.

Parameters and arguments

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):

return f"Hello, {name}! Welcome to Python Programming." #calling the


function

print(greet("Alex"))

Output: Hello, Alex! Welcome to Python Programming.

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.

def add_numbers(num1, num2):

sum = num1 + num2

return sum #calling the function

result = add_numbers(10, 20)

print("The sum of 10 and 20 is:", result)

Output: The sum of 10 and 20 is: 30

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.

Syntax: def function_name(parameters): statement(s) return expression

def keyword is used to define a function

function_name is the name of the function

23
Basics of Python for beginers

parameters are the values passed to the function

statement(s) is the block of code that performs some task

return statement is used to return a value from the function. If there is no value to return, it can be
omitted.

Example:1

def add_numbers(a, b):

sum = a + b

return sum

result = add_numbers(5, 10)

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):

max = numbers[0] for num in numbers:

if num > max: max = num

return max numbers = [5, 10, 2, 8, 3]

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.

8. Modules and Packages


Introduction: Python provides a variety of modules and packages for extending the functionality of
the programming language. To use these modules and packages in our Python programs, we need to
import them. In this tutorial, we will learn how to import modules and packages in Python.

Example : 1 The following is a simple example of importing a module in Python:

24
Basics of Python for beginers

# Importing math module

import math # Using functions from math module

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

The following is an example of importing a package in Python:

# Importing the random package

import random

# Using functions from the random package

print(random.randint(1, 10))

Output: Random number between 1 and 10 (inclusive)

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).

Creating Your Own Modules and Packages in Python

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 and importing a module

Creating a module is simple. We can create a file with a .py extension and add Python code to it. Here's
an example:

Example : 1 Create a file named mymodule.py with the following code:

def greet(name):

print(f"Hello, {name}!")

To use this module, we can import it using the import statement:

import mymodule

mymodule.greet("Alice")

25
Basics of Python for beginers

Output: Hello, Alice!

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 and importing a package

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:

Create a directory named mypackage with the following files:

mypackage/__init__.py:

from .mymodule import greet

mypackage/mymodule.py:

def greet(name):

print(f"Hello, {name}!")

To use this package, we can import it using the import statement:

import mypackage

mypackage.greet("Alice")

Output: Hello, 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.

Using external modules and packages

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.

Easy Example: Using the "math" module

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)

print("The square root of", x, "is", sqrt_x)

26
Basics of Python for beginers

Output: The square root of 16 is 4.0

Explanation:

 We first import the "math" module using the "import" statement.


 We then assign the value 16 to the variable "x".
 We use the "sqrt" function from the "math" module to calculate the square root of "x" and
assign it to the variable "sqrt_x".
 We print out the result using the "print" statement.

Example: Using the "requests" module

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.

import requests url = "https://www.google.com"

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

# Open the file in read mode

file = open("sample.txt", "r")

# Read the contents of the file

contents = file.read()

# Print the contents of the file

print(contents)

# Close the file

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.

# Open the file in read mode

file = open("sample.txt", "r")

# Read the contents of the file

contents = file.read()

# Close the file

file.close()

# Modify the contents of the file

new_contents = contents.replace("random", "sample")

# Open the file in write mode

file = open("new_sample.txt", "w")

# Write the modified contents to the new file

file.write(new_contents)

# Close the file

file.close()

# Print a success message

print("File written successfully!")

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.

Using the "with" statement

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.

with open('newfile.txt', 'w') as f:

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.

with open('example.txt', 'r') as f:

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

You might also like