Lecture1 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Course: FUK-CSC 104 Python Programming Basics

Course Content
• Basic syntax: variables, data types, basic operators, and input and print statements.
• Data structures: Essential data structures like lists, dictionaries, tuples, and sets. How to
manipulate and access data stored in those structures.
• Control flow: conditional statements (if, elif, else) and loops (for and while loops).
• Functions: How to define and call functions. What are parameters, return values, and the
importance of modular code.
• File handling: How to read from and write to files using Python. file modes, such as read
('r'), write ('w'), and append ('a').
• Error handling: The concept of exceptions and how to handle them using try-except
blocks.
• Basic algorithms and problem-solving: Basic algorithms like searching and sorting.
Encourage students to solve problems using Python.
Lecture note 1: Introduction to Python course
Introduction
What is a program?
What is programming?
Who is a programmer?
Why Python?
Python is a scripting language, i.e it is a programming language for writing scripts, which are short
programs that automate a specific task
Brief History of Python
It is developed by Guido van Rossum a Dutch Computer programmer working at Centrum
Wiskunde & Informatica (CWI), the national research institute for mathematics and computer
science in the Netherlands.
It started in 1989 as a “hobby project” called Moulder to create scripts that are easy to learn and
use. The name Moulder was derived from the British rock band mould, he was a big fan of the band.
Later, he found that the name was already used by other programming languages and he didn’t want
to cause confusion. It was renamed Python after the British comedy group Monty Python Flying
Circus, he also liked the idea of the snake python eating other programming languages which
symbolized Python language flexibility and adaptability.
The first known version of the programming language was Python 0.9.1 released in 1991. Python
1.0 was released in 1994 with new features and improvements. Python 3.0 was released in 2008
with significant changes which became a popular language for data scientists, web developers and

Compiled by A. S. Dauda
AI engineers. Some influential frameworks include Django created in 2005 for web development,
scikit-learn released in 2007 for machine learning, TensorFlow released in 2015 for deep learning.
Characteristics of Python
• Easy to learn: easy to learn, a great language for beginners.
• High-level language: python abstracts away low-level details, allowing programmers to focus
on the logic of the program.
• Interpreted language: python code executes line-by-line not compile and run at once.
• Dynamic typing: the datatype of a variable is determined at runtime.
• Cross-platform: python code can run on multiple OS, e.g Windows, MacOS, Linux. Etc
• Scripting: used for writing scripts to automate tasks, perform data analysis etc.
• Open-source: meaning it is free to use, modify, and distribute.
• Extensive support: python has excellent support for many programming paradigms like object-
oriented programming, procedural and functional programming.
Python programming language is a versatile language that can be used to develop a range of
applications including:
• Web applications: using frameworks like Django, Flask, Pyramid etc
• Data Analysis and Science: libraries like pandas, numpy, scipy, matplpotlib etc
• Artificial Intelligence and Machine Learning: libraries like scikit-learn, tensorflow, keras etc
• Desktop Application: framework TKinter, PyQt, wxPython etc
• Mobile Application: framework like kivy, and Buildozer
• Web scraping: libraries like BeautifulSoup and Scrapy.
• Games: libraries like Pygame and Panda3D
• Scientific computing
• Internet of Things (IoT)
• Database Administration
• Computer vision
• Natural language processing
• Audio and Video Processing
Installation
which OS are you using?
Linux and MacOS come along with Python pre-installed but Windows doesn’t come with it.
Therefore, if Python is not installed on your device you can download it from the official website:
https://www.python.org/downloads/
Checking Python installation: go to the terminal or command prompt and type python if you get the
python prompt in respond (>>>) then it is installed else is not.
How to run Python code
• Running Python code in the terminal: open the terminal prompt and type python e.g

Compiled by A. S. Dauda
To exit Ctrl+Z+Press ENTER or write exit() press ENTER
• Running Python code in an editor e.g sublime text editor or you can create the Python file and
run it on the terminal i.e you locate the file and run it

Compiled by A. S. Dauda
Lecture Note 2: Basic Syntax of Python Programming
Objectives:
- Understand the basic syntax of the Python programming language.
- Learn how to write and execute simple Python programs.
- Familiarize yourself with variables, data types, basic operators, and print statements in Python.

Introduction to Python Syntax:


- Python is known for its clean and readable syntax.
- It uses indentation to define code blocks, unlike other languages that use braces ({}) or
keywords (begin/end).

