Вы находитесь на странице: 1из 55

Chapter two

Introduction to python

Aman W
Department of Applied Physics
University of Gondar
Objective

The main objective of the course is to


Become skillful at making a computer do
what you want it to do
Handle different properties of a programing language
python
Learn computational modes of thinking
Develop and use programs that solve realworld problems
Master the art of computational problem solving
Contents

Introduction
What is Computation?
Introduction to Console vs. GUI
Basics of Python scripting
Variables and Data types
Assignments of variables
Expressions
Control structures
Flow Control: Looping
Conditionals
Functions
Exception
Flow Control: Looping
For & while loop
Introduction

Basically a computer
Performs calculations and
Remember/store their results
To perform the above activities, a computer may use
Built in primitives or
Building your own methods(function, procedures, modules) of
calculating that parameter
Example
Playing chess
Calculating temperature/pressure of the atmosphere/
Getting the speed of sound in water/gas
etc
What is computation?

Computational problem solving


Knowledge could be divided into two categories
Declarative knowledge
Statements of fact. i.e
The square root of a number x is a number y such that
y*y = x
Imperative knowledge
how to methods or recipes. Example
How to find the square root of a particular instance of x?

Can you use this technique for calculating the square root of x
Imperative knowledge

How do we transform a physics problem such as the one in the


above into something that can be solved on a computer?
Analyze the problem to find a suitable numerical method of to get a
solution.
Example
How we calculate the square root of any number x?
How we prepare a nice watt/Doro watt?

Write down the basic steps to get a nice watt/Doro watt


Xx
Xx
Algorithms are recipes

Here is a recipe for deducing the square root of a number


x(attributed to Heron of Alexandria) in the first century
guess & check
Start with guess number g
If g*g is close enough to x, stop and say that g is the answer
Otherwise make a new guess, by averaging g and x/g !
Using this new guess, repeat the process until we get close
enough
From an algorithm generate the result-programing
Algorithm to program
A program is a set of instructions.
When you write down directions to your house for a friend
Turn left at the end of main Street,
Go forward three blocks, and
If you get to the gas station, turn around- that is my house(
execute it)
An algorithm is encoded as a program in a specific
programming language.
Languages have syntax
The requirements of form punctuation, spacing, spelling,
etc.
Algorithm to program

Languages have semantics


What happens as a result of an instruction values
replaced, computations done, comparisons made, etc.
Programs encode logic
If the language is used perfectly, but the logic is faulty, the
results will be wrong.
Computers do exactly what you tell them to do,
not necessarily what you intended for them to do!
Introduction to python

Python is a high-level, interpreted, interactive and object oriented-


scripting language.
A High-Level Language:what we mean is that there are levels
between the inner workings of the computer and what we see.
Python is Interpreted: This means that it is processed at runtime by
the interpreter and you do not need to compile your program
before executing it.
Python is Interactive: This means that you can actually sit at a
Python prompt and interact it directly to write your programs.
Python is Object-Oriented: This means that Python supports
Object-Oriented style or technique of programming that
encapsulates code within objects.
Introduction to python: Python Features
Some of Feature include:
Easy-to-learn: Python has relatively few keywords, simple structure, and a
clearly defined syntax. This allows the student to pick up the language in
a relatively short period of time.
Easy-to-read: Python code is clearly defined and if well written visually
simple to read and understand.
Easy-to-maintain: Python's success is that its source code is fairly easy-to-
maintain.
A broad standard library: One of Python's greatest strengths is the bulk of
the library is very portable and cross-platform compatible on Linux,
Windows, and Macintosh.
Interactive Mode: Support for an interactive mode in which you can enter
results from a terminal right to the language, allowing interactive testing
and debugging of snippets of code.
Many more features
Introduction to Console vs. GUI

There are three different ways to start Python:


The Console: An output medium for a program to show
exclusively text-based output.
Interactive Interpreter: You can enter python and start
coding right away in the interactive interpreter by starting
it from the command line.
You can do this from linux, DOS, or any other system
which provides you a command-line interpreter or shell
window.
>>>
Introduction to Console vs. GUI

Script from the Command-line: A Python script can be


executed at command line by invoking the interpreter on
your application, as in the following:
python # Unix/Linux

Graphical User Interface: An output medium that uses more


than just text, like forms, buttons, tabs, and more. More
programs are graphical user interfaces.
Introduction to Console vs. GUI

Integrated Development Environment (IDE): You can run Python


from a graphical user interface (GUI) environment. All you need
is a GUI application on your system that supports Python.
Data Types
Python has a big list of important structural features that make
it an efficient programming tool,
Python has some standard types that are used to define the
operations possible on them and the storage method for each
of them.
Data Type: The type of content a variable holds, like an integer
or a string of characters. Fixed values such as
numbers,
letters, and
strings are called constants or primitives - because
their value does not change
Python has Primitive constructs(standard data types):
Number(integer, floating point and complex number)
String /characters English words
Simple operators /Logical Operators
String constants use single-quotes (')
or double-quotes (")
>>> print 123
123
>>> print 98.6
98.6
>>> print 'Hello world'
Hello world
Conversions

Python converts numbers internally in an expression


containing mixed types to a common type for evaluation.
But sometimes, you'll need to convert a number explicitly
from one type to another to satisfy the requirements of an
operator or function parameter.---- type() function
Type int(x) to convert x to a plain integer.
Type long(x) to convert x to a long integer.
Type float(x) to convert x to a floating-point number.
Type complex(x) to convert x to a complex number with real part x and
imaginary part zero.
Type complex(x, y) to convert x and y to a complex number with real
part x and imaginary part y. x and y are numeric expressions
Type Conversions

>>> print float(99) /100


When you put an integer 0.99
>>> i = 42
and floating point in an >>> type(i)
expression the integer is <type 'int'>
implicitly converted to a >>> f = float(i)
>>> print f
float 42.0
You can control this with >>> type(f)
the built in functions <type 'float'>
>>> print 1 + 2 * float(3) / 4 - 5
int() and -2.5
float() >>>
Python Reserved Words

The following list shows the reserved words in Python.


These reserved words may not be used as constant or variable
or any other identifier names.
Reserved words contain lowercase letters only.

and, exec, not, assert, finally, or, break, for, pass, class, from,
print, continue, global, raise, def, if, return, del, import, try,
elif, in, while, else, is, with, except, lambda, yield.
Python Identifiers

A Python identifier is a name used to identify


a variable,
function,
class,
module, or other object.
An identifier starts with a letter A to Z or a to z or an
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.
Introduction to Variables in Python

What is a variable?
Variables: Alphanumeric (letters and numbers) identifiers
that hold values, like integers, strings of characters, and
dates.
Value: The content of some variable.
Examples of Variables
myAge= 29
The variable myAge might hold the value 29.
yourName=Adane
The variable yourName might hold the value Adane
Assigning Variables

In most programming languages, the variable receiving the value


is always on the left of the assignment operator (usually an
equals sign), and the value itself is always on the right.
numCats=2, 3
myNumber1 = 5
Different Kinds of Variables
a = A text message.
b=3
c = 7.4
d = False
For each of the following variables, select which type of data it
holds when this code is done running.
Assignment(writes)

Variables are stored in memory.


Initially memory is sort of blank like
table shown in fig() a 4, 10
Assigning a variable associates a new
name with a new value

>>> a = 4

Reassigning a variable updates its


value
>>>a= 10
Assignment (writes)
Some special variable types occupy
more than one space in memory
a=10 a 10

b =sally b S
a
We can view an assignment as a l
write to memory l
The variable represents a y
container in memory
Assignment places, or writes the
value into that container
Assignments of variables
A variable is a named place in the memory where a
programmer can store data and later retrieve the data
using the variable name
Programmers get to choose the names of the variables
The declaration happens automatically when you assign a
value to a variable.
The equal sign (=) is used to assign values to variables.
You can change the contents of a variable in a later
statement

x = 12.2 x 12.2=100
y = 14
y = 14
x = 100
Assignment with expression

x=2 Assignment Statement


x=x+2 Assignment with expression
Print statement
print x
Assignment Statements
An assignment statement consists of an expression on the
right hand side and a variable to store the result

x = 3.9 * x * ( 1 - x )
A variable is a memory
location used to store a
X= 0.6
value (x=0.6).
0.6

0.6
x = 3.9 * x * ( 1 - x )

Right side is an expression. 0.4


Once expression is valuated,
the result is placed in
(assigned to) x. 0.93
Simultaneous Assignment
sum, diff = x+y, x-y
How could you use this to swap the values for x and y?
x=y
y=x
Why does this not work?
We could use a temporary variable
Swapping x and y with a temporary
>>>z = x
>>>x = y
>>>y = z Temporary variable
This is cumbersome (but a must in most languages)
We need an extra box of memory to do this
Simultaneous Assignment
We can swap the values of two variables quite easily in
Python!
x, y = y, x
>>> x = 3
>>> y = 4
>>> print x, y
3, 4
>>> x, y = y, x
>>> print x, y
4 ,3
Assignments

Multiple Assignment: You can also assign a single value to


several variables simultaneously. For example:
a=b=c=1
Here, an integer object is created with the value 1, and all
three variables are assigned to the same memory location.
You can also assign multiple objects to multiple variables. For
example:
a, b, c = 1, 2, "john"
Here two integer objects with values 1 and 2 are assigned to
variables a and b, and one string object with the value "john"
is assigned to the variable c.
Operators

What is an operator?
Simple answer can be given using expression
4 + 5 is equal to 9.
Here 4 and 5 are called operands and + is called operator.
Python language supports following type of operators.
Arithmetic / Mathematical Operators
Comparision Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Logical Operators; Boolean

Logical Operators : Establishing the truth or falsehood of


relationships among variables in our programs.
The logical operators supported by Python language are AND,
OR and NOT.
Assume variable x = 10 and y = 20 then:
Logical AND operator.
If both the operands are true then then condition becomes true.
(x and y) is true.
Logical OR Operator.
If any of the two operands are non zero then then condition
becomes true. (x or y) is true.
Logical Operators; Boolean

Logical NOT Operator.


Use to reverses the logical state of its operand. If a condition is
true then Logical NOT operator will make false.

Logical operators in Python


Operator Meaning Example
True if both the operands
and x and y
are true
or True if either of the x or y
operands is true
True if operand is false
not (complements the not x
operand)
Mathematical Operators

Mathematical Operators: Using arithmetic operators (addition,


multiplication, etc.) to modify the values of variables in our
programs.
The main Arithmetic Operators
Addition
Subtraction
Multiplication
Division
Power and
Modulus- remainder
Numeric Expressions
>>> print 4 ** 3 Arithmetic Operators
>>> x = 2 64
>>> x = x+ 2 Operator Operation
>>> print x + Addition
4
Subtractio
>>> y = 440 * 12 >>> j = 23 -
n
>>> print y >>> k = j % 5 Multiplicat
*
5280 ion
>>> print k
>>> z = y / 1000 3 / Division
>>> print z ** Power
5 Remainde
%
r
Operator Precedence Rules

Highest precedence rule to lowest precedence rule


Parenthesis are always respected
Exponentiation (raise to a power)
Multiplication, Division, and Remainder
Addition and Subtraction
Left to right Parenthesis
Power
Multiplication
Addition
Left to Right
Expressions

>>> x = 1 + 2 ** 3 / 4 * 5
1 + 2 ** 3 / 4 * 5
>>> print x
11
>>> 1+8/4*5

Parenthesis
Note 8/4 goes 1+2*5
before 4*5 because of the
Power left-right rule.
Multiplication
Addition
Left to Right 1 + 10

11
Comparison Operators

Boolean expressions ask a


question and produce a Yes Python Meaning
or No result which we use
< Less than
to control program flow
Less than or
Boolean expressions using <=
comparison operators Equal
evaluate to - True / False - == Equal to
Yes / No Greater than
Comparison operators look >=
or Equal
at variables but do not
change the variables
> Greater than
!= Not equal
Remember: = is used for assignment.
Comparison Operators

Python Comparison Operators: Assume a = 10 and b = 20 then:

== Checks if the value of two operands are equal or not, if yes then
condition becomes true. (a == b) is not true.
!= Checks if the value of two operands are equal or not, if values are not
equal then condition becomes true. (a != b) is true.
> Checks if the value of left operand is greater than the value of right
operand, if yes then condition becomes true. (a > b) is not true.
< Checks if the value of left operand is less than the value of right
operand, if yes then condition becomes true. (a < b) is true.
>= Checks if the value of left operand is greater than or equal to the value
of right operand, if yes then condition becomes true. (a >= b) is not
true.
<= Checks if the value of left operand is less than or equal to the value of
right operand, if yes then condition becomes true. (a <= b) is true.
Control Structures

Programming languages allow the programmer to specify the


operations to be carried out.
Control Structures: The general idea of lines of code that can
control other lines of code.
Control structures allow specification of
repetition,
ordering of operations, etc.
Conditionals: Lines of code (called if statements) that check
logical expressions to see if certain code blocks should run.
Loops: Lines of code that instruct the computer to repeat a
block of code until some condition is met.
Functions: Miniature programs within a larger program, each
with their own input, code, and output.
Exception Handling: Lines of code that instruct the computer
how to fail gracefully when errors are encountered.

Conditionals: do this only under these conditions


Looping: repeat this sequence of instructions while this
condition holds
Flow Control: Looping

Computers are often used to automate repetitive tasks.


Repeating identical or similar tasks without making errors is
something that computers do well .
Because iteration is so common, Python provides several
language features to make it easier.
Python has these two flow control or looping
for loop and
While loop
We are going to look at is the these two statement.
Indentation

Increase indent after an if statement or for/while statement


(after : )
Maintain indent to indicate the scope of the block (which
lines are affected by the if/for/while)
Reduce indent to back to the level of the if statement or for
statement to indicate the end of the block
Blank lines are ignored
- they do not affect indentation
Comments on a line by themselves are ignored w.r.t.
indentation
Flow Control: Looping
For and while statements can be used to control looping in a program:
The for Loop has the following
for name in range(max):
statements
Repeats for values 0 (inclusive) to max (exclusive)
>>> for i in range(5):
... print(i)
0
1
2
3
4
For Loops

There are some other


tools that we can use to
Steps to
customise our For Loop. Starting move up in
We can change the Number
starting number of our
loop. for x in range (m,n,o):
We can state the steps we Upper limit
want to go up in (it number
doesnt have to go up in what the
loop will stop
1s) at
For Loop Variations

for name in range(min, max):


statements

for name in range(min, max, step):


statements
Can specify a minimum other than 0, and a step other than 1
>>> for i in range(2, 6):
... print(i)
2
3
4
5
>>> for i in range(15, 0, -5):
... print(i)
15
10
5
For loops & the range() function
range returns a range of numbers
>>> range(3)
[0,1,2]
>>> range(1,3)
[1,2]
>>> range(2,5,2)
[2,4]
for and range:
for i in range(10):
print i
# Prints 0, 1, ..., 9
Syntax of the while Loop

while <Boolean expression>:


<statement-1>
<statement-2>

<statement-n>
A Boolean expression can be a
comparison of two numbers or
strings, using ==, !=, <, >, <=,
>=
These operations return the
Boolean values True or False
While Loops in Python
While Loops in Python
The x is simply a variable. It could have any We must
name. finish the
statement
It is however a special kind of variable known with a colon
as the most recent value

==
Start
while x != n:
X=0 >
<
Execute Command

The n is represents a value that we want x to either equal,


No not equal, be greater than, etc. depending on the condition
Does x
= 5? we want to use.

E.g. n=5 and the condition while x != 5 (not equal to 5) then


Yes
the loop would repeat until x equals 5.
Example:
1. Evaluate the condition
count = 0 # (loop co variable) at line 2
while (count < 9):
2. If the value is False,
count = count + 1 exit the while
print 'The count is:', count statement
----------------------- 3. If the value is True,
x = 1.0 #(loop co variable)
execute each of the
while x < 10.0:
statement in the body
print x, and then go back to the
x = x + 1.0 while statement at line
2
Break & Continue Statement

The break statement in for Char in 'Hello World':


if Char == 'e':
Python terminates the
break
current loop and resumes print Char
execution at the next H
statement. l
The program immediately l
skip the processing of the o

rest of the body of the loop,


W
for the current iteration. But o
the loop still carries on r
running for its remaining l
iterations d
The continue statement in for Char in 'Hello
Python returns the control to World':
the beginning of the while
loop. if Char == 'e':
The continue statement continue
rejects all the remaining print Char
statements in the current
iteration of the loop and
moves the control back to
the top of the loop.
The break and continue
H
statement can be used in
both while and for loops.
Standard loop behavior

Generally, for and while loops


Before the loop header, the loop control variable must be set
to the appropriate initial value --- Initalize outside the loop
Somewhere in the loop body, a statement must reset the loop
control variable -- test of loop variable inside the loop
so that the Boolean expression eventually becomes False, to
terminate the loop---- exit
Getting Python & Help

Getting Python:
The most up-to-date and current source code, binaries,
documentation, news, etc. is available at the official website of
Python:Python Official Website : http://www.python.org/
Documentation
You can download the Python documentation from the following site.
The documentation is available in HTML, PDF, and PostScript formats:
http://docs.python.org/index.html
Tutorial
You should definitely check out the tutorial on the Internet at:
http://docs.python.org/tutorial/.
Assignment 1

Write for loops that will print the following


sequences:
a)0, 1, 2, 3, 4, 5, 6, 7, 8 , 9, 10
b)0, 2, 4, 6, 8
c)1, 3, 5, 7, 9
d)20, 30, 40, 50, 60

Write countdown of number, n=10 with a


statement: