You are on page 1of 40

Introduction to Python

Aradzna M. Kamman
1
Python ─ Overview
 Python is an open source, high-level programming language
developed by Guido van Rossum in the late 1980s and presently
administered by Python Software Foundation.
 Python is a powerful language that you can use to create games,
write GUIs, and develop web applications. It is a high-level
language. Reading and writing codes in Python is much like reading
and writing regular English statements. Because they are not
written in machine-readable language, Python programs need to be
processed before machines can run them.
 Python is an interpreted language. This means that every time a
program is run, its interpreter runs through the code and translates
it into machine-readable byte code.
 Python is an object-oriented language that allows users to manage
and control data structures or objects to create and run programs.
Everything in Python is, in fact, first class. All objects, data types,
functions, methods, and classes take equal position in Python. It
also supports functional and structured programming methods.
2
Advantages of Using Python
 Readability
Python programs use clear, simple, and concise instructions that are
easy to read even by those who have no substantial programming
background. Programs written in Python are, therefore, easier to
maintain, debug, or enhance.
 Higher productivity
Codes used in Python are considerably shorter, simpler, and less
verbose than other highlevel programming languages such as Java and
C++.
 Less learning time
Python is relatively easy to learn. Many find Python a good first
language for learning programming because it uses simple syntax and
shorter codes.
 Runs across different platforms
Python works on Windows, Linux/UNIX, Mac OS X, other operating
systems and smallform devices. It also runs on microcontrollers used
in appliances, toys, remote controls, embedded devices, and other
similar devices.
3
Compiling and interpreting
 Many languages require you to compile (translate) your program
into a form that the machine understands.
compile execute
source code byte code output
Hello.java Hello.class

 Python is instead directly interpreted into machine instructions.

interpret
source code output
Hello.py

4
Installing Python
To install Python, you must first download the installation package of your
preferred version from this link: https://www.python.org/downloads/

Command Line Interaction

5
Integrated Development Environment (IDE)
List of IDE for Python
 PyCharm

 PyDe

 Komodo IDE

 Eric

 Eclipse

 Spyder

 PyScripter

 Geany

 Wing IDE

http://wingware.com/downloads/wingide-101

6
Outputting “Hello World”
Python files have extension .py Multiple Statements on a
Single Line.
The semicolon ( ; ) allows
multiple statements on the
single line given that neither
statement starts a new code
block.

7
Outputting INT/STRING

8
Python Identifiers
A Python identifier is a name used to identify a variable, function,
class, module or other object.

 An identifier starts with


 A to Z
 a to z
 underscore (_) followed by zero or more letters, underscores and digits
(0 to 9).

Python does not allow punctuation characters such as @, $, and %


within identifiers.

Python is a case sensitive programming language.


Thus, x and X are two different identifiers in Python.

9
Reserved Words
The following list shows the Python keywords. These are reserved
words and you cannot use them as constant or variable or any other
identifier names. All the Python keywords contain lowercase letters
only.

10
Indentation
 Python provides no braces to indicate blocks of code for class and
function definitions or flow control. Blocks of code are denoted by
line indentation, which is rigidly enforced.
 The number of spaces in the indentation is variable, but all
statements within the block must be indented the same amount.

For example

11
Multi-Line Statements
Statements in Python typically end Statements contained within
with a new line. Python does, the [], {}, or () brackets do
however, allow the use of the line not need to use the line
continuation character (\) to continuation character.
denote that the line should
continue.

