0% found this document useful (0 votes)
51 views85 pages

Unit P2 - Numbers and Strings

This document introduces variables, data types, and constants in Python. It discusses declaring and initializing variables to store values of different types like integers, floats, and strings. Variables can be updated by assigning new values. Constants are variables that should not change value after initialization. Descriptive naming of variables and constants improves readability of code. The document provides examples of defining, initializing, and updating variables in Python programs.

Uploaded by

ashenbandara007
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)
51 views85 pages

Unit P2 - Numbers and Strings

This document introduces variables, data types, and constants in Python. It discusses declaring and initializing variables to store values of different types like integers, floats, and strings. Variables can be updated by assigning new values. Constants are variables that should not change value after initialization. Descriptive naming of variables and constants improves readability of code. The document provides examples of defining, initializing, and updating variables in Python programs.

Uploaded by

ashenbandara007
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/ 85

Unit P2:

Numbers and
Strings
VARIABLES, VALUES, TYPES, EXPRESSIONS

Chapter 2

This Photo by Unknown Author is licensed under CC BY-SA


Introduction
▪ Numbers and character strings (text sequences) are important data
types in any Python program
o These are also the building blocks we use to build more complex data
structures
▪ In this Unit, you will learn how to work with numbers and text.
▪ We will write several simple programs that use them

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 2


Unit Goals
▪ To declare and initialize variables and constants
▪ To understand the properties and limitations of integers and
floating-point numbers
▪ To appreciate the importance of comments and good code layout
▪ To write arithmetic expressions and assignment statements
▪ To create programs that read, and process inputs, and display the
results
▪ To learn how to use Python strings

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 3


Variables 2.1

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 4


Variables
▪ A variable is a named storage location in a computer program, that
refers to a specific value
▪ There are many different types of values, each type used to store
different things

Variables Values

base 6
height 4
area
address 24.0
residence_city 'Corso Duca Degli Abruzzi'
birth_city
'Torino'

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 5


Variables
▪ You ‘define’ a variable by telling the interpreter:
o What name you assign to the variable (and you will later use to refer to it)
o The initial value of the variable

cans = 4 # defines & initializes the variable cans

▪ You use an assignment statement to place a value into a variable


o Initial value or new value (that replaces a previous value)

cans = 7 # changes the value

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 6


Variable Definition
▪ To define a variable, you must specify a name and an initial value.
o cans = 4 # defines & initializes the variable cans

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 7


Visualizing variables: http://pythontutor.com/

Values
and types
Variable names

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 8


The assignment statement
▪ Use the assignment statement = to place a new value into a
variable: the variable name will now refer to the new value
o cans = 4 # define cans and initialize to 4
o cans = 6 # change the value referred by cans, now refers
to the value 6
▪ Beware: the = sign is NOT used for comparison:
o It copies the value on the right side into the variable on the left side
o You will learn about the comparison operator in the next chapter

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 9


Assignment syntax
▪ The value computed on the right of the '=' sign is assigned to the
variable on the left

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 10


An example: soda deal
▪ Soft drinks are sold in cans and bottles. A store offers a six-pack of
12-ounce cans for the same price as a two-liter bottle. Which
should you buy? (12 fluid ounces equal approximately 0.355 liters.)
List of variables: Type of Number
Number of cans per pack Whole number
Ounces per can Whole number
Ounces per bottle Number with fraction

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 11


Why different types?
▪ We saw three different types of data:
o A whole number (no fractional part) 7 (integer or int)
o A number with a fraction part 8.88 (float)
o A sequence of characters "Bob" (string)

▪ The type is associated with the value, not the variable


o cansPerPack = 6 # int
o canVolume = 12.0 # float

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 12


Updating a Variable (assigning a value)
▪ If an existing variable is assigned a new value, that value replaces
the previous contents of the variable.
▪ For example:
o cansPerPack = 6
o cansPerPack = 8

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 13


Updating a Variable (computed)
▪ Executing the Assignment:
o cansPerPack = cansPerPack + 2
▪ Step by Step:
o Step 1: Calculate the right hand side of the assignment.
Find the value of cansPerPack, and add 2 to it.

o Step 2: Store the result in the variable named on the left side of the
assignment operator

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 14


