0% found this document useful (0 votes)
17 views

py

py

Uploaded by

khaled9khaled999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

py

py

Uploaded by

khaled9khaled999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 153

Programming

1
What is Language?

Language is a mode of communication that

is used to share ideas, opinions with each

other. For example, if we want to teach

someone, we need a language that is

understandable by both communicators.


What is a Programming
Language?

A programming language is a computer language

that is used by programmers (developers) to

communicate with computers. It is a set of

instructions written in any specific language ( C,

C++, C#, Java, Python) to perform a specific task.


Types of Programming Languages
1. Low-level programming language
is machine-dependent (0s and 1s) programming
language. The processor runs low- level
programs directly without the need of a compiler
or interpreter, so the programs written in low-
level language can be run very fast. Machine
Language, Assembly Language
Types of Programming Languages
2. High-level programming language

This programming language requires a compiler

or interpreter to translate the program into

machine language (execute the program). It is

easy to read, write, and maintain. Python, Java,

JavaScript, PHP, C#, …...


Introduction to Python

• Python was created in 1990 by Guido Van


Rossum in Holland.
• Python runs on Mac, Linux, Windows, and
many other platforms.
• High level: you don't have to deal with low-
level machine details.
Introduction to Python
Python has been growing a lot recently partly
because of its many uses in the following
areas:

Data Analysis: it is a great language to


experiment with and has tons of libraries and tools
to handle data, create models, visualize results and
even deploy solutions. This is used in areas like
Finance, E-commerce, and Research.
Introduction to Python
Web Development: frameworks like Django and
Flask allow the development of web applications,
API's, and websites.

Machine Learning: Tensorflow and Pytorch are


some of the libraries that allow scientists and the
industry to develop and deploy Artificial Intelligence
solutions in Image Recognition, Health, Self-driving
cars, and many other fields.
Installing Python 3
Visit https://www.python.org/downloads/ and
download the latest version. The installation is just
like any other Windows-based software.
First Steps
There are two ways of using Python to run your
program - using the interactive interpreter prompt
or using a source file.

• Using The Interpreter Prompt:


Open the terminal in your operating and typing
python and pressing enter key.
you should see >>> where you can start typing stuff.
This is called the Python interpreter prompt.
First Steps
• Using The Interpreter Prompt:
First Steps
• Using The Interpreter Prompt:
How to Quit the Interpreter Prompt

If you are using the Windows command prompt,


press ctrl+z followed by the enter key.

Or:

Write exit() followed by the enter key.


First Steps
• source file:

We cannot type out our program at the interpreter


prompt every time we want to run something, so we
have to save them in files and can run our programs
any number of times.

To create our Python source files, we need an editor


software where you can type and save.
First Steps
Choosing An Editor :

• A good programmer’s editor will make your life


easier in writing the source files.

• A good editor will help you write Python programs


easily, making your journey more comfortable
and helps you reach your destination (achieve
your goal) in a much faster and safer way.
First Steps
Choosing An Editor :
Python
Wadhah S. Sebti
Running Code

You can run Python code directly in


the terminal as commands or you
can save the code in a file with the
.py extension and run the Python
file.
Running Code
Terminal:

Running commands directly in the terminal is


recommended when you want to run something
simple.

Open the command line and type python3:


C:>python3
Running Code
Terminal:
C:>python3
>>>
Let's test it by running our first program to perform basic math and add
two numbers.

>>> 2 + 2
The output is:
4
Syntax
Python is known for its clean syntax.

The language avoids using unnecessary characters to indicate some


specificity.

Semicolons:

• Python makes no use of semicolons to finish lines. A new line is


enough to tell the interpreter that a new command is beginning.
Syntax
Indentation

• Many languages use curly-brackets to define scopes.

• Python's interpreter uses only indentation to define when a


scope ends and another one starts.

• This means you have to be aware of white spaces at the


beginning of each line.
Syntax
Indentation

This definition of a function works:

def my_function():

print('First command’)

This doesn't work because the indentation of the second line is


missing and will throw an error:
def my_function():
print('First command')
Syntax
Case sensitivity and variables
Python is case sensitive. So the variables name and
Name are not the same thing and store different values.

name = ‘Ali’

Name = ‘Mona'
Syntax
Comments

to comment something in your code, use the hash mark #. The


commented part does not influence the program flow.

# this will print Ali’s name

A = “Ali”

print(A)
Comments
Comments are any text to the right of the # symbol and is
mainly useful as notes for the reader of the program.

For example:
#calculates the sum of any given two numbers
a+b
Print('hello world’) # Note that print is a
statement
Data Types
• In programming, a data type consists of a set of
values and a set of operations that can be performed
on those values. A literal is the way a value of a data
type looks to a program.
Data Types
• Python interpreter evaluates a literal, the value it
returns is simply that literal. Table 2-2

• shows example literals of several Python data types.


Data Types
• String

In Python, a string literal is a sequence of characters


enclosed in single or double quotation marks. The following
session with the Python shell shows some example strings:
Data Types
• String
>>> 'Hello there!'
'Hello there!'
>>> "Hello there!"
'Hello there!'
>>> ''
''
>>> ""
Data Types
• String
>>> ''
''
>>> ""
''
The last two string literals (‘ ’ and "“ ) represent the
empty string. Although it contains no characters, the
empty string is a string nonetheless.
Data Types
• String
>>> "I'm using a single quote in this string!"
"I'm using a single quote in this string!"
>>> print("I'm using a single quote in this string!")
I'm using a single quote in this string!
Control Codes within Strings
The characters that can appear within strings include letters of the
alphabet (A-Z, a-z), digits (0-9), punctuation (., :, ,, etc.), and other
printable symbols (#, &, %, etc.). In addition to these “normal”
characters, we may embed special characters known as control
codes or Escape Sequences.

The backslash symbol (\) signifies that the character that follows it is
a control code, not a literal character.
Control Codes (Escape Sequences)
Control Codes within Strings
The \n control code represents the newline control code which moves
the text cursor down to the next line in the console window.

\t for tab,

\b for backspace,

\a for alert (or bell).

The \b and \a do not produce the desired results in the interactive


shell, but they work properly in a command shell.
Control Codes within Strings
print('A\nB\nC') the output:
A
B
print('D\tE\tF') C
DEF
print('WX\bYZ') WYZ
123456

print('1\a2\a3\a4\a5\a6')
Control Codes within Strings
print("Did you know that 'word' is a word?")

print('Did you know that "word" is a word?')

print('Did you know that \'word\' is a word?')

print("Did you know that \"word\" is a word?")


the output:
Did you know that 'word' is a word?
Did you know that "word" is a word?
Did you know that 'word' is a word?
Did you know that "word" is a word?
Variables
• In any program, you need to store and manipulate data to
create a flow or some specific logic.

• That's what variables are for.

• You can have a variable to store a name, another one to


store the age of a person, or even use a more complex type
to store all of this at once like a dictionary.
Variables
name='Bob'

age=32

You can use the print() function to show the value of a


variable.

print(name)

print(age)
Variables
In summary, variable names:

• Are Case sensitive: time and TIME are not the same

• Have to start with an underscore _ or a letter (DO NOT start with a


number)

• Are allowed to have only numbers, letters and underscores. No


special characters like: #, $, &, @, etc.

• This, for instance, is not allowed: party#time, 10partytime.


Variables and Assignment
x = 10

This is an assignment statement. An assignment statement


associates a value with a variable. The key to an assignment
statement is the symbol = which is known as the assignment
operator.

It is best to read x = 10 as “x is assigned the value 10,”

or “x gets the value 10.”


Variables and Assignment
x = 10

print(x)

x = 20

print(x) the print statements produce different results:


10
x = 30 20
30
print(x)
Variables and Assignment
x = 10
uses the str function to treat x as a
print('x = ' + str(x)) string so the + operator will use
string concatenation:
x = 20 print('x = ' + str(x))
print('x = ' + str(x)) the output:
x = 10
x = 30 x = 20
x = 30
print('x = ' + str(x))
Variables and Assignment
x = 10
illustrates the print function
print('x = ‘ , x) accepting two parameters. The first
parameter is the string 'x =', and the
x = 20 second parameter is the variable x
bound to an integer value.
print('x = ‘ , x)
the output:
x = 30 x = 10
x = 20
print('x = ‘ , x) x = 30
Variables and Assignment
A programmer may assign multiple variables in one
statement.
x, y, z = 100, -45, 0
print('x =', x, ' y =', y, ' z =', z)

the output:
x = 100 y = -45 z = 0
Types
Determining the Type

• First of all, let's learn how to determine the data type.

• Just use the type() function and pass the variable of your choice as
an argument, like the example below.

type(my_variable)

print(type(my_variable))
Types
Boolean:

A boolean type variable can only represent either True or


False.

my_bool = True

print(type(my_bool))

<class 'bool'>
Types
Numbers

There are three numeric types: int, float, and complex.

• Integer

my_int = 32

print(type(my_int))

<class 'int'>
Types
Numbers

• Float

my_float = 32.85

print(type(my_float))

<class 'float'>
String Concatenation
• String

You can join two or more strings to form a new string using the
concatenation operator +

.Here is an example:

>>> "Hi " + "there, " + "Ken!"

'Hi there. Ken!'


String Concatenation
• String

word1 = 'New '

word2 = 'York'
print(word1 + word2)
Output = NewYork
Python

Wadhah S. Sebti
Expressions

Expressions provide an easy way to perform operations on data


values to produce other data values. You saw strings used in
expressions earlier. When entered at the Python shell prompt, an
expression’s operands are evaluated, and its operator is then
applied to these values to compute the value of the expression.
In this section, we examine arithmetic expressions in more detail.
Expressions
Arithmetic Expressions
An arithmetic expression consists of operands and operators
combined in a manner that is already familiar to you from
learning algebra. Table 2-6 shows several arithmetic operators
and gives examples of how you might use them in Python code.
Expressions
Expressions
Type Conversions
A type conversion function is a function with the same name as
the data type to which it converts.
Type Conversions
>>> profit = 1000.55
>>> print('$' + profit)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'float' objects
To solve this problem, we use the str function to convert the
value of profit to a string and then concatenate:
>>> print('$' + str(profit))
$1000.55
Type Conversions
>>> profit = ‘1000’ # profit is string type
>>> print(50 + profit)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
50 +profit
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> print(50 + int(profit))
1050
User Input
As you create programs in Python, you’ll often want your programs to
ask the user for input. You can do this by using the input function.
This function causes the program to stop and wait for the user to
enter a value from the keyboard. When the user presses the
return or enter key, the function accepts the input value and makes it
available to the program.
A program that receives an input value in this manner typically saves
it for further processing.
User Input
The following example receives an input string from the user and
saves it for further processing.
>>> name = input("Enter your name: ")
Enter your name: Ken Lambert
>>> name
'Ken Lambert'
>>> print(name)
Ken Lambert
User Input
Enter an input statement using the input function at the shell prompt.
When the prompt asks you for input, enter a number. Then, attempt
to add 1 to that number.
>>> num1 = input("Enter a number: ")
Enter a number: 25
>>> int(num1 + 1)
26
>>> print(int(num1) + 1)
User Input
Enter an input statement using the input function at the shell prompt.
When the prompt asks you for input, enter a number. Then, attempt
to add 1 to that number.
>>> num1 = int(input("Enter a number: "))
Enter a number: 25
>>> num1 + 1
26
>>> print(num1 + 1)
User Input
>>> num1 = int(input("Enter a number: "))
Enter a number: 25.5
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
length = int(input('Enter a NO1.: '))
ValueError: invalid literal for int() with base 10: '2.5'
User Input
>>> num1 = float(input("Enter a number: "))
Enter a number: 25.5
>>> num1 + 1
26.5
>>> print(num1 + 1)
26.5
User Input
Write a program that calculates and prints “NO1 + NO2 = ”the
summation of 2 numbers.
>>> num1 = float(input("Enter NO1: "))
Enter NO1: 99
>>> num2 = float(input("Enter NO2: "))
Enter NO2: 60.1
>>> print(“NO1 + NO2 = ”, NO1 + NO2)
NO1 + NO2 = 159.1
Python
Selection Statements

Wadhah S. Sebti
Selection
Selection: if and if-else Statements
In this section, we explore several types of selection statements, or
control statements, that allow a computer to make choices.

Before you can test conditions in a Python program, you need to


understand the Boolean data type. The Boolean data type consists of
only two data values—true and false. In Python, Boolean literals can be
written in several ways, but most programmers prefer to use the
standard values True and False.
Selection
Selection: if and if-else Statements
Simple Boolean expressions consist of the Boolean values True or
False, variables bound to those values, function calls that return
Boolean values, or comparisons. The condition in a selection statement
often takes the form of a comparison.
Selection
Selection: if and if-else Statements
Selection
The following session shows some example comparisons and their values:
>>> 4 == 4
True
>>> 4 != 4
False Note that == means equals,
>>> 4 < 5 whereas = means assignment.
True
>>> 4 >= 3
True
>>> "A" < "B"
True
Selection
One-Way Selection Statements
The simplest form of selection is the if statement. This type of control
statement is also called a one-way selection statement, because it
consists of a condition and just a single sequence of statements.
if Statement
Here is the syntax for the if statement:
if <condition>:
<sequence of statements>
>>> if x < 0:
x = –x
Selection
if-else Statements

The if-else statement is the most common type of selection statement. It


is also called a two-way selection statement, because it directs the
computer to make a choice between two alternative courses of action.
Selection
if-else Statements
Our next example prints the maximum and minimum of two input numbers.
first = 10
second = 20
if first > second:
maximum = first
minimum = second
else:
maximum = second
minimum = first
Selection
if-else Statements
print("Maximum:", maximum)
print("Minimum:", minimum)
Selection
Multi-Way if Statements
a program is faced with testing several conditions that entail more than two
alternative courses of action.
The syntax of the multi-way if statement is the following:
if <condition-1>:
<sequence of statements-1>
elif <condition-n>:
<sequence of statements-n>
else:
<default sequence of statements>
Selection
Multi-Way if Statements

The process of testing several conditions and responding accordingly can be


described in code by a multi-way selection statement. Here is a short
Python script that uses such a statement to determine and print the letter
grade corresponding to an input numeric grade:
Selection
Multi-Way if Statements
number = int(input("Enter the numeric grade: "))
if number > 89:
letter = 'A'
elif number > 79:
letter = 'B'
elif number > 69:
letter = 'C'
else:
letter = 'F'
print("The letter grade is", letter)
Selection
Logical Operators and Compound Boolean Expressions
The two conditions can be combined in a Boolean expression that uses the
logical operator.
Selection
Logical Operators and Compound Boolean Expressions
Selection
Logical Operators and Compound Boolean Expressions
The next example verifies some of the claims made in the truth tables in Figure 3-5:
>>> A = True
>>> B = False
>>> A and B
False
>>> A or B
True
>>> not A
False
Selection
Logical Operators and Compound Boolean Expressions
The next code segment accepts only valid inputs for our grade conversion
script and displays an error message otherwise:
number = int(input("Enter the numeric grade: "))
if number > 100:
print("Error: grade must be between 100 and 0")
elif number < 0:
print("Error: grade must be between 100 and 0")
else:
# The code to compute and print the result goes here
Selection
Logical Operators and Compound Boolean Expressions
The two conditions can be combined in a Boolean expression that uses
the logical operator or. The resulting compound Boolean expression
simplifies the code somewhat, as follows:
number = int(input("Enter the numeric grade: "))
if number > 100 or number < 0:
print("Error: grade must be between 100 and 0")
else:
print(“Your grade is: “,number)
Selection
Logical Operators and Compound Boolean Expressions

Yet another way to describe this situation is to say that if the number is
greater than or equal to 0 and less than or equal to 100, then we want the
program to perform the computations and output the result; otherwise, it
should output an error message. The logical operator and can be used to
construct a different compound Boolean expression to express this logic:
Selection
Logical Operators and Compound Boolean Expressions

number = int(input("Enter the numeric grade: "))

if number >= 0 and number <= 100:

print(“Yes: the grade is OK")

else:

print("Error: grade must be between 100 and 0")


Python
PROBLEM SOLVING

Wadhah S. Sebti
PROBLEM SOLVING
Python Assignment Operators:

Before writing a program, first needs to find a


procedure for solving the problem. The program
written without proper pre-planning has higher
chances of errors.
PROBLEM SOLVING
Steps of problem solving
Problem Definition: understand the problem.
Problem Analysis: how to solve the problem.
solution design: using algorithms or flowchart.
solution Programming: Write the code.
Solution Implementation: try to run the code without
errors.
Program Execution: real run.
PROBLEM SOLVING
PROBLEM SOLVING
solution design: (algorithm)
. An algorithm is a sequence of steps to solve a
particular problem
or
algorithm is an ordered set of unambiguous
steps that produces a result and terminates in
a finite time.
PROBLEM SOLVING
solution design: (algorithm)
Example 1:
To determine the sumo f two numbers A and B
the following algorithm may be used.Step 1:
start
PROBLEM SOLVING
solution design: (algorithm)
Step 1: Start
Step 2: Read two numbers say A, B
Step 3: Calculate the sum, (Sum = A+B).
Step 4: Display Sum.
Step 5: Stop.
PROBLEM SOLVING
solution design: (algorithm)
Step 1: Start
Step 2: Input first numbers say A
Step 3: Input second number say B
Step 4: SUM = A + B
Step 5: Display SUM
Stop6: Stop
PROBLEM SOLVING
solution design: (algorithm)
Example 2:
Find the Area of rectangle, where:
area = length*width
PROBLEM SOLVING
solution design: (algorithm)
Step 1: Start
Step 2: Input Length say L
Step 3: Input Width say W
Step 4: Area = L * W
Step 5: Display Area
Stop6: Stop
PROBLEM SOLVING
solution design: (FLOWCHART)
Flowchart is diagrammatic /Graphical
representation of sequence of steps to solve a
problem. To draw a flowchart following
standard symbols are use:
PROBLEM SOLVING
solution design: (FLOWCHART)
PROBLEM SOLVING
solution design: (FLOWCHART)
PROBLEM SOLVING
solution design: (FLOWCHART)
Example 1:
Find the sum of two numbers
PROBLEM SOLVING
PROBLEM SOLVING
solution design: (FLOWCHART)
Example 2:
Find the Area of rectangle
PROBLEM SOLVING
Python
Loops

Wadhah S. Sebti
Loops
Python Assignment Operators:
Loops
Python Assignment Operators:
Loops
Python Assignment Operators:
Loops
Python Membership Operators:
Loops
Definite Iteration:
Loops are used when you need to repeat a block of
code a certain number of times or apply the same logic
over each item in a collection.

There are two types of loops: for and while.


Loops
For Loop (in):

Basic Syntax:

The basic syntax of a for loop is as below.


Loops
For Loop (in):

The list of cars contains three items.The for loop will iterate
over the list and store each item in the car variable,
and then execute a statement, in this case print(car), to
print each carin the console.
Loops
>>> for character in "Hi there!":

print(character, end = " ")

Hi there!
Loops
For Loop (range() function):

The range function is widely used in for loops because


it gives you a simple way to list numbers.

This code will loop through the numbers 0 to 5 and


print each of them.
Loops
For Loop (range() function):

In contrast, without the range() function, we would do


something like this.
Loops
•Here is a for loop that runs the output statement four times:

>>> for eachPass in range(4):

print(“Hello!")

Hello!

Hello!

Hello!

Hello!
Loops
•We can print the output statement four times at one line:

>>> for eachPass in range(4):

print(" Hello ", end = " ")

Hello! Hello! Hello! Hello!


Loops
Now let’s explore how Python’s exponentiation operator might be
implemented in a loop. Recall that this operator raises a number to a
given power. For instance, the expression 2 ** 3 computes the value of
23, or 2 * 2 * 2.
Loops
>>> number = 2

>>> exponent = 3

>>> product = 1

>>> for eachPass in range(exponent):

product = product * number

print(product, end = " ")

248
Loops
You can also definea start and stop using range().

>>> for count in range(1, 11):

print(count, end = " ")

1 2 3 4 5 6 7 8 9 10
Loops
Here we are starting in 5 and stoping in 10.The number
you set to stop is not included.
Loops
Here we starting in 10 and incrementing by 2 until 20,
since 20 is the stop, it is not included.
Loops
Loops That Count Down
>>> for count in range(2, 11, 2):
print(count, end = " ")

246810
>>> theSum = 0
>>> for count in range(2, 11, 2):
theSum += count
>>> theSum
30
Loops
Loops That Count Down
>>> for count in range(10, 0, -1):

print(count, end = " ")

10 9 8 7 6 5 4 3 2 1
Loops
Augmented Assignment
Expressions such as x = x + 1 or x = x + 2 occur so frequently in loops
that Python includes abbreviated forms for them. The assignment
symbol can be combined with the arithmetic and concatenation
operators to provide augmented assignment operations.
<variable> <operator>= <expression>
which is equivalent to
<variable> = <variable> <operator> <expression>
Loops
Augmented Assignment
Following are several examples:
a = 17
s = "hi"
a += 3 # Equivalent to a = a + 3
a -= 3 # Equivalent to a = a - 3
a *= 3 # Equivalent to a = a * 3
a /= 3 # Equivalent to a = a / 3
a %= 3 # Equivalent to a = a % 3
s += " there" # Equivalent to s = s + " there"
Loops
w h i l e Loops:
Basic Syntax:
The basic syntax of a while loop is as below.
Loops
w h i l e Loops:
The example below takes each value of number and
calculates its squared value.
Loops
theSum = 0.0

data = input("Enter a number or just enter to quit: ")

while data != "":

number = float(data)

theSum += number

data = input("Enter a number or just enter to quit: ")

print("The sum is", theSum)


Loops
Count Control with a while Loop
The next two code segments show the same summations with a for loop
and a while loop, respectively.
# Summation with a for loop # Summation with a while loop
theSum = 0 theSum = 0
for count in range(1, 100001): count = 1
theSum += count while count <= 100000:
print(theSum) theSum += count
count += 1
print(theSum)
Loops
Count Control with a while Loop
The next example shows two versions of a script that counts down, from an
upper bound of 10 to a lower bound of 1. It’s up to you to decide which
one is easier to understand and write correctly.

# Counting down with a for loop # Counting down with a while loop

for count in range(10, 0, –1): count = 10

print(count, end = " ") while count >= 1:


print(count, end = " ")
count -= 1
Loops
The while True Loop and the break Statement
Our next example modifies the input section of the grade-conversion
program to continue taking input numbers from the user until she enters
an acceptable value. The logic of this loop is similar to that of the previous
example.
Loops
The while True Loop and the break Statement
Simply use the break keyword, and the loop will stop its
execution.
Python
Strings and Text Files

Wadhah S. Sebti
The Structure of Strings
Unlike an integer, which cannot be decomposed into more primitive
parts, a string is a data structure. A data structure is a compound unit
that consists of several other pieces of data. A string is a sequence of
zero or more characters. Recall that you can mention a Python string
using either single quote marks or double quote marks. Here are some
examples:
The Structure of Strings
>>> "Hi there!"
'Hi there!'
>>> ""
''
>>> 'R'
'R'

Note that the shell prints a string using single quotes, even when you
enter it using double quotes. In this book, we use single quotes with
single-character strings and double quotes with the empty string or
with multi-character strings.
The Structure of Strings
When working with strings, the programmer sometimes must be aware
of a string’s length and the positions of the individual characters within
the string. A string’s length is the number of characters it contains.
Python’s len function returns this value when it is passed a string.
>>> len("Hi there!")
9
>>> len("")
0
The Structure of Strings
The positions of a string’s characters are numbered from 0, on the left,
to the length of the string minus 1, on the right. Figure 4-1 illustrates
the sequence of characters and their positions in the string "Hi there!".
Note that the ninth and last character, '!', is at position 8.

Figure 4-1 Characters and their positions in a string


The Structure of Strings
The string is an immutable data structure. This means that its internal
data elements, the characters, can be accessed, but cannot be
replaced, inserted, or removed.
The Subscript Operator
Although a simple for loop can access any of the characters in a string,
sometimes you just want to inspect one character at a given position
without visiting them all. The subscript operator [] makes this possible.
The simplest form of the subscript operation is the following:

<a string>[<an integer expression>]


The Subscript Operator
The first part of this operation is the string you want to inspect. The
integer expression in brackets indicates the position of a particular
character in that string. The integer expression is also called an index.
In the following examples, the subscript operator is used to access
characters in the string "Alan Turing":
The Subscript Operator
>>> name = "Alan Turing"
>>> name[0] # Examine the first character
'A'
>>> name[3] # Examine the fourth character
'n'
>>> name[len(name)] # Oops! An index error!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
The Subscript Operator
>>> name[len(name) - 1] # Examine the last character
'g'
>>> name[-l] # Shorthand for the last character
'g'
>>> name[-2] # Shorthand for next to last character
'n'
The Subscript Operator
The subscript operator is also useful in loops where you want to use
the positions as well as the characters in a string. The next code
segment uses a count-controlled loop to display the characters and
their positions:
>>> data = "Hi there!"
>>> for index in range(len(data)):
print(index, data[index])
The Subscript Operator
>>> data = "Hi there!"
>>> for index in range(len(data)):
print(index, data[index])
0H
1i
2
3t
4h
5e
6r
7e
8!
Slicing for Substrings
Some applications extract portions of strings called substrings. For
example, an application that sorts filenames according to type might
use the last three characters in a filename, called its extension, to
determine the file’s type (exceptions to this rule, such as the extensions
".py" and ".html", will be considered later in this chapter).
Slicing for Substrings
>>> name = "myfile.txt" # The entire string
>>> name[0:]
'myfile.txt'
>>> name[0:1] # The first character
'm'
>>> name[0:2] # The first two characters
'my'
>>> name[:len(name)] # The entire string
'myfile.txt'
>>> name[-3:] # The last three characters
'txt'
>>> name[2:6] # Drill to extract 'file'
'file'
Testing for a Substring with the in Operator
If you might want to pick out filenames with a .txt extension. A slice
would work for this, but using Python’s in operator is much simpler.
When used with strings, the left operand of in is a target substring, and
the right operand is the string to be searched. The operator in returns
True if the target string is somewhere in the search string, or False
otherwise.
Testing for a Substring with the in Operator
The next code segment traverses a list of filenames and prints just the
filenames that have a .txt extension:
>>> fileList = ["myfile.txt", "myprogram.exe", "yourfile.txt"]
>>> for fileName in fileList:
if ".txt" in fileName:
print(fileName)
myfile.txt
yourfile.txt
String Methods
Fortunately, Python includes a set of string operations called methods
that make tasks like length, count, lower, upper, ….. .

A method is always called with a given data value called an object,


which is placed before the method name in the call. The syntax of a
method call is the following:

<an object>.<method name>(<argument-1>,..., <argument-n>)


String Methods
String Methods
String Methods
String Methods
Examples:
>>> s = "Hi there!"
>>> len(s)
9
>>> s.center(11)
' Hi there! '
>>> s.count('e')
2
>>> s.endswith("there!")
True
>>> s.startswith("Hi")
True
>>> s.find("the")
3
String Methods
Examples:
>>> s.isalpha()
False
>>> 'abc'.isalpha()
True
>>> "326".isdigit()
True
>>> words = s.split()
>>> words
['Hi', 'there!']
String Methods
Examples:
>>> " ".join(words)
'Hithere!'
>>> " ". join(words)
'Hi there!'
>>> s.lower()
'hi there!'
>>> s.upper()
'HI THERE!'
>>> s.replace('i', 'o')
'Ho there!'
>>> " Hi there! ".strip()
'Hi there!'

You might also like