Basic Programming Using Python
Basic Programming Using Python
using Python
Module Objectives
Agenda
Overview of Python
Programming with Python
Variables, Expressions, Statements
Functions
Conditions
Iteration
To make learners grounded with the basics of computer programming
through Python as we strongly believe that Python is the future.
Problem Solving
History of Python
History of Python
What is Python?
Python is a high-level, interpreted, interactive and objectoriented scripting language. Python was designed to be highly
readable which uses English keywords frequently where as other
languages use punctuation and it has fewer syntactical
constructions than other languages.
Lets discuss all of these bold words, one by one:
1.
2.
Interpreted
3.
Interactive
4.
Object oriented
1.
2.
Interpreted Language
10
Interpreted Language
11
By Object Oriented it means that, Python supports ObjectOriented style or technique of programming that encapsulates
code within objects.
12
What is a program ?
13
Getting Started
There are two ways to write a program in Python :
Interactive Mode Programming:
You type Python statements into the Python shell and the
interpreter immediately prints the result.
Type the following text to the right of the Python prompt and press
the Enter key:
If you are running new version of Python, then you would need to
use print statement with parenthesis like print ("Hello, Python!");.
15
Getting Started
Script Mode Programming:
16
If you are not sure what type a value has, the interpreter can tell
you.
18
Strings belong to the type str and integers belong to the type
int. Less obviously, numbers with a decimal point belong to a
type called float, because these numbers are represented in a
format called floating-point.
What about values like "17" and "3.2"? They look like numbers,
but they are in quotation marks like strings.
19
Variable
20
Variable Names
21
Keywords
22
Statement
23
Expressions
24
The following are all legal Python expressions whose meaning is more
or less clear:
The symbols +, -, and /, and the use of parenthesis for grouping, mean
in Python what they mean in mathematics. The asterisk (*) is the
symbol for multiplication, and ** is the symbol for exponentiation.
25
Order of Operations
P Parentheses
E Exponentiation
M Multiplication
D Division
A Addition
S Subtraction
26
Operations on Strings
27
Operations on Strings
28
Input
29
Comments
In this case, the comment appears on a line by itself. You can also
put comments at the end of a line:
30
Activity
In this activity, you will:
1.
Record what happens when you print the following:
1.
N=7
2.
7+5
3.
5.2 , this, 4-2, that, 5/2.0
2.
The difference between input and raw_input is that input
evaluates the input string and raw_input does not. Try the
following in the interpreter and record what happens:
>>> x = input()
3.14
>>> type(x)
>>> x = raw_input()
3.14
>>> type(x)
31
Activity
>>> x = input()
'The knights who say "ni!"'
>>> x
3.
32
Activity
4.
5.
33
Functions
Definition of a Function
A function is a block of organized, reusable code that is used to perform a
single, related action. Functions provide better modularity for your
application and a high degree of code reusing.
Simple rules to define a function in Python:
Function blocks begin with the keyword def followed by the function
name and parentheses ( ).
The code block within every function starts with a colon (:) and is
indented.
35
Syntax of a function
36
Example: Function
Here is the simplest form of a Python function. This function
37
Calling a Function
Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is the example to call
printme() function:
38
39
Scope of a Variable
Global variables
Local variables
Variables that are defined inside a function body have a local scope,
and those defined outside have a global scope.
This means that local variables can be accessed only inside the
function in which they are declared, whereas global variables can be
accessed throughout the program body by all functions.
40
41
Local Variable
When you create a local variable inside a function, it only exists inside
the function, and you cannot use it outside. For example:
This function takes two arguments, concatenates them, and then prints
the result twice. We can call the function with two strings:
42
Activity
43
Conditions
Decision Making
45
Operators
46
Operators
47
Operators
48
Boolean Values
The Python type for storing true and false values is called bool.
Example:
>>> type(True)
<type 'bool'>
>>> type(true)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
49
Boolean Expression
>>> 5 == 5
True
>>> 5 == 6
False
50
If
statements
Ifelse
statements
Nested
if statements
51
If statement
a=100
if a==100:
print Value of a is 100
print Good Bye
Output:
Value of a is 100
Good Bye
52
Example:
var1 = 100
if var1:
print "1 - Got a true expression value"
else:
print "1 - Got a false expression value"
var2 = 0
if var2:
print "2 - Got a true expression value"
else:
print "2 - Got a false expression value"
print "Good bye!"
53
Output:
54
if choice == 'a':
function_a()
else:
print "Invalid choice."
55
Nested If Statement
56
Example
Assume x= 10 and y =5
if x == y:
print x, "and", y, "are equal"
else:
if x < y:
print x, "is less than", y
else:
print x, "is greater than", y
Output:
x is greater than y
Copyright 2013 Accenture All rights reserved.
57
58
59
60
In the last example, if the user had made the response a valid
Python expression by putting quotes around it, it would not have
given an error:
>>> speed = input(prompt)
What...is the airspeed velocity of an unladen swallow?
"What do you mean, an African or a European swallow?"
>>> speed 'What do you mean, an African or a European swallow?'
61
Type Conversion
Each Python type comes with a built-in command that attempts to convert values of
another type into that type. The int(ARGUMENT) command, for example, takes any
value and converts it to an integer, if possible, or complains otherwise:
>>> int("32") 32
>>> int("Hello")
ValueError: invalid literal for int() with base 10: 'Hello'
int can also convert floating-point values to integers, but remember that it truncates
the fractional part:
>>> int(-2.3)
-2
>>> int(3.99999)
3
>>> int("42")
42
>>> int(1.0)
1
62
Activity
2.
Try to evaluate the following numerical expressions in your head, then use the
Python interpreter to check your results:
a)>>> 5 % 2
b)>>> 9 % 5
c)>>> 15%12
d)>>> 12 % 15
e)>>> 0 % 7
f)>>> 7 % 0
if x < y:
print x, "is less than", y
elif x > y:
print x, "is greater than", y
else:
print x, "and", y, "are equal"
Wrap this code in a function called compare(x, y). Call comparethree times: one
each where the first argument is less than, greater than, and equal to the second
argument.
Copyright 2013 Accenture All rights reserved.
63
Activity
Enter the following expressions into the Python shell:
3.
a)
b)
c)
d)
e)
f)
g)
h)
i)
j)
k)
True or False
True and False
not(False) and True
True or 7
False or 7
True and 0
False or 8
"happy" and "sad"
"happy" or "sad"
"" and "sad"
"happy" and ""
Analyze these results. What observations can you make about values of
different types and logical operators? Can you write these observations in
the form of simple rules about and and or expressions?
64
Iteration
What is a Loop ?
66
Types of Loops
67
While Loop
Condition
If
condition
is true
Conditional
Code
Copyright 2013 Accenture All rights reserved.
If
condition
is false
68
Example
count = 0
while (count < 4):
print 'The count is:', count
count = count + 1
print "Good bye!
OUTPUT:
The count is: 0
The count is: 1
The count is: 2
The count is: 3
69
For Loop
The for loop in Python has the ability to iterate over the items of
any sequence.
70
Example
for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!
OUTPUT:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Copyright 2013 Accenture All rights reserved.
71
Activity
Time duration:
72
Activity
1.
Write a function sum_of_squares_of_digits that computes the sum of the squares of the
digits of an integer passed to it.
For example,sum_of_squares_of_digits(987) should return 194, since9**2 + 8**2 + 7**2 == 81 + 64 + 49
== 194.
def sum_of_squares_of_digits(n):
"""
>>> sum_of_squares_of_digits(1)
1
>>> sum_of_squares_of_digits(9)
81
>>> sum_of_squares_of_digits(11)
2
>>> sum_of_squares_of_digits(121)
6
>>> sum_of_squares_of_digits(987)
194
"""
Check your solution against the doctests above.
Copyright 2013 Accenture All rights reserved.
73
Summary
Summary
Problem Solving
2.
3.
4.
5.
6.
Iteration- Loops
75
Knowledge Check
76
Questions