Undefined Variables
▪ You must define (and initialize) a variable before you use it: (i.e. it
must be defined somewhere above the line of code where you first
use the variable)
o canVolume = 12 * literPerOunce
o literPerOunce = 0.0296
o Will cause a NameError: name 'literPerOunce' is not defined
▪ The correct order for the statements is:
o literPerOunce = 0.0296
o canVolume = 12 * literPerOunce

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 15


Data types
▪ The data type is associated with the value and not the variable.
Therefore:
▪ A variable can be assigned different values of different types, at
different places in a program

o taxRate = 5 # an int
Then later…
o taxRate = 5.5 # a float
And then
o taxRate = "Non-taxable" # a string

▪ If you use a variable and it has an unexpected type an error will occur in
your program

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 16


Example…
▪ Open PyCharm (or repl.it) and create a new project

▪ # Testing different types in the same variable


taxRate = 5 # int
print(taxRate)
taxrate = 5.5 # float
print(taxRate)
taxRate = "Non-taxable" # string
print(taxRate)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 17


But…
▪ taxRate = "Non-taxable" # string
print(taxRate)
print(taxRate + 5)
o Generates: TypeError: can only concatenate str (not "int") to
str

▪ print(taxRate + "??")
o Prints Non-taxable??

▪ So…
o Once you have initialized a variable with a value of a particular type you should
take great care to keep storing values of the same type in the variable

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 18


Caveats
▪ You should try the operations that are valid according to the
current value of the variable, only
o Remember which type each variable refers to

▪ When you use the “+” operator with strings the second argument
is concatenated to the end of the first, but both arguments must
be strings
o We’ll cover string operations in more detail later in this chapter

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 19


Table 1: Number Literals in Python

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 20


Naming variables
▪ Use These Simple Rules
o Variable names must start with a letter or the underscore ( _ ) character
• Continue with letters (upper or lower case), digits or the underscore
o You cannot use other symbols (? or %, ...) nor spaces
o Separate words with ‘camelCase’ notation
• Use upper case letters to signify word boundaries
o Don’t use ‘reserved’ Python words (see Appendix C, pages A6 and A7)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 21


Table 2: Variable Names in Python

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 22


Tip: Use Descriptive Variable Names
▪ Choose descriptive variable names
▪ Which variable name is more self descriptive?
o canVolume = 0.35
o cv = 0.355
▪ This is particularly important when programs are written by more
than one person.

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 23


Constants
▪ In Python a constant is a variable whose value should not be changed
after it’s assigned an initial value.
▪ It is a good practice to use all caps when naming constants
o BOTTLE_VOLUME = 2.0
▪ It is good style to use named constants to explain numerical values to be
used in calculations: Which is clearer?
o totalVolume = bottles * 2
o totalVolume = bottles * BOTTLE_VOLUME
▪ A programmer reading the first statement may not understand the
significance of the “2”
▪ Python will let you change the value of a constant
o Just because you can do it, doesn’t mean you should do it

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 24


Constants: Naming & Style
▪ It is customary to use all UPPER_CASE letters for constants to
distinguish them from variables.
o It is a nice visual way cue
▪ BOTTLE_VOLUME = 2 # Constant
▪ MAX_SIZE = 100 # Constant
▪ taxRate = 5 # Variable

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 25


Python comments
▪ Use comments at the beginning of each program, and to clarify
details of the code
▪ Comments are a courtesy to others and a way to document your
thinking
o Comments to add explanations for humans who read your code
▪ The compiler ignores comments
o Other programmers will read them
o Even yourself, tomorrow
Documentation is a love letter that you write to
your future self. Damian Conway (2005).
“Perl Best Practices”, p.153, "O'Reilly Media, Inc."

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 26


Commenting Code
##
# This program computes the volume (in liters) of a six-pack of soda
# cans and the total volume of a six-pack and a two-liter bottle
#

# Liters in a 12-ounce can


CAN_VOLUME = 0.355

# Liters in a two-liter bottle.


BOTTLE_VOLUME = 2

# Number of cans per pack.


cansPerPack = 6

# Calculate total volume in the cans.


totalVolume = cansPerPack * CAN_VOLUME
print("A six-pack of 12-ounce cans contains", totalVolume, "liters.")

# Calculate total volume in the cans and a 2-liter bottle.


