0% found this document useful (0 votes)
16 views21 pages

Advpython Chapter 1

Chapter One provides a comprehensive overview of Python programming concepts, including lists, dictionaries, functions, and modules. It explains how to manipulate lists and dictionaries, create and call functions, and utilize Python modules for code organization. Additionally, the chapter introduces Git as a version control system, detailing its structure and initialization process.

Uploaded by

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

Advpython Chapter 1

Chapter One provides a comprehensive overview of Python programming concepts, including lists, dictionaries, functions, and modules. It explains how to manipulate lists and dictionaries, create and call functions, and utilize Python modules for code organization. Additionally, the chapter introduces Git as a version control system, detailing its structure and initialization process.

Uploaded by

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

Chapter One

Python Refresher

1.1 Lists in Python


 The list is a sequence data type which is used to store the collection of data.
 A list is like a box where you can put lots of stuff, like numbers or words, and keep
them together.
 You can use square brackets to s [] to make a list. Put the stuff inside brackets,
separating them with commas.
Example

Students = [ ‘ Mohamed ’ , ‘ahmed’ , ‘jama’ , ‘ismail’ , ‘asha’]

 Each element in the list has a number that shows where it is. We call this number the
index. But remember, we start counting from 0 . So, to get the first thing in the list,
you use Students[0], and for the second thing, you use Students[1], and so on.
Changing The Value Of An Element In The List
We can change the value of an element in a list by assigning a new value to that element
using its index

Students = [ ‘ Mohamed ’ , ‘ahmed’ , ‘jama’ , ‘ismail’ , ‘asha’]


print("Original list:", Students)

# Change the value of the element at index 2 from ismail to suleiman


Students[2] = ‘suleiman’
print("Updated list after changing value:", Students)

Output

Original list: [ ‘ Mohamed ’ , ‘ahmed’ , ‘jama’ , ‘ismail’ , ‘asha’]


Updated list after changing value: [ ‘ Mohamed ’ , ‘ahmed’ , ‘jama’ , ‘suleiman’ ,
‘asha’]
Adding a new value to the list:
We can add a new value to the end of a list using the .append() method. :

Students = [ ‘ Mohamed ’ , ‘ahmed’ , ‘jama’ , ‘ismail’ , ‘asha’]


print("Original list:", Students)

# Add a new value (‘faadumo’) to the end of the list

[Link](‘faadumo’)

print("Updated list after adding new value:",Students)

Output:

Original list: [ ‘ Mohamed ’ , ‘ahmed’ , ‘jama’ , ‘ismail’ , ‘asha’]


Updated list after adding new value: [ ‘ Mohamed ’ , ‘ahmed’ , ‘jama’ , ‘ismail’ , ‘asha’ , ‘faadumo’]
Deleting an element using .remove():
You can delete a specific value from the list using the .remove() method. It removes the first
occurrence of the specified value. Here's an example:

Students = [ ‘ Mohamed ’ , ‘ahmed’ , ‘jama’ , ‘ismail’ , ‘asha’]


print("Original list:", Students)

# Remove the value ‘ahmed’ from the list


[Link](‘ahmed’)

print("Updated list after removing value using remove():", Students)

Output:

Original list: [ ‘ Mohamed ’ , ‘ahmed’ , ‘jama’ , ‘ismail’ , ‘asha’]


Updated list after removing value using remove(): [ ‘ Mohamed ’ , ‘jama’ , ‘ismail’ ,
‘asha’]
Deleting an element using .pop():
You can remove and return an element from a specific index using the .pop() method. If you
don't specify an index, it removes and returns the last element.

Students = [ ‘ Mohamed ’ , ‘ahmed’ , ‘jama’ , ‘ismail’ , ‘asha’]


print("Original list:", Students)

# Remove and return the element at index 2


removed element = [Link](2)

print("Removed element:", removed_element)


print("Updated list after removing value using pop():", Students)

Output:

Original list: [ ‘ Mohamed ’ , ‘ahmed’ , ‘jama’ , ‘ismail’ , ‘asha’]


Removed element: jama
Updated list after removing value using pop(): [ ‘ Mohamed ’ , ‘ahmed’ , ‘ismail’ , ‘asha’]
Getting the Elements of the List using For Loop
We can get the elements of the list by using for loop:

Students = [ ‘ Mohamed ’ , ‘ahmed’ , ‘jama’ , ‘ismail’ , ‘asha’]


For student in Students :
Print(student)

Output

Mohamed
Ahmed
Jama
Ismail
asha
• Exercise(3 Marks)

Create a list named fruits and add three fruits to it using the .append() method.
After that, print the list.

Given the list of numbers below, change the third element in the list to the
number 10. Print the list before and after the change.
numbers = [1, 2, 3, 4, 5]

You have a list colors containing several colors. Use a for loop to print each color
in the list.
colors = ["red", "blue", "green", "yellow"]
1.2 Dictionaries in Python
 Dictionaries in Python are powerful data structures that allow you to store data as key-value pairs. They are
incredibly useful when you need to associate keys with values, and you can retrieve, modify, or delete items
based on the key.
Characteristics of Dictionaries
 Mutable: You can change, add, or remove items after the dictionary is created.
 Unordered: Items in a dictionary are not stored in any particular order. This means you cannot access
items by index like you do in lists.
 Dynamic: They can grow and shrink as needed.
 Indexed by Keys: Instead of using numerical indexes, dictionaries use keys. Keys must be of an