Comments:
- comments are used to write notes for clarifications and the Python interpreter will ignore them
as valid Python codes.
- there are two types of comment, single-line comment and multi-line (docstring) comment.
- a single line comment in Python starts with the hash symbol (#) and extends to the end of the
line.
- Comments are meant to explain what the portion of the code is intended to do and help other
people understand your code, especially in a collaborative environment.
The Zen of Python
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.

Compiled by A. S. Dauda
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Statements:
- Python uses newline characters to terminate statements, so each statement is typically written
on a separate line.
- However, you can use a semicolon (;) to write multiple statements on a single line.

Variables:
- Variables are used to store data values in Python.
- Variable names can contain letters, numbers, and underscores but cannot start with a number.
- Variables are case-sensitive (e.g., "myVariable" is different from "MyVariable").
Some other rules will not break your code but will make your code easier to read and understand,
avoid using keywords or reserved words for variable creations. It should be short but descriptive,
and the variable's names should be all in lowercase, and uppercase has meanings.
Assigning value to a variable
x = 1
x,y,z = 3,0,1 this is called multiple assignment
Constant
Python doesn’t have a constant datatype but professional Python programmers follow a good
etiquette of using Uppercase letters in naming a constant. For example, in the calculation of the
area of a circle 𝐴 = 𝜋𝑟 2 if we are to present it in Python code, the π is constant.
PI = 22/7
r = 2
Compiled by A. S. Dauda
area = PI*r**2
Error in Python
A traceback is a record of where the interpreter ran into trouble when trying to execute your
code.
Example:
1. Syntax error: it occurs when Python doesn’t recognize your code as valid code. For
example, using an apostrophe inside a string with a single quote, missing brackets, etc.
2. Semantic error: it occurs when Python recognize your code as valid code but the meaning
attached to the code is wrong. e.g using a variable without initialization, performing
operations on incompatible datatypes, etc.
3. Logical error: occurs when your code is syntactically and semantically correct but it gives
unexpected or incorrect results. e.g infinite loops, incorrect algorithm implementation,
unintended variable modification.

Data Types:
- Python has several built-in data types, including integers, floats (decimal numbers), strings
(text), lists, tuples, dictionaries, and booleans (True/False).
- Use the `type()` function to determine the data type of a variable or value.
Number:
We use numbers to keep scores in games, represent given data in visualizations, store
information in web applications and so on. They are grouped into integer and float
Integer: integers are whole numbers where we can add (+), subtract (-), divide(/), and multiply
(*) them. Parenthesis can be used to specify the order of operations.
Float: any number with a decimal is regarded as a float in Python.
N.B: by default any division operation of integers will result in float, operation between float and
integer will result in float.
Example: 2/3 , 1 + 1.0 , etc
Underscores in number
For easier representation, you can use an underscore to make the number more readable and
Python will understand it.
thousand = 20_000
million = 10_000_000

String

Compiled by A. S. Dauda
A string is a series of characters. Anything inside single or double quotes is considered a string in
Python.
Example:
Working with string methods
A method is an action that Python can perform on a piece of data.
1. .title() – make every first letter of a word in the string capital, useful in names
2. .lower() – make the string to lowercase, useful in storing data
3. .upper() – make the string to uppercase,
Using variables in a string
In a situation where you want to use a variable’s value inside a string datatype.
f-string
the f- stands for format, so Python formats the string inside the variable.
Example
first_name = “Dauda”
last_name = “Sani”
full_name = f”{first_name} {last_name}”
print(full_name)
Or
full_name = “{} {}”.format(first_name, last_name)
Whitespace with string
A whitespace refers to nonprinting characters such as spaces, end-of-line symbols, tabs etc.
They help present output for clarity. We use escape sequence to define them
\t, \n, etc
Removing whitespace in a string
“ Dauda” and “Dauda “are confusing in programming. Because of the extra spaces before and
after the text Dauda. In the given example we can see how we can remove the extra spaces
Example:
name = “ Dauda”
print(name.lstrip())

Compiled by A. S. Dauda
Other methods are rstrip and strip.
In the real world, they are used to clean user input before storing it in a program. For example,
Comparing two strings, checking usernames when they want to log in. etc.

Basic Operators:
- Arithmetic Operators: `+` (addition), `-` (subtraction), `*` (multiplication), `/` (division), `//`
(floor division), `%` (modulus), `**` (exponentiation).
- Assignment Operators: `=` (assignment), `+=`, `-=`, `*=`, `/=`, `//=`, `%=` (compound
assignment).
- Comparison Operators: `==` (equal to), `!=` (not equal to), `<` (less than), `>` (greater than),
`<=` (less than or equal to), `>=` (greater than or equal to).
- Logical Operators: `and`, `or`, `not` (logical AND, OR, NOT).

Print Statement:
- The `print()` function displays output in Python.
- You can pass multiple arguments to `print()` to concatenate and display them.
Example:
# This is a comment
# Assigning values to variables
x = 10
y = 5.5
name = "John"
# Performing arithmetic operations
sum = x + y
difference = x - y
# Displaying output
print("Sum:", sum)
print("Difference:", difference)

Compiled by A. S. Dauda

You might also like