totalVolume = totalVolume + BOTTLE_VOLUME
print("A six-pack and a two-liter bottle contain", totalVolume, "liters.")

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 27


Arithmetic 2.2

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 28


Basic Arithmetic Operations
▪ Python supports all basic arithmetic operations:
o Addition +
o Subtraction -
o Multiplication *
o Division /
o Exponent **
▪ Use parentheses to write expressions

b * ((1 + r / 100) ** n)

▪ Precedence is similar to Algebra:


o PEMDAS
• Parenthesis, Exponent, Multiply/Divide, Add/Subtract

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 29


Mixing numeric types
▪ If you mix integer and floating-point values in an arithmetic
expression, the result is a floating-point value.
▪ 7 + 4.0 # Yields the floating value 11.0

▪ 4 and 4.0 are different data types, for a computer

▪ Remember:
o If you mix strings with integer or floating-point values the result is an error

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 30


Floor division
▪ When you divide two integers with the / operator, you get a
floating-point value.
o For example, 7 / 4 yields 1.75
▪ We can also perform floor division or integer division using the
// operator.
o The “//” operator computes the quotient and discards the fractional part
o For example, 7 // 4 evaluates to 1
• In fact, 7 divided by 4 is 1.75 with a fractional part of 0.75, which is
discarded.
o Only for integer numbers

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 31


Calculating a remainder
▪ If you are interested in the remainder of dividing two integers, use
the “%” operator (called modulus):
o remainder = 7 % 4
▪ The value of remainder will be 3
▪ Sometimes called “modulo division”
▪ Only for integer numbers

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 32


Example
# Convert pennies to dollars and cents
pennies = 1729
dollars = pennies // 100 # Calculates the number
of dollars
cents = pennies % 100 # Calculates the number
of pennies
print("I have", dollars, "and", cents, "cents")

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 33


Integer Division and Remainder Examples

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 34


Calling functions
▪ A function is a collection of programming instructions that carry
out a particular task.
▪ The print() function can display information, but there are many
other functions available in Python
o You will learn to call the available functions, and to create your own
▪ When calling a function you must provide the correct number of
arguments (also called parameters)
o The program will generate an error message if you don’t

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 35


Calling functions that return a value
▪ Most functions return a value. That is, when the function
completes its task, it passes a value back to the point where the
function was called.
▪ For example:
o The call abs(-173) returns the value 173.
o The value returned by a function can be used in an expression or can be
stored in a variable:
• distance = abs(x)

▪ You can use a function call as an argument to the print function


o print(abs(-173))

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 36


Built-in Mathematical Functions

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 37


Python libraries (modules)
▪ A library is a collection of code (e.g., functions, constants, data
types), written and compiled by someone else, that is ready for
you to use in your program
o Always check the documentation before using
▪ The standard library is a library that is considered part of the
language and is included with any Python system
o https://docs.python.org/3/library/index.html
▪ Libraries (including the standard library) are organized in modules
o Related functions and data types are grouped into the same module.
o Functions defined in a module must be explicitly loaded into your program
before they can be used

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 38


Libraries, modules, functions
▪ Built-in functions
o Always available (such as print(), abs(), …)
▪ Standard library
o Part of every Python installation
o Organized in modules
o Each module contains many functions
o Before using the functions, you must import the module
▪ Additional libraries
o Not part of Python
o Must be downloaded/installed in your project (using the IDE or with
command line tools)
o After being installed, they can be imported and functions may be used

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 39


Built-in functions (always available)

https://docs.python.org/3/library/functions.html

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 40


Standard Library functions
▪ The sqrt() function, which computes the square root of its
argument, is in the ‘math’ module of the standard library
o https://docs.python.org/3/library/math.html

# First include this statement at the top of your


# program file.
from math import sqrt

# Then you can simply call the function as


y = sqrt(x)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 41


Some Functions from the Math Module

from math import xxxxx

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 42


Importing modules
▪ Three ways to import functions from modules:
o from math import sqrt, sin, cos
# imports listed functions
o from math import *
# imports all functions from the module
o import math
# imports the module and gives access to all functions
▪ If you use the last style you have to add the module name and a “.”
before each function call
o import math
o y = math.sqrt(x)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 43