immutable type (such as strings, numbers, or tuples that contain only immutable items) and must be
unique within a dictionary.
 Values: Values can be of any type and can be repeated across different keys in the dictionary.
Basic Syntax
Students = {
1 : ‘jama’ ,
2 : ‘ismail’,
3: ‘aamina’
}
Accessing Items
We can access the value associated with a specific key using square brackets [] or the get() method
value1 = Students[1] # Raises an error if key does not exist
value1_safe = [Link](1) # Returns None if key does not exist

• Adding and Modifying Items


To add a new key-value pair, assign a value to a new key. If the key already exists, this will modify the
value:

Students[4] = ‘mohamed' # Adds a new key-value pair


Students[1] = 'new_value' # Modifies the value of an existing key

Removing Items
You can remove items using the del statement or the pop() method:

del Students[1] # Removes the key 1 and its value

popped_value = [Link](1) # Removes the key 1 and returns it’s value


1.3 Functions
Python Functions is a block of statements that return the specific task. The idea is to put
some commonly or repeatedly done tasks together and make a function so that instead of
writing the same code again and again for different inputs, we can do the function calls to
reuse code contained in it over and over again.
Some Benefits of Using Functions
 Increase Code Readability
 Increase Code Reusability

The syntax to declare a function is:


Types of Functions
Built-in library function: These are Standard functions in Python that are available to
use.
User-defined function: We can create our own functions based on our requirements.
Creating a Function in Python
We can define a function in Python, using the def keyword. We can add any type of
functionalities and properties to it as we require.
By the following example, we can understand how to write a function in Python. In this
way we can create Python function definition by using def keyword.

def greating():
print(‘hello student.’)
Calling a Function in Python
After creating a function in Python we can call it by using the name of the functions Python followed by
parenthesis containing parameters.
greating()

Function with Parameters


When you define a function, parentheses are used to enclose the function's parameters. These
parameters are variables that act as placeholders for the values that you pass to the function when
you call it.

def say_hello(name):

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

• In this example:
say_hello is the function name.
name is the parameter inside the parentheses. This function takes one parameter, which
means it expects you to provide one piece of data when you call it.
Function Call With Parameters
When you call a function, you use its name followed by parentheses. Inside these
parentheses, you provide the arguments to the function, which are the actual values that
replace the parameters inside the function during its execution. If the function requires
parameters, you must include the appropriate arguments in the same order as the
parameters were defined.
say_hello(“Jama")
• In this call:
“Jama" is the argument that is passed to the say_hello function. The string “Jama" takes the place of the
name parameter inside the function.

Examples of Functions
1.
def oddOrEven(x):
if x % 2 == 0 :
return f"{x} is Odd"
else :
return f'{x} is Even'

print(oddOrEven(37))
2.
Calculating The Area of a Circle
import math
def calculate_circle_area(radius):

area = [Link] * radius ** 2


return area
Python Modules
In Python, a module is a file containing Python definitions, functions, and statements. It serves
as a way to organize and reuse code. Modules can be used to break down a large program
into smaller, more manageable parts, making it easier to understand, maintain, and
collaborate on code
Importing Modules
To use a module in Python, you need to import it into your program.
1. Import the entire module
import math
2. Importing specific items from the module
from math import sqrt , pi
3. Importing module with shortname
import numby as np
Using Modules
Once a module is imported, you can use its functions, objects, and variables in your code. You
access these items using dot notation, which combines the module name and the item name

import math

radius = 5
area = [Link] * [Link](radius, 2)
print("The area of the circle is:", area)

In this example, we import the math module, access the value of pi using [Link], and
calculate the area of a circle using the pow function from the math module.
Creating Your Own Modules
 Aside from using built-in modules, you can also create your own modules to organize and package
code. To create a module, you simply save your Python code in a file with a .py extension.
 For example, let's create a module named my_module.py that contains a function to tells if number is odd or
even
#my_module.py
Def oddorEven(x):
If x %2 ==0:
Return True
Else:
Return False

Now, you can import and use this module in another Python script:
import my_module
X = my_module.oddorEven(5)
print(x)
In this case, we import our custom module my_module and call the oddoreven function defined within it.
Introduction to Git
Git is a distributed version control system.
 A version Control system is a system that maintains different versions of your project when
we work in a team or as an individual. (system managing changes to files) As the project
progresses, new features get added to it. So, a version control system maintains all the
different versions of your project for you and you can roll back to any version you want
without causing any trouble to you for maintaining different versions by giving names to it like
MyProject.
Distributed Version control system means every collaborator(any developer working on a team
project)has a local repository of the project in his/her local machine unlike central where team
members should have an internet connection to every time update their work to the main
central repository.
So, by distributed we mean: the project is distributed. A repository is an area that keeps all
your project files, images, etc. In terms of Github: different versions of projects correspond to
commits.
Git Repository Structure
It consists of 4 parts:

1. Working directory: This is your local directory where you make the project (write code) and
make changes to it.
2. Staging Area (or index): this is an area where you first need to put your project before
committing. This is used for code review by other team members.
3. Local Repository: this is your local repository where you commit changes to the project
before pushing them to the central repository on Github. This is what is provided by the
distributed version control system. This corresponds to the .git folder in our directory.
4. Central Repository: This is the main project on the central server, a copy of which is with
every team member as a local repository.
Initializing Git repository
1. git init
2. git add [Link] ------------- optional
3. git commit -m "first commit“ ------------ message
4. git branch -M main
5. git remote add origin [Link]
6. git push -u origin main
• End Of Chapter One

You might also like