Lec 01 - Introduction To Python - CS
Lec 01 - Introduction To Python - CS
Python
By
Dr. Mubarak Sufyan
1
Table of content:
Introduction Public and Private data
Features of python Assignment
Limitation of python Naming rules
Python used by Sequences types
Versions Positive and Negative Indices
Installing python Reference Semantic
Python Editors Objects and Classes
Working in Python Dictionaries
Python interpreter Functions
Numpy Conditions Statement
To Understand the Code Control Flow Statement
Basic Data Types Packages
Keyword, Operators, and Syntax Modules
Arithmetic Operators Catching Exceptions
Logical Operators File Objects
List of methods Standard Library
Whitespace
Comments
2
Variables
The Key for programming
3
Programming Languages
Computer programs, known as software, are instructions that tell a computer what
to do.
Computers do not understand human languages,
so programs must be written in a language a computer can use.
There are hundreds of programming languages
They were developed to make the programming process easier for people.
However, all programs must be converted into the instructions the computer can
execute.
Which Programming Language is the Best?
Knowing that there are so many programming languages available, it would be natural
for you to wonder which one is best.
But, in truth, there is no “best” language.
Each one has its own strengths and weaknesses. 4
Programming Languages (2)
• First generation: Machine Language
• Second generation: Assembly language.
• Third Generation:
o Closer to English but included simple mathematical notation.
o Such as, FORTRAN、COBOL、C and C++、Visual Basic.
• Fourth Generation:
o A high level language that requires fewer instructions to accomplish a task than a third
generation language.
o Used with databases:
▪ Query languages, Report generators, Forms designers, and Application generators
• Fifth Generation:
o Declarative languages.
o Functional: Lisp, Scheme, SML. Also called applicative.
o Everything is a function.
o Logic: Prolog. Based on mathematical logic. Rule- or Constraint-based 5
Programming Languages (3)
• The principal paradigms
o Imperative Programming --- compiler.
▪ Procedure: Fortran, ALGOL, COBOL and BASIC, Pascal and C.
▪ Object-Oriented Programming (C++, Java) .
o Declarative Programming :
▪ Logic: Prolog.
▪ Functional/Applicative Programming (Lisp)
• Object-Oriented Programming Languages
o Simula
▪ First object-oriented language
▪ Developed by Ole Johan Dahl in the 1960s.
o Smalltalk
▪ First purely object-oriented language.
▪ Developed by Xerox in mid-1970s.
6
▪ Still in use on some computers.
Introduction
Python is an open source and cross-platform programming language,
that has become increasingly popular over the last ten years.
Python is an interpreted, high-level, general-purpose programming
language.
General-purpose language:
can be used for to program Web Applications, Enterprise Applications and
Embedded Applications, and within Data Science and Engineering
Applications.
Python : It has become popular in business and academic applications.
History:
Created by Guido van Rossum and first released in 1991.
Named for Monty Python
quickly became popular for a wide range of programming tasks.
Around 1995 it became even more popular due to it’s popularity in Internet
7
related programs.
Introduction (2)
Python is
a high-level programming language.
an object-oriented
interpreted
Created for distributed systems management tasks.
Useful as a scripting language
script: A small program meant for one-time use
Targeted towards small to medium sized projects
Procedural, Functional
Provides automatic memory management and garbage collection
Powerful as many other programming languages like C, C++, Java etc.
Dynamically typed.
Python also has hints of functional languages like LISP (AI).
Has a simple and flexible code structure and the code is easy to read.
can be used on all platforms (Windows, macOS and Linux).
8
Features of Python
Free and Open Source
Easy to interface with C/ObjC/Java/Fortran
Great interactive environment
Easy to use
Expressive Language
It is more capable to expressing the code’s purpose than many other languages.
Ex. //In C++ Swapping values #In Python: Swap values
int x=2,y=3,temp; x,y=2,3
temp=x; x,y=y,x
x=y;
y=temp
Complete Language:
All types of required functionality is available through various modules of Python standard
library. 9
Features of Python (2)
Has high number of free available Python Packaged and Libraries
Cross-platform Language:
It can run on variety of platforms like Windows, Linux/UNIX, Macintosh, Supercomputers,
Smart phones etc.
It is a portable language.
Variety of Applications:
Python is being used in many diverse fields/applications like :
Scripting
Web Applications
Game developments
System Administrations
AI
Rapid Prototyping
GUI Programs
Database Applications: such as SQL Server and MySQL
Using the Structured Query Language (SQL) or the upcoming NoSQL databases
10
The Most Popular Programming Languages
They categorize the
different Programming
Languages into the
following categories:
Web Applications
Mobile Applications
Enterprise Applications
Embedded Applications
Interpreted
Not compiled like Java
Code is written and then directly executed by an interpreter
Type commands into interpreter and see immediate results
Java: Runtime
Code Compiler Computer
Environment
12
Interpreter
The Python language uses an interpreter,
An interpreter is a program that both translates and executes the
instructions in a high-level language program.
How is interpreter work?
Reads each individual instruction in the program
Converts it to machine language instructions and then
Immediately executes them.
This process repeats for every instruction in the program.
Why?
Because interpreters combine translation and execution, they typically do
not create separate machine language programs
13
The Python Interpreter
Typical Python implementations offer both an interpreter and compiler
Interactive interface to Python with a read-eval-print loop
Google,
Yahoo!,
Youtube
Many Linux distributions
Games and apps (e.g. Eve Online)
AI
Etc.
15
Python packages
two most popular tools for installing Python Packages and setting up Python
environments are
1. PIP is a Python Package Manager
is a package manager for Python packages, or modules if you like.
is a tool for installing Python packages.
If you do not have PIP installed, you can download and install it from this page:
https://pypi.org/project/pip/
is typically used from the Command Prompt (Windows) or Terminal window
(macOS).
Installing Python Packages: pip install packagename
Uninstalling Python Packages: pip uninstall packagename
2. Conda - a Package and Environment Manager (for Python and other
languages)
a distribution package like Anaconda
16
Python packages
Can install and use separate Python packages created by third parties.
Install different packages for different topics such as Packages for
Desktop GUI Development
Database Development
Web Development, Software
AI
Etc.
and then later import these modules in your code
17
Some Packages
Example: Python Packages for Science and Numerical Computations
NumPy
is the fundamental package for scientific computing with Python
Downloads: http://numpy.scipy.org/
Tutorial: http://www.scipy.org/Tentative_NumPy_Tutorial
SciPy
SciPy is a free and open-source Python library used for scientific computing and technical
computing.
contains modules for
optimization, linear algebra, integration, interpolation, special functions, FFT, signal and image
processing, ODE solvers and other tasks common in science and engineering
Matplotlib
is a Python 2D plotting library
Pandas
Python Data Analysis Library
18
Standard Library
Core:
os, sys, string, getopt, StringIO, struct, pickle, ...
Regular expressions:
re module; Perl-5 style patterns and matching rules
Internet:
socket, rfc822, httplib, htmllib, ftplib, smtplib, ...
Miscellaneous:
pdb (debugger), profile+pstats
Tkinter (Tcl/Tk interface), audio, *dbm, ...
19
IDLE Development Environment
IDLE(Integrated Development
Program):
singleprogram that provides tools to
write, execute and test a program
Automatically installed when Python
language is installed
Runs in interactive mode
Has built-in text editor with features
designed to help write Python program
typically used on Windows
21
Anaconda
22
Python Editors
An editor is a program where you create your code
and where you can run and test it
Most Editors have also feature for Debugging.
The IDLE (integrated development environment) Editor, used for example Python programs
For more advanced programs a better editor as
Python IDLE (works well with Windows)
Visual Studio Code : Web: https://code.visualstudio.com
Spyder: Web: https://www.spyder-ide.org
Visual Studio : Web: https://visualstudio.microsoft.com
PyCharm: Web: https://www.jetbrains.com/pycharm/
Wing Python IDE: 3 different version (Wing 101, Wing Personal, and Wing Pro)
Jupyter Notebook : Web: http://jupyter.org (JupyterHub, and Microsoft Azure Notebooks)
Eclipse with Pydev (http://pydev.sourceforge.net/)
Shell
jupyter notebook (nice to try)
24
Download Python
Note: For step by step installation instructions, see the course web site.
25
Documentation: http://docs.python.org/
The Python tutorial is good!
Installing
30
First Python Program
hello.py
1 print("Hello, world!")
31
Python Shell
32
33
Command Prompt
34
Add Python to Path
In the Windows menu, search for “advanced
system settings”
and select View advanced system settings.
click Environment Variables
find and select the user variable named Path
click Edit. . . to change its value
Select ”New” and add the path where
”python.exe” is located
The Default Location is: C: \ U se r s \ u s e r
\AppData\ L oc al \Programs\Python\Python(version
number)\
Click Save and open the Command Prompt once
more and enter ”python” to verify it works.
35
Add Python to Path
36
The print Statement
print “newline\n"
print("text")
print() (a blank line)
swallows.py
1 print("Hello, world!")
2 print()
3 print("Suppose two swallows \"carry\" it together.")
4 print('African or "European" swallows?')
37
Comments
Start comments with # – the rest of line is ignored.
Syntax:
# comment text (one line)
Can include a “documentation string” as the first line of any new function or
class that you define.
The development environment, debugger, and other tools use it: it’s good style
to include one.
def my_function(x, y):
“““This is the docstring. This fun swallows2.py
ction does blah blah blah.””” 1 # Suzy Student, CSE 142, Fall 2097
# The code would go here... 2 # This program prints important messages.
3 print("Hello, world!")
4 print() # blank line
5 print("Suppose two swallows \"carry\" it
6 together.")
print('African or "European"
38 swallows?')
Simple functions: ex.py
671> python call last):
Python 3.5.6 … File "<stdin>", line 1,
>>> import ex in <module>
40
Numbers
There are three numeric types in Python:
Int
Float
Complex
41
Strings Methods in string
Strings in Python are surrounded by either upper()
single quotation marks lower()
capitalize()
or double quotation marks.
count(s)
’Hello’ is the same as ”Hello”
find(s)
rfind(s)
index(s)
strip(), lstrip(), rstrip()
replace(a, b)
expandtabs()
split()
join()
center(), ljust(), rjust()
42
String Input
Using input()
43
Assignment
46
Naming conventions
47
Accessing Non-Existent Name
Accessing a name before it’s been properly
created (by placing it on the left side of an
assignment), raises an error
>>> y
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 3.45 or y == “Hello”:
x = x + 1
y = y + “ World” # String concat.
print (x)
print (y)
References
Python Homepage
• http://www.python.org
Python Tutorial
• http://docs.python.org/tutorial/
Python Documentation
• http://www.python.org/doc
Python Library References
http://docs.python.org/release/2.5.2/lib/lib.html