Floating-point to integer conversion
▪ You can use the function int() and float() to convert between
integer and floating-point values:
balance = total + tax # balance: float
dollars = int(balance) # dollars: integer
▪ You lose the fractional part of the floating-point value (no rounding
occurs)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 44


Floating-point to integer conversion
Function Definition
math.floor(x) Return the floor of x, the largest integer less than or equal to x
math.ceil(x) Return the ceiling of x, the smallest integer greater than or equal to x.
math.trunc(x) Return the real value x truncated to an integer (not the same as floor, for negative
numbers!)
round(x,d) Return x rounded to d digits precision after the decimal point. If d is omitted or is
None, it returns the nearest integer to its input.
int(x) Return an integer object constructed from a number or string x. For floating point
numbers, this truncates towards zero. For strings, it converts the string to an
integer

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 45


Roundoff Errors / Rounding Errors
▪ Floating point values are not exact
o This is a limitation of binary values; not all floating-point numbers have an exact
representation
▪ Try this:
price = 4.35
quantity = 100
total = price * quantity
# Should be 100 * 4.35 = 435.00
print(total) # prints 434.99999999999994
▪ You can deal with roundoff errors by
o Rounding to the nearest integer (see Section 2.2.4)
o Displaying a fixed number of digits after the decimal separator (see Section 2.5.3)
o Defining a “tolerance” EPSILON and do only approximate comparisons (see Section
3.2, and see math.isclose())

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 46


Arithmetic Expressions

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 47


