Python Language
Content
Introduction
IDLE
Data types
Mathematical operators
Input /Output
Strings
Range() function
Control structure
Iteration
For loop and while loop
Introduction to Python
Python is a powerful modern computer programming language.
Python allows you to use variables without declaring them (i.e., it
determines types implicitly), and it relies on indentation as a
control structure.
Python was developed by Guido van Rossum, and it is free
software.
The object-oriented nature of Python was part of its design from
the very beginning.
Python is available on a wide variety of platforms.
Introduction to Python (Cont)
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.
You can download the latest version by visiting the Python home page,
at http://www.python.org.
Python has an interpreter.
Unlike human languages, the Python vocabulary is actually pretty
small.
The biggest pitfall with programming in C or C++ is that the
responsibility of memory management is in the hands of the developer.
The memory management is performed by the Python interpreter.
IDLE
An IDE is an integrated development environment
—one program that provides all the tools that
developer needs to write software.
To exit the Python interactive prompt, we need to
use an end-of-file character. Under Windows, this
corresponds to the Ctrl-Z key combination; in
Linux, it corresponds to Ctrl-D.
Alternatively, one can use the exit() function:
IDLE (Cont)
Reserved words
Variables
A variable can be any combination of letters, digits
and underscore characters.
The first character cannot be a digit.
Variables in Python are case sensitive: variable
and VARIABLE are not the same.
Reserved word cannot be used for the variables.
It should be a meaningful name.
WWW.64BITS.LK
Spacing is not allowed for the variables.
Example : X _LabName RESULT2
VaRiAbLe
Variables (Cont)
Variables (Cont)
Assigning Values to Variables:
Python variables do not have to be explicitly
declared 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.
Variables (Cont)
Built in types of Data
A data type is a set of values and a set of operations
defined on those values. Many data types are built
into the Python language.
In this section, we consider Python's built-in data
types int (for integers), float (for floating-point
numbers), str (for sequences of characters)
and bool (for true-false values).
Built in types of Data (Cont)
type() function
Mathematics Operators
Mathematics Operators (Cont)
Mathematics Operators (Cont)
Type the commands and get the output
Type the following commands and explain the output
-20// 3
-20%3
Operator Precedence
Print() function
A program consists of one or more statements. A statement
is an instruction that the interpreter executes.
The following statement invokes the print function to display
a message:
print("This is a simple Python program")
By default, the print function places a single space in
between the items it prints. Print uses a keyword argument
named sep to specify the string to use insert between items.
The name sep stands for separator.
Print() function (Cont)
Comments
In a Python command, anything after a # symbol is
a comment.
Comments are not part of the command, but
rather intended as documentation for anyone
reading the code. Multiline comments are also
possible, and are enclosed by triple double-quote
symbols:
For example:
print( " Hello world ") # this is a comment
input() function
The built-in function input() takes a string
argument. This string is used as a prompt. When the
input() function is called, the prompt is printed and
the program waits for the user to provide input via
the keyboard.
input(): Prompts the user for input with its string
argument and returns the string the user enters.
Find the difference between the outputs:
a=input(‘Enter a number:’)
print(a)
a=int(input(‘Enter a number:’))
print(a)
a=float(input(‘Enter a number:’))
print(a)
Built-in Functions
int(): Returns the integer form of its argument.
float(): Returns the float form of its argument.
str(): Returns the string of its argument.
Bool(): Returns the Boolean value True or False
chr(): Returns the character for the ASCII value
ord(): Returns the ASCII value
eval(): Returns the result of evaluating its string
argument as any Python expression, including
arithmetic and numerical expressions
Exercise
Write a program to read character and get the
corresponding ASCII value for the character entered.
Write a program to read a number and get the
corresponding character from the ASCII table.
Note: Open a new file in file menu and save the file
with the extension of .py
Built-in Functions (Cont)
Strings
A string is created by enclosing text in quotes. You
can use either single quotes, ', or double quotes, ". A
triple-quote can be used for multi-line strings.
To get the length of a string (how many characters it
has), use the built-in function len. For example,
len('Hello') is 5
Strings Concatenation and repetition
The operators + and * can be used on strings.
The + operator combines two strings. This operation
is called concatenation.
The * repeats a string a certain number of times.
Strings Concatenation and repetition (Cont)
Indexing
We will often want to pick out individual characters from a
string.
Python uses square brackets to do this.
The table below gives some examples of indexing the string
s='Python'
Slices
A slice is used to pick out part of a string. It behaves like a combination
of indexing and the range function.
Below we have some examples with the string
s='abcdefghij'.
Write the code and get the outputs?
S=‘ABCDEFGHIJKL’
1. S[2:6]
2. S[:8]
3. S[3:]
4. S[2:9:2]
5. S[-3:]
6. S[:]
7. S[::-1]
8. len(S)
The range function
The range function (Cont)
Execute the following codes:
for i in range(10):
print(i)
for i in range(10):
print(i, end=‘ ’)
for i in range(3,9):
print(i)
Conditional Statement
Comparison Operators
The comparison operators are ==, >, <, >=, <=,
and !=
That last one is for not equals.
Here are a few examples
Exercise
1. Write a python program to read the two numbers
and find the largest number.
2. Write a python program to read the three numbers
and find the minimum number.
3. Write a python program to read a number and
display the number as odd or even.
Iteration (Loops)
Computers are often used to automate repetitive
tasks.
For loops
Probably the most powerful thing about computers
is that they can repeat things over and over very
quickly.
Iteration and Loops
A loop repeats a sequence of statements
A definite loop repeats a sequence of statements a
predictable number of times
Count n for count in range(5): print('Hello!')
times
Hello
Hello
Hello
Statements Hello
Hello
The for Loop
Python’s for loop can be used to iterate a definite number of times
for <variable> in range(<number of times>): <statement>
Use this syntax when you have only one statement to repeat
Count n for count in range(5): print('Hello!')
times
Hello
Hello
Hello
Statements Hello
Hello
The for Loop
for <variable> in range(<number of times>): loop header
<statement-1>
<statement-2>
… loop body
<statement-n>
Use indentation to format two or more statements below the loop header
for count in range(3):
print('Hello!')
Count n print('goodbye')
times
Hello!
goodbye
Hello!
Statements goodbye
Hello!
goodbye
Using the Loop Variable
The loop variable picks up the next value in a sequence on each pass
through the loop
The expression range(n) generates a sequence of ints from 0 through
n - 1
loop variable
>>> for count in range(5):
print(count)
...
Count n
0
times
1
2
3
4
Statements
>>> list(range(5)) # Show as a list
[0, 1, 2, 3, 4]
Counting from 1 through n
The expression range(low, high) generates a sequence of ints
from low through high - 1
>>> for count in range(1, 6): print(count)
...
Count h - l 1
times 2
3
4
5
>>> list(range(1, 6)) # Show as a list
Statements
[1, 2, 3, 4, 5]
Skipping Steps in a Sequence
The expression range(low, high, step) generates a sequence of
ints starting with low and counting by step until high - 1 is
reached or exceeded
>>> for count in range(1, 6, 2):
Count (h - l + 1) print(count)
times ...
1
3
5
>>> list(range(1, 6, 2)) # Show as a list
[1, 3, 5]
Statements
Counting down in a Sequence
The expression range(high, low, step) generates a sequence of
ints starting with high and counting by step until low - 1 is
reached, when step is negative
>>> for count in range(4, 1, -1):
Count (h - l + 1) print(count)
times ...
4
3
2
>>> list(range(4, 1, -1)) # Show as a list
[4, 3, 2]
Statements
Accumulator Loop: Summation
Compute and print the sum of the numbers between 1 and 5, inclusive
total = 0
for n in range(1, 6):
total = total + n
print(total)
In this program, the variable total is called an accumulator
variable
Iteration (Cont)
Output
Iteration (Cont)
Output
Iteration (Cont)
While Loop
while (conditional test):
Statement 01
Statement 02
…………………..
Statement n
While something is True keep running the loop, exit as soon as
the test is False.
The conditional test syntax is the same as for if and elif
statements.
Iteration (Cont)
The break statement
The break statement can be used to break out of a
for or while loop before the loop is finished
The Continue statement
This is a control flow statement that causes the
program to immediately skip the processing of the
rest of the body of the loop, for the current iteration.
But the loop still carries on running for its
remaining iterations:
The pass Statement
The pass statement in Python is used when a
statement is required syntactically but you do not
want any command or code to execute.
Exercise
Implement the following flowchart in Python and get
the output.
QUESTIONS??
THANK YOU!!