Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Lec 01 - Introduction To Python - CS

Uploaded by

mu7senan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Lec 01 - Introduction To Python - CS

Uploaded by

mu7senan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

L1 – Introduction to

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

 If you learn to program using one language,


 you should find it easy to pick up other languages.
 The key is to learn how to solve problems using a programming approach.

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

Note: Python can be used to


program
• Web Applications
• Enterprise Applications
• Embedded Applications 11
Interpreted Languages

 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

Python: Code Interpreter Computer

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

[finin@linux2 ~]$ python


Python 2.4.3 (#1, Jan 14 2008, 18:32:40)
[GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def square(x):
... return x * x
...
>>> map(square, [1, 2, 3, 4])
[1, 4, 9, 16]
>>>
 Allows you to type commands one-at-a-time and see results
 A great way to explore Python's syntax
 Repeat previous command: Alt+P
 Python interpreter evaluates inputs:
>>> 3*(7+2)
27 14
Python Used by

 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

 Anaconda is a distribution package, where you get Python compiler, Python


packages and the Spyder editor, all in one package.
 includes Python, the Jupyter Notebook, and other commonly used packages
for scientific computing and data science.
 Anaconda is available for Windows, macOS, and Linux Web:
https://www.anaconda.com

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)

 Select one dependent on your background, our programming skills, etc.


23
Versions

 Many Python versions have been released till now.


 Python releases as the following:
 Python 3.13 (First released: 2024-10-01 (planned), End of support: 2029-10)
 Python 3.12
 Python 3.11
 Python 3.10
 Python 3.9
 Python 3.8
 ………
 Python 1.6.1 (September 2000)
 Python 1.5.2 (April 1999)

24
Download Python

 Downloads  Open a terminal and


 Downloads: http://www.python.org  run python or run Idle from Finder.
 Documentation:  Linux:
http://www.python.org/doc/
 Chances are you already have Python
 Free book: http://www.diveintopython.org installed.
 Can be on:  To check, run python from the
terminal.
 Windows:
 If not, install from your distribution's
 Install Python. package system.
 Run Idle from the Start Menu.
 Mac OS X:
 Python is already installed.

Note: For step by step installation instructions, see the course web site.
25
Documentation: http://docs.python.org/
The Python tutorial is good!
Installing

 Dependent on the operating system, which have


 Select, download and install the code editor.
 Download the python version
 Install python
 Depended on your topics
 Start install the required packages
Working in Python
 There are various Python distributions available today:
 Default installation available from www.python.org is called CPython
installation.
 Anaconda Python distribution is highly recommended distribution that
comes preloaded with many packages and libraries e.g. NumPy, SciPy,
Panda etc.
 Jupyter notebook: It is a web based, interactive computing environment.
 Spyder : It is a powerful Python IDE with many useful editing, interactive
testing and debugging features
 Many popular IDEs are also available e.g. Spyder IDE, PyScripter IDE
etc.
 Working in Interactive Mode(Python IDLE)
 type one command at a time and the Python executes the given command
there and then and gives the output.
 Working in Script Mode(Python IDLE)
 save all the commands in the form of program file and show all the output
29
lines together which is not possible in Interactive mode.
Start using Python
 Can use
 Python prompts with ‘>>>’.
 Python IDE The basic code editor, or an integrated development environment, called
IDLE
 Example: Plotting in Python
 Lets open your Python Editor and type the following:
1 print ( ” Hello World ! ” )

 You can run Python interactively in different ways either


 using the Console which is part of the operating system ((or ”terminal”, or ‘command
prompt’)
 the Python IDLE
 the Python Shell which is part of the basic Python installation from
https://www.python.org

30
First Python Program

 Python does not have a main method like Java


 The program's main code is just written directly in the file
 Python statements do not end with semicolons

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)

 Escape sequences such as \" are the same as in Java


 Strings can also start/end with '

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>

>>> ex.fact1(6) NameError: name 'fact1' is


not defined
1296
>>>
>>> ex.fact2(200)
78865786736479050355236321
393218507…000000L
>>> ex.fact1
<function fact1 at
0x902470>
>>> fact1
Traceback (most recent
Basic Datatypes
 Integers (default for numbers) “abc” ‘abc’ (Same thing.)

z = 5 / 2 # Answer is 2, integer  Unmatched can occur within the string.


division. “matt’s”
 Floats  Use triple double-quotes for multi-line
strings or strings than contain both ‘
x = 3.456 and “ inside of them:
 Strings “““a‘b“c”””
 Can use “” or ‘’ to specify.

40
Numbers
 There are three numeric types in Python:
 Int
 Float
 Complex

 The usual notations and operators


 12, 3.14, 0xFF, 0377, (-1+2)*3/4**5, abs(x), 0<x<=5

 C-style shifting & masking


 1<<16, x&0xff, x|1, ~x, x^y
 Integer division truncates :-(
 1/2 -> 0 # float(1)/2 -> 0.5
 Long (arbitrary precision), complex
 2L**100 -> 1267650600228229401496703205376L
 1j**2 -> (-1+0j)

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

 Python allows for command line input.


 That means we are able to ask the user for input.
 Example:
 String Input in Python

 Using input()

43
Assignment

 Binding a variable in Python means setting a name to hold a reference


to some object.
 Assignment creates references, not copies
 Names in Python do not have an intrinsic type.
 Objects have types.
 Python determines the type of the reference automatically based on the
data object assigned to it.
 You create a name the first time it appears on the left side of an
assignment expression:
x=3
 A reference is deleted via garbage collection after any names bound to
it have passed out of scope.
44
Assignment (2)
 Accessing Non-Existent Names
 If you try to access a name before it’s been properly created (by placing it on the
left side of an assignment), you’ll get an error.
>>> y
Traceback (most recent call last):
File "", line 1, in -toplevel- y
NameError: name ‘y' is not defined
>>> y = 3
>>> y
3
 Multiple Assignment
 You can also assign to multiple names at the same time.
>>> x, y = 2, 3
>>> x
2
>>> y
3 45
Naming Rules
 Names are
 case sensitive and
 cannot start with a number.
 They can contain letters, numbers, and underscores.
 bob
 Bob
 _bob
 _2_bob_
 bob_2
 BoB

46
Naming conventions

The Python community has these recommend-ed naming


conventions
joined_lower for functions, methods and, attributes
joined_lower or ALL_CAPS for constants
StudlyCaps for classes
camelCase only to conform to pre-existing conventions
Attributes: interface, _internal, __private

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

Traceback (most recent call last):


File "<pyshell#16>", line 1, in -toplevel-
y
NameError: name ‘y' is not defined
>>> y = 3
>>> y
3
A Code Sample (in IDLE)

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

 Python Add-on Packages:


 http://pypi.python.org/pypi
Python Books
 You find other Python textbooks within different domains on my Python Web page:
 https://www.halvorsen.blog/documents/programming/python/
 Python Books:
 Python Programming
 Include the necessary foundation for basic programming with focus on Python

 Python for Science and Engineering


 Include numerical calculations in mathematics and engineering.

 Python for Control Engineering –


 The focus is on the use of Python within measurements, data collection (DAQ), control
technology, both analysis of control systems (stability analysis, frequency response, ...) and
implementation of control systems (PID, etc.).

 Python for Software Development


 The focus is on the use of Python for creating modern Software Systems such as tware Systems,
Software Development, Software Engineering, Database Systems, Web Application Desktop
Applications, GUI Applications, etc 51
End
52

You might also like