PYTHON PROGRAMMING
Assoc. Prof. Dr. Bora Canbula
Manisa Celal Bayar University
Department of Computer Engineering
https://github.com/canbula/PythonProgramming/ gkdtw9f
Week01 Syllabus
Week01 Syllabus
Project Themes
Sports Economy Health
Week01 Syllabus
Project Examples
๏ Predicting Game Outcomes
๏ Injury Risk Prediction
๏ Player Market Value Prediction
๏ Fan Engagement Analysis
๏ Athlete Performance Comparison
Sports
๏ Stock Market Prediction
๏ Cryptocurrency Price Prediction
๏ Consumer Spending Analysis
๏ Predicting Unemployment Rates
๏ Credit Scoring Model
Economy
๏ Disease Outbreak Prediction
๏ Personalized Health Recommendations
๏ Health Risk Prediction
๏ Hospital Readmission Prediction
๏ Nutritional De ciency Prediction
Health
fi
Week02 Introduction to Python
Natural Languages vs. Programming Languages
A language is a tool for expressing and recording thoughts.
Computers have their own language called
machine language. Machine languages are created
by humans, no computer is currently capable of
creating a new language. A complete set of known
commands is called an instruction list (IL).
The di erence is that human languages developed
naturally. They are still evolving, new words are
created every day as old words disappear. These
languages are called natural languages.
Elements of a Language
• Alphabet is a set of symbols to build words of
a certain language.
• Lexis is a set of words the language o ers its
users.
• Syntax is a set of rules used to determine if a
certain string of words forms a valid sentence.
• Semantics is a set of rules determining if a
certain phrase makes sense.
Machine Language vs. High-Level Language
The IL is the alphabet of a machine language. It’s the
computer’s mother tongue.
High-level programming language enables humans to write
their programs and computers to execute the programs. It is
much more complex than those o ered by ILs.
A program written in a high-level programming language is
called a source code. Similarly, the le containing the source
code is called the source le.
ff
fi
ff
fi
ff
Week02 Introduction to Python
Compilation vs. Interpretation
There are two di erent ways of transforming a program from
a high-level programming language into machine language:
Compilation: The source code is translated once by getting a
le containing the machine code.
Interpretation: The source code is interpreted every time it is
intended to be executed.
Compilation Interpretation
• The execution of the • You can run the code as soon
translated code is usually as you complete it, there are
faster. no additional phases of
• Only the user has to have the translation.
compiler. The end user may • The code is stored using
use the code without it. programming language, not
• The translated code is stored machine language. You don’t
using machine language. Your compile your code for each
code are likely to remain your di erent architecture.
secret.
• The compilation itself may be • Don’t expect interpretation to
a very time-consuming ramp up your code to high
process speed
• You have to have as many • Both you and the end user
compilers as hardware have the interpreter to run
platforms you want your code your code.
to be run on.
fi
ff
ff
Week02 Introduction to Python
What is Python?
Python is a widely-used, interpreted, object-oriented, and
high-level programming language with dynamic semantics,
used for general-purpose programming.
Python was created by Guido van
Rossum. The name of the Python
programming language comes from
an old BBC television comedy sketch
series called Monty Python’s Flying
Circus.
Python Goals
• an easy and intuitive language just as powerful
as those of the major competitors
• open source, so anyone can contribute
to its development
• code that is as understandable as plain English
• suitable for everyday tasks, allowing for short
development times
Why Python? Why not Python?
• easy to learn • low-level programming
• easy to teach • applications for mobile
• easy to use devices
• easy to understand
• easy to obtain,
install and deploy
Week02 Introduction to Python
Python Implementations
An implementation refers to a program or environment, which
provides support for the execution of programs written in the
Python language.
• CPython is the traditional implementation of Python and it’s
most often called just “Python”.
• Cython is a solution which translate Python code into “C”
to make it run much faster than pure Python.
• Jython is an implementation follows only Python 2, not
Python 3, written in Java.
• PyPy represents a Python environment written in Python-
like language named RPython (Restricted Python), which is
actually a subset of Python.
• MicroPython is an implementation of Python 3 that is
optimized to run on microcontrollers.
Start Coding with Python
• Editor will support you in writing the code. The Python 3
standard installation contains a very simple application
named IDLE (Integrated Development and Learning
Environment).
• Console is a terminal in which you can launch your code.
• Debugger is a tool, which launches your code step-by-step
to allow you to inspect it.
rst.py
https://forms.o ce.com/r/z2XZbbypBR
fi
ffi
Week02 Introduction to Python
Function Name
A function can cause some e ect
or evaluate a value, or both.
Where do functions come from?
• From Python itself
• From modules
• From your code
rst.py
Argument
• Positional arguments
• Keyword arguments
fi
ff
Week02 Introduction to Python
Literals
A literal is data whose values are determined by the literal
itself. Literals are used to encode data and put them into code.
literals.py
•String
•Integer
•Float
•Complex
•Boolean
•Binary
•Octal
•Hexadecimal
•Scienti c Notation
fi
Week02 Introduction to Python
Basic Operators
An operator is a symbol of the programming language, which is
able to operate on the values.
Multiplication Division
Integer Float
Float Float
Float Float
Float Float
Exponentiation Floor Division
Integer Integer
Float Float
Float Float
Float
Float
Modulo Addition
Integer Integer
Float Float
Float
Float
Week02 Introduction to Python
Operator Priorities
An operator is a symbol of the programming language, which is
able to operate on the values.
priorities.py
• + (unary)
• - (unary)
• ** (right-sided binding)
• *
• /
• //
• % (left-sided binding)
• + (binary)
• - (binary)
Week02 Introduction to Python
Variables
Variables are symbols for memory addresses.
https://docs.python.org/3/library/functions.html
Week02 Introduction to Python
Identi er Names
For variables, functions, classes etc. we use identi er names.
We must obey some rules and we should follow some naming
conventions.
• Names are case sensitive.
• Names can be a combination of letters, digits, and
underscore.
• Names can only start with a letter or underscore,
can not start with a digit.
• Keywords can not be used as a name.
https://forms.o ce.com/r/y6xQaXSL1F
fi
ffi
fi
Week02 Introduction to Python
Your First Homework
Week01/info_ rstname_lastname.py
A string variable with the name student_id that contains
your student id.
A string variable with the name full_name that contains
your full name.
Week02/types_ rstname_lastname.py
An integer with the name: my_int
A oat with with the name: my_ oat
A boolean with the name: my_bool
A complex with the name: my_complex
Rules for your pull requests
✓ Please run your code rst in your computer, do not
submit codes with syntax errors.
✓ Submit your code to WeekXX folder. WeekXX/hw is
for me to move accepted works.
✓ If a change is requested, please edit the existing pull
request, don’t open a new one.
fl
fi
fi
fi
fl
Week02 Introduction to Python
Your First Homework
Week01/info_ rstname_lastname.py
A string variable with the name student_id that contains
your student id.
A string variable with the name full_name that contains
your full name.
Week02/types_ rstname_lastname.py
An integer with the name: my_int
A oat with with the name: my_ oat
A boolean with the name: my_bool
A complex with the name: my_complex
fl
fi
fi
fl
Week03 Introduction to Python
Equality & Identity & Comparison
Equality
Left- or Right-sided?
Inequality Updated Priority Table
Operator Type
+, - unary
** binary
Comparison Chaining *, /, //, % binary
+, - binary
<, <=, >, >= binary
!=, == binary
Using one of the comparison operators in Python, write
QUESTION
a simple two-line program that takes the parameter n as
input, which is an integer, prints False if n is less than
100, and True if n is greater than or equal to 100.
Conditional Execution
if statement
Ternary Operator
Week03 Introduction to Python
Loops
• The program generates a random
number between 1 and 10.
• The user is asked to guess the
QUESTION
number.
• The user is given feedback if the
guess is too low or too high.
• The user is asked to guess again
until the correct number is guessed.
• The user is asked to enter a
QUESTION
number.
• The program prints the numbers
from 0 to n-1.
break and continue
Can we use while/for with else?
Packaging Python Modules
Steps that are required for packaging our modules
and make them available to be installed via pip.
Install git and
connect to your
GitHub account
Find a name for your
package in pypi.org
Create a repo
with this name
Connect your
local directory
to this repository
Packaging Python Modules
Steps that are required for packaging our modules
and make them available to be installed via pip.
Folder Structure
boracanbula An empty directory
dist Directory for source codes
src
Directory using the name
boracanbula with your package
__init__.py An empty Python file
statistics.py The Python file that includes
tests a function or a class
test_statistics.py (use an appropriate file name)
Directory for tests
LICENSE A Python file which its
pyproject.toml name starts with test_
README.md A text file that includes a license
A markdown file for A text file with the .toml extension
the detailed description that includes the configuration
of your project details of your project
Packaging Python Modules
statistics.py LICENSE
test_statistics.py
README.md
pyproject.toml
Packaging Python Modules
Be sure that you have the required modules Build
Go to your
“Account settings”
in pypi.org
Create an API token
.pypirc
Create a .pypirc file
in your home directory
with this token
Check your package in PyPI
Upload your package to PyPI
👏👏
Create a release in GitHub
Install your package via pip
Functions
Functions are defined by using def keyword, name
and the parenthesized list of formal parameters.
Function names should be lowercase, with words separated by
underscores as necessary to improve the readability. PEP 8
Basic Function Definition Input/Output Arguments
Default Values for Arguments
Type Hints and Default Values for Arguments
3 1 07
PEP
Multiple Type Hints for Arguments
n 3.10
tho
> Py
Lambda Functions
Function Docstrings
257
P EP
Docstrings PEP 257
A docstring is a string literal that occurs as the first
Statement in a module, function, class, or method
definition. Such a docstring becomes the __doc__
special attribute of that object.
One-line Docstrings
Multi-line Docstrings
Docutils and Sphinx are tools to automatically create
documentations
reST (reStructuredText) Format
Google
Format
Some other formats are Epytext (javadoc), Numpydoc, etc
Parameter Kinds PEP 362
Kind describes how argument values are bound to the
parameter. The kind can be fixed in the signature of
the function.
Standard Binding: Positional-or-Keyword
Positional-or-Keyword & Keyword-Only
Positional-Only & Positional-or-Keyword & Keyword-Only
4 57
PEP
Handle Every Situation
Function Attributes PEP 232
Functions already have a number of attributes such as
__doc__, __annotations__,
__defaults__, etc. Like everything in Python,
functions are also objects, therefore user can add a
dictionary as attributes by using get / set methods to
__dict__.
Nested Scopes PEP 227
Like attributes, function objects can also have
methods. These methods can be used as inner
functions and can be useful for encapsulation.
Getter and Setter Methods
Homework for Functions
Week03/functions_firstname_lastname.py
custom_power Examples
A lambda function
Two parameters (x and e)
x is positional-only
e is positional-or-keyword
x has the default value 0
e has the default value 1
Returns x**e
custom_equation
A function returns float
Five integer parameters (x, y, a, b, c)
x is positional-only with default value 0
y is positional-only with default value 0
a is positional-or-keyword with default value 1
b is positional-or-keyword with default value 1
c is keyword-only with default value 1
Function signature must include all annotations
Docstring must be in reST format.
Returns (x**a + y**b) / c
fn_w_counter
A function returns a tuple of an int and a dictionary
Function must count the number of calls with caller
information
Returning integer is the total number of calls
Returning dictionary with string keys and integer values
includes the caller ( _ _name_ _ ) as key, the number of
call coming from this caller as value.