12
Quotation in Python
 Python accepts single ('), double (") and triple (''' or """) quotes to
denote string literals, as long as the same type of quote starts and
ends the string.
 The triple quotes are used to span the string across multiple lines.

13
Comments in Python
 A hash sign (#) that is not inside a string literal begins a comment.
All characters after the # and up to the end of the physical line are
part of the comment and the Python interpreter ignores them.

14
Python - Variable Types
 Variables are nothing but reserved memory locations to store
values. This means that when you create a variable you reserve
some space in memory.

Assigning Values to Variables


Python variables do not need
explicit declaration to reserve
memory space. The declaration
happens automatically when you
assign a value to a variable. The
equal sign (=) is used to assign
values to variables.
The operand to the left of the =

operator is the name of the variable


and the operand to the right of the
= operator is the value stored in the
variable.
15
Multiple Assignment
 Python allows you to assign a  You can also assign multiple
single value to several variables objects to multiple variables.
simultaneously.

16
Standard Data Types
 Python has five standard data types
 Numbers
 String

 Boolean

 List

 Tuple

17
Python - Numbers
 Number data types
store numeric values.
Number objects are
created when you
assign a value to them.

18
Converting Integers to their String Representation

19
Math Commands
 Python has useful commands for performing calculations.
Command name Description Constant Description
abs(value) absolute value e 2.7182818...
ceil(value) rounds up pi 3.1415926...
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root

 To use many of these commands, you must write the following at


the top of your Python program:
from math import *
20
Python - String
 Strings in Python are
identified as a contiguous
set of characters
represented in the quotation
marks. Python allows for
either pairs of single or
double quotes. Subsets of
strings can be taken using
the slice operator ( [ ] and
[:] ) with indexes starting at
0 in the beginning of the
string and working their way
from -1 at the end.
 The plus (+ or ,) sign is the
string concatenation
operator and the asterisk
(*) is the repetition
operator. 21
String Properties
 len(string) - number of characters in a string
(including spaces)
 str.lower(string) - lowercase version of a string
 str.upper(string) - uppercase version of a string

22
Python - Boolean
 A
precedence: Order in which
operations are computed.
* / % ** have a higher

precedence than + -
1 + 3 * 4 is 13

Parentheses can be used


to force a certain order of
evaluation.
(1 + 3) * 4 is 16

23
Python - Lists
 my_list = [item_1, item_2, item_3]

 A list contains items separated by commas and enclosed within


square brackets ([]).

 The items belonging to a list can be of different data type.

 The values stored in a list can be accessed using the slice operator
([ ] and [:]) with indexes starting at 0.

24
Lists Properties
Python - Tuples
 The main differences between lists and tuples are: Lists are
enclosed in brackets ( [ ] ) and their elements and size can be
changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated. Tuples can be thought of as read-only lists.

26
Python - Basic Operators

Types of Operator
 Arithmetic Operators
 Comparison (Relational) Operators

 Logical Operators

 Assignment Operators

27
Arithmetic Operators Comparison (Relational)
A=9,B=2 Operators
+ Addition A + B = 11 A = 10 , B = 20
== Equal (a == b) False
- Subtraction A – B =7
!= Not Equal (a != b) True

* Multiplication A * B =18 <> Not Equal (a <> b) True

/ Division A / B = 4.5 > Greater than (a > b) False

< less than (a < b) True


% Modulus A%B=1
>= Greater than (a >= b) False
or Equal
** Exponent A ** B= 81

<= Less than or (a <= b) True


// Floor Division A // B= 4
Equal

28
Logical Operators Assignment Operators
A = 10 , B = 20 = Equal c=a+b
c += a
and / AND (a and b) False += Add AND c=c+a

c -= a
or / OR (a or b) True -= Subtract AND c=c-a

not / NOT not(a and b) True c *= a


*= Multiply AND c=c*a

c /= a
/= Divide AND c=c/a

c %= a
%= Modulus AND c=c%a

c **= a
**= Exponent AND c = c ** a

c //= a
//= Floor Division c = c // a

29
User Input

30
Python - Decision Making
if statements
An if statement consists of a
boolean expression followed by
one or more statements.

if...else statements
An if statement can be
followed by an optional else
statement, which executes
when the boolean expression is
FALSE.

nested if statements
You can use one if or else
if statement inside
another if or else
if statement(s).

31
Python – For Loop
 The for statement iterates over a range of values. These values can
be a numeric range.

SYNTAX:
for variable in list:
statements

32
Range
 The range function specifies a range of integers:
 range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
 It can also accept a third value specifying the change between values.
 range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step

33
Python – While Loop
 while loop: Executes a group of statements as long as a condition is True.
 good for indefinite loops (repeat an unknown number of times)

 Syntax:
while condition:
statements

34
Python - Functions
 A function is a set of statements that perform a specific task, a
common structuring element that allows you to use a piece of code
repeatedly in different parts of a program. They can be passed as
arguments, assigned to variables, or stored in collections.

SYNTAX:
def function_name(parameter list):
function body/statements

35
 a

36
Functions can all other Functions
 a

37
Global and Local variables
 Global Variables
Variable declared outside of the function or in global scope
is known as global variable. This means, global variable can
be accessed inside or outside of the function.

OUTPUT:

x inside : global
x outside: global
38
Global and Local variables
 Local Variables
A variable declared inside the function's body or in the
local scope is known as local variable.
OUTPUT:

NameError: name 'y' is not


defined
The output shows an error,
because we are trying to
access a local variable yin
a global scope whereas the
local variable only works
inside foo() or local scope.

39
THANK YOU!

40

You might also like