Chapter One
Python Programming
Lecturer: [Link] MBUMBO
Major:Telecommunications
Minor: Cybersecurity
Tel:674653215
Email:enghit2023@[Link]
Python Basics
Variables
Operators
Strings
Input and output
Control flow
Lists
Dictionaries
Tuples
Introduction to python
Python is a high level, interpreted programming language known for its clear syntax and
readability.
It supports multiple programming paradigms, including procedural, object oriented and
functional programming.
Python is widely used in various domains such as web development, data analysis,
artificial intelligence, scientific computing.
Python programming community also contributes a vast amount of libraries and tools,
making it possible for programmers to use python.
Requirements to use python
To use python, you typically need the following requirements
1. Python interpreter: You can download the python interpreter from the official
python website([Link]) and install it on your computer
2. Integrated development environment (IDE) While not strictly necessary, an IDE
can make coding in python much easier. Some popular IDEs for python include
pycharm, visual studio code, Jupiter notebook
3. Text Editor
4. Operating system(python is compatible with windows , macOS and Linux
Python syntax
Python syntax is relatively simple and easy to learn
1 Indentation: python uses indentation to define code blocks,
rather than curly braces or keywords like “begin” and “end”.
Consistent indentation is crucial in python to indicate the structure of
your code.
2. Comments: single line comments start with a hash symbol(#) , and
multi-line comments are enclosed in triple quotes(‘’’ or ‘’’)
Understanding of basic programming concepts
It’s helpful to have a basic understanding of programming concepts
like variables, data types, loops and functions before you start
python
Variables
Python variables do not need explicit declaration. You can assign
a value to a variable using he assign a value to a variable using
the assignment operator (=)
Data types – python supports various data types such as integers,
floats, strings, lists, tuples, dictionaries, and more.
Print statement : you can print out to the console using the print()
function.
Control Structures: python has if statements, for loops, while
loops, and more to control the flow of your program.
Functions: functions are defined using the def keyword, following
by the function name and parameters.
Importing Modules: you can import external modules using the
import statement to extend python’s functionality.
Python structure
In python, the structure of a typical program can be broken down
into several key components.
1. Shebang line (optional) This line is used at the beginning of a
python script to specify the path to the python interpreter that
should be used to run the script, for example
‘’’ python
#!/usr/bin/env python3
2. imports. In this section, you import any modules or libraries that
your program will use. This is typically done at the beginning of your
scripts
3. Global variables This is where you define any global
variables that will be used throughout your program.
‘’’ python
Global_var =10
4. Function definitions define any functons that your program
will use. Functions in python are define using def keyword
‘’’ python
def my_function(parameter):
#function body
5. Main body. This is where the main logic of your program
resides. It could be a series of statements or functions calls
‘’’python
If_name_==“_main_”:
# main program logic
6. Execution At the end of the script, you might have a call to
a function or some code that should run when the script is
executed.
‘’’python
if_name_==_main_”:
main()
This is a basic outline of the structure of a python program.
It’s important to note that python is designed to be readable
and easy to understand, so the structure of your program
should be clear and logical.
How to write a python program
To write a simple python program, you first need to define the logic you want
to implement. Then, open a text editor or an integrated development
environment (IDE) like visual studio code or pycharm. Write your python
code by following the syntax rules, such as proper indentation. Save the file
with a .py extension and run it using a python interpreter. You can use a
terminal or command prompt to execute the program by typing ‘python
[Link]’ .Start with a simple program, such as printing “Software
engineering” to get familiar with the basics of python programming.
Use Meaningful variable names to make your code more readable.
2 comment your code to explain complex parts or provide context for others
(and your future self)
Break down your problem into smaller, manageable tasks and tackle each one
step by step
Take advantage of python’s built in functions and libraries to simplify your code
Use version control systems like Git to track changes and collaborate with
others. Remember to practice regularly and explore various resources to
improve your programming skills.
[Link]
Variables
message = “Python programming language is easy!"
print(message)
We’ve added a variable named message. Every variable is connected to a value, which is the
information associated with that variable. In this case the value is the “Python programming
language is easy!" text.
Adding a variable makes a little more work for the Python interpreter. When it processes the first
line, it associates the variable message with the " “Python programming language is easy!"
text. When it reaches the second line, it prints the value associated with message to the screen.
Let’s expand on this program by modifying “Python programming language is [Link]!" to
print a second message. Add a blank line to “Python programming language is easy!" , and
then add two new lines of code:
You can change the value of a variable in your program at any time, and
Python will always keep track of its current value.
Naming and Using Variables
When you’re using variables in Python, you need to adhere to a
few rules and guidelines. Breaking some of these rules will
cause errors; other guidelines just help you write code that’s
easier to read and understand. Be sure to keep the following
variable rules in mind:
Variable names can contain only letters, numbers, and underscores.
They can start with a letter or an underscore, but not with a number.
For instance, you can call a variable message_1 but not 1_message.
• Spaces are not allowed in variable names, but underscores can be used
to separate words in variable names. For example, greeting_message
works, but greeting message will cause errors.
• Avoid using Python keywords and function names as variable names;
that is, do not use words that Python has reserved for a particular programmatic purpose, such as the
word print and Built-in Functions” on page 471.)
• Variable names should be short but descriptive. For example, name is
better than n, student_name is better than s_n, and name_length is better than
length_of_persons_name.
• Be careful when using the lowercase letter l and the uppercase letter O
because they could be confused with the numbers 1 and 0
It can take some practice to learn how to create good variable names,
especially as your programs become more interesting and
complicated. As you write more programs and start to read through
other people’s code, you’ll get better at coming up with meaningful
names.
The Python variables you’re using at this point should be lowercase.
You won’t get errors if you use uppercase letters, but uppercase letters
in variable names have special meanings.
Programming languages are strict, but they disregard good and bad spelling.
As a result, you don’t need to consider English spelling and grammar rules when
you’re trying to create variable names and writing code. Many programming errors
are simple, single-character typos in one line of a program.
If you’re spending a long time searching for one of these errors, know that you’re
in good company.
Many experienced and talented programmers spend hours hunting down these
kinds of tiny errors.
Strings
Because most programs define and gather some sort of
data, and then do something useful with it, it helps to
classify different types of data. The first data type we’ll look
at is the string. Strings are quite simple at first glance, but
you can use them in many different ways. A string is a
series of characters. Anything inside quotes is considered a
string in Python, and you can use single or double quotes
around your strings like this:
Changing Case in a String with Methods
One of the simplest tasks you can do with strings is change the case of the words in a
string. Look at the following code, and try to determine what’s happening:
In this example, the variable name refers to the lowercase string "ada
lovelace". The method title() appears after the variable in the print() call. A
method is an action that Python can perform on a piece of data. The dot (.)
after name in [Link]() tells Python to make the title() method act on the
variable name. Every method is followed by a set of parentheses, because
methods often need additional information to do their work. That information
is provided inside the parentheses.
The title() function doesn’t need any additional information, so its
parentheses are empty. The title() method changes each word to title case,
where each word begins with a capital letter.
This is useful because you’ll often want to think of a name as a piece of
information. For example, you might want your program to recognize the
input values Ada, ADA, and ada as the same name, and display all of them
as Ada.
Several other useful methods are available for dealing with case as well.
For example, you can change a string to all uppercase or all lowercase
letters like as follows,
The lower() method is particularly useful for storing data. Many times
you won’t want to trust the capitalization that your users provide, so
you’ll convert strings to lowercase before storing them. Then when you
want to display the information, you’ll use the case that makes the most
sense for each string.
Using Variables in Strings
In some situations, you’ll want to use a variable’s value inside a
string. For example, you might want two variables to represent a
first name and a last name respectively, and then want to combine
those values to display someone’s full name:
To insert a variable’s value into a string, place the letter f immediately
before the opening quotation mark .
Put braces around the name or names of any variable you want to
use inside the string. Python will replace each variable with its value
when the string is displayed. These strings are called f-strings.
The f is for format, because Python formats the string by replacing
the name of any variable in braces with its value. The output from the
previous code is:
Adding Whitespace to Strings with Tabs or Newlines
Numbers
Numbers are used quite often in programming to keep score in
games, represent data in visualizations, store information in web
applications, and so on.
Python treats numbers in several different ways, depending on
how they’re being used. Let’s first look at how Python manages
integers, because they’re the simplest to work with.
Floats
Python calls any number with a decimal point a float. This term is used in most
programming languages, and it refers to the fact that a decimal point can appear at
any position in a number. Every programming language must be carefully designed
to properly manage decimal numbers so numbers behave appropriately no matter
where the decimal point appears.
Introduction to lists in python
A list is a collection of items in a particular order. You can make a list that includes
the letters of the alphabet, the digits from 0–9, or the names of all the people in
your family. You can put anything you want into a list, and the items in your list
don’t have to be related in any particular way. Because a list usually contains
more than one element, it’s a good idea to make the name of your list plural, such
as letters, digits, or names. In Python, square brackets ([]) indicate a list, and
individual elements in the list are separated by commas. Here’s a simple example
of a list that contains a few kinds of bicycles: