Download week2_basics - WordPress.com

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Selective Programming
Languages (week2)
Banda Ramadan
Outlines
This week we will cover Python basics as follows:
▪ Python syntax.
▪ Data types.
▪ Types of Operators
▪ Control structure: selection and repetition structures.
▪ User interaction: input from the user
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
2
Python Syntax
Identifiers:
▪ A Python identifier is a name used to identify a variable, function, class,
module or other object.
▪ An identifier starts with a letter or an underscore ( _ ) followed by zero or
more letters, underscores and digits.
▪ Punctuation characters such as @, $, and % are not allowed.
▪ Python is a case sensitive programming language.
▪ Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
3
Python Syntax
Reserved words
nd
exec
Not
as
finally
or
assert
for
pass
break
from
print
class
global
raise
continue
if
return
def
import
try
del
in
while
elif
is
with
else
lambda
yield
except
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
4
Python Syntax
Lines and Indentation
▪ Python doesn't use braces { } to indicate blocks of code for class
and function definitions or flow control.
▪ Blocks of code are denoted by line indentation.
▪ Python accepts single ('), double (") and triple (''' or """) quotes to
denote string literals.
Example:
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
5
Python Syntax
▪ No semicolon ( ; ) is required at the end of a Python statement.
▪ However, using the semicolon allows multiple statements on a
single line.
Ex:
import sys; x = 'foo'; sys.stdout.write(x + '\n')
▪ A single line comment is generated by adding (#) at the beginning
of a text.
▪ Multiple line comments should be generated by surrounding the text
with (''') or (""").
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
6
Standard Data Types
▪ Python has five standard data types:
− Numbers
− String
− List
− Tuple
− Dictionary
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
7
Python Numbers
▪ Number data types store numeric values. Number objects are
created when you assign a value to them.
For example :
num1 = 20
Num2 = 30.0
▪ Python supports different numerical types including integer and
float.
▪ There is no need to specify the type of the number variable. Python
will automatically identify its type
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
8
Python Strings
▪ 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.
Example:
str = "Hello World, this is me"
▪ Elements of the string can be accessed by its index as follows:
print("The first letter is: " + str[0])
Output
The first letter is: H
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
9
Python Strings
▪ Subsets of strings can be taken using the slice operator ([ ] and [:] ).
▪ The plus (+) sign is the string concatenation operator and the asterisk (*)
is the repetition operator.
Example:
str = 'Hello World!'
print(str)
#
print(str[0])
#
print(str[2:5])
#
print(str[2:])
#
print(str * 2)
#
print(str + "TEST") #
Prints
Prints
Prints
Prints
Prints
Prints
complete string
first character of the string
characters starting from 3rd to 5th
string starting from 3rd character
string two times
concatenated string
Output
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
10
Python Lists
▪ Lists are the most versatile of Python's compound data types.
▪ To some extent, lists are similar to arrays in C.
▪ One difference between them is that all 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 [:]) .
▪ The plus (+) sign is the list concatenation operator, and the asterisk
(*) is the repetition operator.
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
11
List Example
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print(list)
#
print(list[0])
#
print(list[1:3])
#
print(list[2:])
#
print(tinylist * 2) #
print(list + tinylist)
Prints complete list
Prints first element of the list
Prints elements starting from 2nd till 3rd
Prints elements starting from 3rd element
Prints list two times
# Prints concatenated lists
Output
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
12
Python Tuples
▪ A tuple is another sequence data type that is similar to the list.
▪ Tuples are enclosed within parentheses.
▪ The main differences between lists and tuples are: Lists are
enclosed in brackets ( [ ] ) and their elements and size can be
changed.
▪ Tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
▪ Tuples can be thought of as read-only lists.
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
13
Tuple Example
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2
tinytuple = (123, 'john')
print(tuple)
#
print(tuple[0])
#
print(tuple[1:3])
#
print(tuple[2:])
#
print(tinytuple * 2)
#
print(tuple + tinytuple)
)
Prints complete tuple
Prints first element of the tuple
Prints elements starting from 2nd till 3rd
Prints elements starting from 3rd element
Prints tuple two times
# Prints concatenated tuple
Output
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
14
Tuple Example
▪ The following code is invalid with tuple, because we attempted to
update a tuple, which is not allowed:
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000
list[2] = 1000
# Invalid syntax with tuple
# Valid syntax with list
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
15
Python Dictionary
▪ Python's dictionaries are kind of hash table type.
▪ They work like associative arrays or hashes and consist of keyvalue pairs.
▪ A dictionary key can be almost any Python type, but are usually
numbers or strings.
▪ Values can be any Python object.
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
16
Python Example
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print(tinydict)
# Prints complete dictionary
print(tinydict.keys())
# Prints all the keys
print(tinydict.values()) # Prints all the values
Output
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
17
Python Arithmetic Operators
Assume variable a holds 10 and variable b holds 21, then:
Operator
Description
Example
+ Addition
Adds values on either side of the operator.
a + b = 31
- Subtraction
Subtracts right hand operand from left hand operand.
a – b = -11
* Multiplication
Multiplies values on either side of the operator
a * b = 210
/ Division
Divides left hand operand by right hand operand
b / a = 2.1
% Modulus
Divides left hand operand by right hand operand and
returns remainder
Performs exponential (power) calculation on operators
b%a=1
** Exponent
//
a**b =10 to the power 20
Floor Division - The division of operands where the result 9//2 = 4 and 9.0//2.0 = 4.0, is the quotient in which the digits after the decimal point
11//3 = -4, -11.0//3 = -4.0
are removed. But if one of the operands is negative, the
result is floored, i.e., rounded away from zero (towards
negative infinity):
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
18
Python Comparison Operators
Assume variable a holds 10 and variable b holds 20, then
Operator
Description
==
If the values of two operands are equal, then the
(a == b) is not true.
condition becomes true.
If values of two operands are not equal, then
(a!= b) is true.
condition becomes true.
If the value of left operand is greater than the value (a > b) is not true.
of right operand, then condition becomes true.
!=
>
Example
<
If the value of left operand is less than the value of
right operand, then condition becomes true.
>=
If the value of left operand is greater than or equal (a >= b) is not true.
to the value of right operand, then condition
becomes true.
If the value of left operand is less than or equal to
(a <= b) is true.
the value of right operand, then condition becomes
true.
<=
(a < b) is true.
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
19
Python Assignment Operators
Assume variable a holds 10 and variable b holds 20, then:
Operator
Description
Example
=
Assigns values from right side operands to left side
operand
It adds right operand to the left operand and assign the
result to left operand
c = a + b assigns value of a + b into c
+= Add AND
c += a is equivalent to c = c + a
-= Subtract AND It subtracts right operand from the left operand and
assign the result to left operand
c -= a is equivalent to c = c - a
*= Multiply AND
It multiplies right operand with the left operand and
assign the result to left operand
c *= a is equivalent to c = c * a
/= Divide AND
It divides left operand with the right operand and assign
the result to left operand
c /= a is equivalent to c = c / ac /= a is equivalent to
c=c/a
%= Modulus AND It takes modulus using two operands and assign the
result to left operand
c %= a is equivalent to c = c % a
**= Exponent
AND
c **= a is equivalent to c = c ** a
Performs exponential (power) calculation on operators
and assign value to the left operand
//= Floor Division It performs floor division on operators and assign value to c //= a is equivalent to c = c // a
the left operand
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
20
Logical operator
The following logical operators are supported by Python language. Assume
variable a holds True and variable b holds False then:
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
21
Python Identity Operator
Identity operators compare the memory locations of two objects. There are two
Identity operators as explained below:
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
22
Data Conversion
▪ There are several built-in functions to perform conversion from one data
type to another.
int(x [,base])  Converts x to an integer. The base specifies the base if x is a string.
float(x)
 Converts x to a floating-point number.
