Chapters (1 and 2)
Chapters (1 and 2)
First Chapter
Python Programming
A general overview
Arithmetic, Strings, and Variables
CENG 111
Dr. Eng. Abdullatif BABA
2020 - 2021
Programming languages
Programming is the process of creating a set of instructions stored inside the memory in order to
tell a microprocessor how to perform a given task. Programming can be done using a variety of
programming languages.
Programming languages are classified as : Machine language, Assembly language, and High level
languages
MACHINE LANGUAGE : is a low-level programming language (the language of 0s and 1s) which is
composed of instructions used directly to control a computer's central processing unit (CPU). Each
instruction causes the CPU to perform a very specific task. Machine code is a strictly numerical
language which is intended to run as fast as possible. The majority of practical programs are written
in higher-level languages or assembly language. The source code is then interpreted to executable
machine code by utilities such as compilers or assemblers.
HIGH LEVEL LANGUAGE : high level languages are English like statements and programs. like
Java, C++, C#, Python.
Programming languages
• Python comes with a wide range of ready-made libraries that can be used in your own
programs.
• A very practical feature of Python is its maintainability. Since Python programs are
relatively easy to read and modify, they are easy for programmers to keep up to date.
Python’s support for maintenance is a big win in the eyes of many professionals.
Programming languages
What Is Python Useful For?
While Python is a general-purpose language that can be used to write any kind of program, it is especially popular for
the following applications:
• Scripts. These short programs automate common administrative tasks, such as adding new users to a system,
uploading files to a website, downloading webpages without using a browser, and so on.
• Website development. A number of Python projects—such as Django, Bottle and Zope, are popular among
developers as tools for quickly creating dynamic websites. The popular news site "reddit.com" was written using
Python.
• Text processing. Python has excellent support for handling strings and text files, including regular expressions and
Unicode.
• Scientific computing. Many superb scientific Python libraries are available on the web, providing functions for
statistics, mathematics, and graphing.
• Education. Thanks to its relative simplicity and utility, Python is becoming more and more popular as a first
programming language in schools.
Python isn’t the best choice for all projects. It is often slower than languages such as Java, C#, or C++. So, for example,
you wouldn’t use Python to create a new operating system.
But when you need to minimize the amount of time a programmer spends on a project, Python is often an excellent
choice.
Programming languages
The programming process
1. Determine what your program is supposed to do—that is, figure out its requirements.
2. Write the source code (in our case, the Python code) in IDLE (Python’s Integrated Development Environment) or any
other text editor. This is often the most interesting and challenging step, and it often involves creative problem solving.
Python source code files end with .py; Example: web.py, urlexpand.py, clean.py, and so on.
3. Convert the source code to object code using the Python interpreter. Python puts object code in .pyc files. For
example, if your source code is in the file urlexpand.py, its object code will be put in the file urlexpand.pyc
4. Run, or execute, the program. With Python, this step is usually done immediately and automatically after step 2 is
finished.
5. Finally, check the program’s output. If errors are discovered, go back to step 2 to try to fix them. The process of fixing
We typically call the contents of a .py file a program, source code, or just code.
Object code is sometimes referred to as executable code, the executable, or even just software.
Programming languages
Installing Python
2. Choose the most recent version of Python 3 (it should have a name like Python 3.x, where x is some small number).
This will take you to the appropriate download page with instructions for downloading Python on different computer
systems.
3. Click the appropriate installer link for your computer. For instance, if you are running Windows, click Windows x86
5. After the installation has finished (which could take a few minutes), test to see that Python is installed properly. Open
the Windows Start menu and choose All Programs. You should see an entry for Python 3.0 (often highlighted in yellow).
Select IDLE (Python GUI), and wait a moment for the IDLE program to launch
Python Programming
Arithmetic, Strings, and Variables
Let’s see how to interact with the Python shell. Start IDLE; you should find it listed as a
program in your Start menu on Windows.
What you should see when you first launch the Python interactive command shell. The
top two lines tell you what version of Python you are running.
Python 3.6.6rc1 (v3.6.6rc1:1015e38be4, Jun 12 2018, 07:51:23) [MSC v.1900 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
Integer Arithmetic
• An integer is a whole number, such as 25, –86, or 0; Python puts no limit on the size of
an integer
• Python also uses ** for exponentiation and % to calculate remainders (for example, 25
• Python also has an integer division operator, //. It works like /, except that it always
returns an integer. For example, 7 // 3 evaluates to the integer 2; the digits after the
For example
Python Programming
Arithmetic, Strings, and Variables
Floating Point Arithmetic
All the basic arithmetic operations that work with integers also work with floats,
even % (remainder) and // (integer division)
>>> 3.
3.0
>>> .5
0.5
Python Programming
Arithmetic, Strings, and Variables
Floating Point Arithmetic
Unlike integers, floating point numbers have minimum and maximum values that, if
exceeded, will cause overflow errors.
Example:
>>> 500.0 ** 10000
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
500.0 ** 10000
OverflowError: (34, 'Result too large')
Complex numbers
Python has built-in support for complex numbers that involve the square root of –1.
In Python, 1j denotes the square root of –1:
Example:
>>> 1j
1j
>>> 1j * 1j
(-1+0j)
Python Programming
Arithmetic, Strings, and Variables
Python comes with many different modules of prewritten code, including the math module.
The following table lists some of the most commonly used math module functions.
• To use the math module, or any existing Python module, you must first import it:
You can now access any math function by putting math. in front of it:
>>> math.sqrt(5)
2.2360679774997898
0.012518132023611912
Python Programming
Arithmetic, Strings, and Variables
Notice:
When using the from math import * style of importing if you have functions with the same name as any of the functions in
the math module, the math functions will overwrite them!
Thus, it’s generally safer to use the import math style of importing. This will never overwrite existing functions.
Python Programming
Arithmetic, Strings, and Variables
Strings
A string is a sequence of one or more characters, such as "cat!", "567-45442",
and "Up and Down". Characters include letters, numbers, punctuation, plus hundreds
of other special symbols and unprintable characters.
Indicating a string
Python lets you write string literals in three main ways:
• Single quotes, such as 'http', 'open house', or 'cat'
• Double quotes, such as "http", "open house", or "cat"
• Triple quotes, such as """http""", or multiline strings, such as
"""
Me and my monkey
Have something to hide
"""
One of the main uses of single and double quotes is to conveniently handle " and ' characters inside strings:
"It's great"
'She said "Yes!" '
Triple quotes are useful when you need to create long, multiline strings. They can also contain " and ' characters at the
same time.
Python Programming
Arithmetic, Strings, and Variables
String length
To determine the number of characters in a string, use the len(s) function:
>>> len('pear')
4
>>> len('up, up, and away')
16
>>> len("moose")
5
>>> len("") #The empty string has zero characters in it.
0
You can create new strings by linking (adding) some old strings together:
>>> 'hot ' + 'dog'
'hot dog'
>>> 'Once' + " " + 'Upon' + ' ' + "a Time"
'Once Upon a Time'
1. To see a list of all the built-in functions in Python, type dir(__builtins__) at the
command prompt.
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError',
'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError',
'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning',
'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError',
'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError',
'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration',
'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError',
'_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray',
'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format',
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min',
'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
'type', 'vars', 'zip']
2. To see the doc string for any function; you can use the help(function_name)
>>> help (round)
Help on built-in function round in module builtins:
round(...)
round(number[, ndigits]) -> number
3. You can run the Python help utility by typing help() at a prompt. This will provide you
with all kinds of useful information, such as a list of all available modules, help with
individual functions and keywords, and more.
>>> help()
Welcome to Python 3.6's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.6/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
help>
4. Once you’ve imported a module, you can list all of its functions using
the dir(m) function:
>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf',
'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10',
'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
Python Programming
Arithmetic, Strings, and Variables
Getting Help
Another alternative is to print a documentation strings
>>> print(math.tanh.__doc__)
tanh(x)
>>> print(bin.__doc__)
Return the binary representation of an integer.
>>> bin(2796202)
'0b1010101010101010101010'
Python Programming
Arithmetic, Strings, and Variables
Converting Between Types of data
1. Implicit Conversions
Sometimes Python will convert between numeric types without requiring an explicit
conversion function. For example:
>>> 25 * 8.5
212.5
Here, 25 is automatically converted to 25.0, and then multiplied by 8.5. In general, when
you mix integers and floats in the same expression, Python automatically converts the
integers to floats.
6. the Python math module has a number of functions for removing digits after
decimals: math.trunc(x), math.ceil(x), and math.floor(x).
>>> help(math.trunc)
Help on built-in function trunc in module math:
trunc(...)
trunc(x:Real) -> Integral
Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.
• A variable name can be of any length, the characters could be letters, numbers, or the
underscore character (_).
• Spaces, dashes, punctuation, quotation marks, and other such characters are not allowed.
• The first character of a variable name cannot be a number; it should be a letter or an
underscore character.
• Python is case sensitive; thus TAX, Tax, and tax are three different variable names.
• You cannot use Python keywords as variable names. For
example: if, else, while, def, or, and, not, in, and is are some of Python’s keywords.
Python Programming
Arithmetic, Strings, and Variables
Variables and Values
In all programming langaues variables label, or point to, a value; i.e. values should be
assigned to variables.
>>> fruit = 'Python_Programming'
>>> fruit
'Python_Programming‘
It’s essential to understand that assignment statements don’t make a copy of the value they
point to. All they do is label, and re-label, existing values.
Python Programming
The source book of this course is illustrated below
• Up to now, we’ve been writing single Python statements and running them at the
interactive command line. While that’s useful for learning about Python functions where
• Thus we turn to writing programs (also known as scripts). Programs are just text files
• When you run (or execute) a program, Python performs each statement in the file one after
the other.
Python Programming
Writing Programs
We often refer to the statements inside a Python program as source code, and so a program
file is sometimes called a source code file, or source file.
All Python source code files end with the extension .py.
A Python program runs using a special piece of software called a virtual machine. This is
essentially a software simulation of a computer designed just to run Python, and it is part of
the reason why many .pyc files can run on different computer systems without any change.
Note that IDLE is not strictly part of Python; it is a separate application that sits on top of Python to make it easier to
use.
Python Programming
Writing Programs
First program: Reading Strings from the Keyboard
# name_py_program_example
name = input('What is your first name? ') .strip()
print('Hello ' + name.capitalize() + '!')
To run this in IDLE, open name.py in an IDLE window, and then to run it press F5 (or, equivalently, choose Run > Run
Module).
You should see this in the window that appears:
What is your first name? cenk
Hello Cenk!
# name_py_program_example A comment
This line calls the input function, which is the standard built-in function for reading strings
from the keyboard. When it runs, the prompt 'What is your name?' appears in the output
window, followed by a blinking cursor. The program waits until the user enters a
name = input('What is your string and presses Enter.
first name? ') .strip() The input function evaluates to whatever string the user enters, and so the variable name ends
up labeling the string that the user types in.
strip() function to remove any leading/trailing whitespace characters
Example: >>> ' oven '.strip()
'oven'
This line displays a greeting. The function name.capitalize() ensures that the first character of
print('Hello ' +
name.capitalize() + '!') the string is uppercase and the remaining characters are lower-case. This way, if the user
happens to enter a name that isn’t correctly capitalized, Python will correct it.
To see what functions are available for strings, type dir('') at IDLE’s interactive command line.
Python Programming
Writing Programs
Second program: Reading numbers from the keyboard
# age.py
age = input('How old are you today? ')
age10 = int(age) + 10
print('In 10 years you will be ' + str(age10) + ' years old.')
The print statement is the standard built-in function for printing strings to the screen. As we
will see, it is extremely flexible and has many useful features for formatting strings and
By default, it prints out each string in the standard output window, separating the strings with
a space. You can easily change the string separator like this:
jack.ate.no.fat
Python Programming
Writing Programs
# coins_short.py
n = int(input('Nickels? ')) # 1 nicle = 5 cents
d = int(input('Dimes? ')) # 1 dime = 10 cents
q = int(input('Quarters? ')) # 1 quarter = 25 cents
# calculate the total amount of money
total = 5 * n + 10 * d + 25 * q
# print the results
print() # prints a blank line
print(str(total) + ' cents')
140 cents
Indicating in comments what parts are for input, processing, and output is a good habit to get into. It helps clarify the different tasks your
program performs; and when we start writing functions, it provides a natural way of dividing up your programs into sensible functions.