Unbalanced Parentheses
▪ Consider the expression
((a + b) * t / 2 * (1 - t)
o What is wrong with the expression?
▪ Now consider this expression.
(a + b) * t) / (2 * (1 - t)
o This expression has three “(” and three “)”, but it still is not correct
▪ At any point in an expression the count of “(“ must be greater
than or equal to the count of “)”
▪ At the end of the expression the two counts must be the same

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 48


Programming Tips
▪ Use Spaces in expressions
totalCans = fullCans + emptyCans
o Is easier to read than
totalCans=fullCans+emptyCans

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 49


Problem Solving
Exercise 2.3

DEVELOP THE ALGORITHM FIRST, THEN WRITE PYTHON CODE

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 50


Problem Solving: First by Hand
▪ A very important step for developing an algorithm is to first carry
out the computations by hand.
o If you can’t compute a solution by hand, how do you write the program?
▪ Example Problem:
o A row of black and white tiles needs to be placed along a wall. For aesthetic
reasons, the architect has specified that the first and last tile shall be black.
o Your task is to compute the number of tiles needed and the gap at each
end, given the space available and the width of each tile.

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 51


Start with example values
▪ Givens
o Total width: 100 inches
o Tile width: 5 inches
▪ Test your values
▪ Let’s see… 100/5 = 20, perfect! 20 tiles. No gap.
o But wait… BW…BW “…first and last tile shall be black.””
▪ Look more carefully at the problem….
o Start with one black, then some number of WB pairs

▪ Observation: each pair is 2x width of 1 tile


o In our example, 2 x 5 = 10 inches

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 52


Keep applying your solution
o Total width: 100 inches
o Tile width: 5 inches

▪ Calculate total width of all tiles


o One black tile: 5 in
o 9 pairs of BWs: 90 in
o Total tile width: 95 in
▪ Calculate gaps (one on each end)
o 100 – 95 = 5 in = total gap
o 5 in gap / 2 = 2.5 in, at each end

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 53


Now devise an algorithm
▪ Use your example to see how you calculated values
▪ How many pairs?
o Note: must be a whole number
o Integer part of: (total width – tile width) / ( 2 x tile width )
▪ How many tiles?
o 1 + 2 x the number of pairs
▪ Gap at each end
o (total width – number of tiles x tile width) / 2

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 54


The algorithm
▪ Calculate the number of pairs of tiles
o Number of pairs = integer part of (total width – tile width) / (2 * tile width)
▪ Calculate the number of tiles
o Number of tiles = 1 + (2 * number of pairs)
▪ Calculate the gap
o Gap at each end = (total width – number of tiles * tile width / 2)
▪ Print the number of pairs of tiles
▪ Print the total number of tiles in the row
▪ Print the gap

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 55


Strings 2.4

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 56


Strings
▪ Basic definitions:
o Text consists of characters
o Characters are letters, numbers, punctuation marks, spaces, ….
o A string is a sequence of characters
▪ In Python, string literals are specified by enclosing a sequence of
characters within a matching pair of either single or double quotes.
print("This is a string.", 'So is this.')
▪ By allowing both types of delimiters, Python makes it easy to
include an apostrophe or quotation mark within a string.
o message = 'He said "Hello"'
o Remember to use matching pairs of quotes: single with single, double with
double

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 57


String Length
▪ The number of characters in a string is called the length of the
string.
o Example, the length of "Harry" is 5
▪ You can compute the length of a string using Python’s len()
function:
length = len("World!") # length is 6
▪ A string of length 0 is called the empty string. It contains no
characters and is written as "" or ''.

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 58


String Concatenation (“+”)
▪ You can ‘add’ one String onto the end of another
firstName = "Harry"
lastName = "Morgan"
name = firstName + lastName # HarryMorgan
print("my name is:", name)
▪ You wanted a space in between the two names?
name = firstName + " " + lastName # Harry Morgan

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 59


Note
▪ Using “+” to concatenate strings is an example of a concept called
operator overloading.
▪ The “+” operator performs different functions, depending on the
types of the involved values:
o integer + integer → integer addition
o float + float, float + integer → float addition
o string + string → string concatenation
o list + list → list concatenation
o…
▪ But…
o string + integer → error

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 60


String repetition (“*”)
▪ You can also produce a string that is the result of repeating a string
multiple times
▪ Suppose you need to print a dashed line
▪ Instead of specifying a literal string with 50 dashes, you can use the
* operator to create a string that is comprised of the string "-"
repeated 50 times
dashes = "-" * 50
o results in the string
"-------------------------------------------------"
▪ The “*” operator is also overloaded

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 61


Converting Numbers to Strings
▪ Use the str() function to convert between numbers and strings.
balance = 888.88
dollars = 888
balanceAsString = str(balance)
dollarsAsString = str(dollars)
print(balanceAsString)
print(dollarsAsString)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 62


Converting Strings to Numbers
▪ To turn a string containing a number into a numerical value, we use
the int() and float() functions:
id = int("1729")
price = float("17.29")
print(id)
print(price)
▪ This conversion is important when the strings come from user
input

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 63


Conversion errors
▪ You cannot convert a character’s string into a number, it is
necessary to have a string made of digits to do so:
▪ Example:
o val = int(″20″)

o val = int(″Hola″)
ValueError: invalid literal for int() with
base 10: ‘Hola'

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 64


Strings and Characters
▪ Strings are sequences of characters
▪ Strings are immutable: they cannot be modified after their creation
o The same variable can be updated to refer to another string, however

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 65


Extracting a character from a String
▪ Each character inside a String has an index number:
index
0 1 2 3 4 5 6 7 8 9
c h a r s h e r e character

▪ The first character has index zero (0)


o The last character has index len(name)-1
▪ The [] operator returns a character at a given index inside a
String:
0 1 2 3 4
name = "Harry"
H a r r y
first = name[0]
last = name[4]
name[0] name[4]

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 66


Valid index
▪ The only valid indexes are from 0 to len(string)-1
▪ Invalid indexes will generate an error
o IndexError: string index out of range.

name = 'Bob' Bob has length 3


print(name, 'has length', len(name)) B
print(name[0]) o
print(name[1]) b
print(name[2]) Traceback (most recent call last):
print(name[3]) File "main.py", line 6, in <module>
print(name[3])
IndexError: string index out of range

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 67


Immutability
▪ Strings are immutable in python
▪ You can’t change the value of a character
o A TypeError occurs

name = 'Bob' B
Traceback (most recent call last):
print(name[0]) File "main.py", line 5, in <module>
name[0] = 'G'
name[0] = 'G' TypeError: 'str' object does not support
item assignment

▪ Workaround: we will learn how to build a new ‘updated’ string


instead of modifying the current one

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 68


String slices
▪ It is possible to extract a part of a string or slice
▪ Given a string:
oname = ʺnever odd or evenʺ
▪ If we want the string slice from character 4 (index 3→’e’) included,
to 8 (index 7 → ‘d’) not included
▪ stringSlice = name[3:7]
▪ The string slice contains characters in indexes 3, 4, 5 and 6.
oʺer oʺ

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 69


String slices - 2
▪ Examples
▪ name[ : 6] → ʺnever odd or evenʺ
o All the characters included from the first one (index 0) to the 6° one, (index
6 not included)
▪ name[6 : ] → ʺnever odd or evenʺ
o Characters from the 7° to the last one inlcluded
▪ name[ : ]
o All the characters included, it makes a copy of the string

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 70


String portions
▪ A string portion can be extracted providing start, stop and step
indexes
▪ name[3:8:2] → ʺnever odd or evenʺ
o Include all the characters from 3 to 8 using an increment of 2 of the index
steps.
▪ name[::2] → ʺnever odd or evenʺ
o Include all the characters in even indexes

▪ name[1::2] → ʺnever odd or evenʺ


o Include all the characters in odd indexes

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 71


String Operations

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 72


Characters
▪ Characters are stored as integer values
o See the ASCII subset on Unicode chart in Appendix A
o For example, the letter ‘H’ has an ASCII value of 72
▪ Python uses Unicode characters
o Unicode defines over 100,000 characters
o Unicode was designed to be able to encode text in essentially all written
languages
o https://home.unicode.org/ and http://www.unicode.org/charts/

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 73


ASCII codes

For Unicode characters see: https://unicode-table.com/

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 74


Character conversions

ASCII/Unicode
Character
value (integer)
'x'
120

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 75


Functions vs Methods
▪ Python is an object-oriented language, and all values are objects.
o Object-oriented programming is out of the scope of the course, we will only
see some very practical aspect
▪ Every object may have methods, i.e., functions that can be called
on that specific object, using a syntax object.method()
▪ Example: all strings have an upper() method that returns a new
string, converted to upper case
name = "John Smith"
# Sets uppercaseName to "JOHN SMITH"
uppercaseName = name.upper()

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 76


Functions vs Methods – what to Remember
FUNCTION METHOD

▪ Functions are general and can accept ▪ Methods are specific to a type of
arguments of different types object
o All strings have a group of methods
▪ Functions are called directly, with a list
o All integers have a group of methods
of parameters
o…
o exmp. func(param), print(a)

▪ Functions may return a result, that may ▪ Methods are called with the dot-syntax
be stored in a variable o object.method()
o result = func(param) ▪ Methods may return a result, that may
be stored in a variable
o result = obj.method()

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 77


Some Useful String Methods

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 78


String Escape Sequences
▪ How would you print a double quote?
o Preface the " with a “\” inside the double quoted String
print("He said \"Hello\"")

▪ OK, then how do you print a backslash?


o Preface the \ with another \
print("C:\\Temp\\Secret.txt")

▪ Special characters inside Strings


*
o Output a newline with a ‘\n’
**
print("*\n**\n***")
***

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 79


Summary

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 80


Summary: variables
▪ A variable is a storage location with a name.
▪ When defining a variable, you must specify an initial value.
▪ By convention, variable names should start with a lower case letter.
▪ An assignment statement stores a new value in a variable,
replacing the previously stored value.

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 81


Summary: operators
▪ The assignment operator = does not denote mathematical
equality.
▪ Variables whose initial value should not change are typically
capitalized by convention.
▪ The / operator performs a division yielding a value that may have a
fractional value.
▪ The // operator performs an integer division, the remainder is
discarded.
▪ The % operator computes the remainder of a floor division.

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 82


Summary: python overview
▪ The Python library declares many mathematical functions, such as
sqrt() and abs()
▪ You can convert between integers, floats and strings using the
respective functions: int(), float(), str()
▪ Python libraries are grouped into modules. Use the import
statement to use methods from a module.

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 83


Summary: Strings
▪ Strings are sequences of characters.
▪ The len() function yields the number of characters in a String.
▪ Use the + operator to concatenate Strings; that is, to put them
together to yield a longer String.
▪ In order to perform a concatenation, the + operator requires both
arguments to be strings. Numbers must be converted to strings
using the str() function.
▪ String index numbers are counted starting with 0.

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 84


Summary: Strings
▪ Use the [ ] operator to extract the elements (single characters) of
a String
▪ Use the operator [a:b] to extract slices of the string or [a:b:c] to
use a different index step during the extraction.

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 85

You might also like