str(x)
 Converts object x to a string representation.
repr(x)
 Converts object x to an expression string.
eval(str)
 Evaluates a string and returns an object.
tuple(s)
 Converts s to a tuple.
list(s)
 Converts s to a list.
set(s)
 Converts s to a set.
dict(d)
 Creates a dictionary. d must be a sequence of (key,value) tuples.
chr(x)
 Converts an integer to a character.
hex(x)
 Converts an integer to a hexadecimal string.
oct(x)
 Converts an integer to an octal string.
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
23
Decision Making
▪ IF Statement  Syntax:
if expression:
statement(s)
Output
1 - Got a true expression value
100
Good bye!
Example:
var1 = 100
if var1:
print("1 - Got a true expression value")
print (var1)
var2 = 0
if var2:
print("2 - Got a true expression value")
print(var2)
print("Good bye!")
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
Think ..
What will the output be if the
second condition was
if var2 == 0
24
Decision Making
▪ IF-ELSE statements – syntax:
If expression:
statement(s)
else:
statement(s)
Example:
amount=int(input("Enter amount: "))
Output
Enter amount: 600
Discount 30.0
Net payable: 570.0
Enter amount: 1200
Discount 120.0
Net payable: 1080.0
if amount<1000:
discount=amount*0.05
print("Discount“+ discount)
else:
discount=amount*0.10
print("Discount“+ discount)
print("Net payable:“+ amount-discount)
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
25
Decision Making
▪ The elif Statement
syntax:
Example:
amount=int(input("Enter amount: "))
Output
Enter amount: 600
Discount 30.0
Net payable: 570.0
if amount<1000:
Enter amount: 3000
discount=amount*0.05
Discount 300.0
print("Discount “ + discount)
Net payable: 2700.0
elif amount<5000:
discount=amount*0.10
Enter amount: 6000
print("Discount “ + discount)
Discount 900.0
else:
Net payable: 5100.0
discount=amount*0.15
print("Discount “+ discount)
print("Net payable: “+ (amount-discount))
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
26
Output
Decision Making
▪ Nested IF Statement
syntax:
Enter number: 8
divisible by 2 not divisible by 3
enter number: 15
divisible by 3 not divisible by 2
Example:
num=int(input("enter number: "))
if num % 2 ==0:
if num % 3 ==0:
print("Divisible by 3 and
else:
print("divisible by 2 not
else:
if num % 3 ==0:
print("divisible by 3 not
else:
print("not Divisible by 2
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
enter number: 12
Divisible by 3 and 2
enter number: 5
not Divisible by 2 not divisible by 3
2")
divisible by 3")
divisible by 2")
not divisible by 3")
27
Repetition structures
▪ While Loop Statements:
Example:
Syntax:
count = 0
while(count < 9):
print('The count is:‘+ count)
count = count + 1
print("Good bye!")
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
Output
The count
The count
The count
The count
The count
The count
The count
The count
The count
Good bye!
is:
is:
is:
is:
is:
is:
is:
is:
is:
0
1
2
3
4
5
6
7
8
28
Repetition structures
▪ The infinite loop:
Example:
var = 1
while var == 1 : # This constructs an infinite loop
num = int(input("Enter a number :"))
print("You entered: ", num)
print("Good bye!")
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
Output
Enter a number :20
You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number :11
You entered: 11
.
.
.
Infinite
29
Repetition structures
▪ Using else statement with while loop:
Example:
count = 0
while count < 5:
Output
0
1
2
3
4
5
is
is
is
is
is
is
less than 5
less than 5
less than 5
less than 5
less than 5
not less than 5
print(count + " is less than 5")
count = count + 1
else:
print(count + " is not less than 5")
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
30
Repetition structures
▪ For loop statement :
Syntax –
Example:
for letter in 'Python': # traversal of a string sequence
print ('Current Letter :‘+ letter)
print()
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # traversal of List sequence
print ('Current fruit :‘+ fruit)
Output
Current
Current
Current
Current
Current
Current
Letter
Letter
Letter
Letter
Letter
Letter
:
:
:
:
:
:
P
y
t
h
o
n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
print ("Good bye!")
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
31
Repetition structures
▪ For loop statement :
(iterating by sequence index)
What does range( ) do?
Try to type in Python
interpreter the following:
list(range(5))
Example:
Output
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print('Current fruit :'+ fruits[index])
What does len( ) do?
Try to print
len(fruits)
print ("Good bye!")
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
32
Repetition structures
▪ For loop statement :
(Using else statement)
What does break
do?
Also Investigate what
continue do
Output
Example:
numbers=[11,33,55,39,55,75,37,21,23,41,13]
The list does not contain
even number
for num in numbers:
if num%2==0:
print('the list contains an even number')
break
else:
print('the list does not contain even number')
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
33
Repetition structures
▪ Nested loops:
syntax:
Example:
import sys
for i in range(1,11):
for j in range(1,11):
k=i*j
print(k, end='')
print()
Output
12345678910
2468101214161820
36912151821242730
481216202428323640
5101520253035404550
6121824303642485460
7142128354249566370
8162432404856647280
9182736455463728190
102030405060708090100
Note the purpose of
end=''
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
34
User Interaction – Input from the user
Output
▪ User input:
Enter a number:10
The number you entered is a:
<class 'str'>
Enter a nother number: 10
The number you entered is a:
<class 'int'>
Example
x=input("Enter a number:")
print("The number you entered is a: ", type(x))
print()
y = int(input("Enter a nother number: "))
print("The number you entered is a: ", type(y))
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
35
Summary
This week we covered Python basics as follows:
▪ Python syntax.
▪ Data types.
▪ Types of Operators
▪ Control structure: selection and repetition structures.
▪ User interaction: input from the user.
@ Banda Ramadan - Applied Science Private University (Slides prepared from Tutorials Point, 2016, Python 3, Tutorials Point (I) Pvt. Ltd.)
36