0% found this document useful (0 votes)
12 views13 pages

Python Data Types Overview

This document covers the basics of data types in Python, including Booleans, Integers, and Strings. It explains how to create, manipulate, and convert these data types, as well as the operations that can be performed on them. By the end of the lecture, students should be able to identify and apply various data types in Python programming.

Uploaded by

amnouyporn-pra67
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)
12 views13 pages

Python Data Types Overview

This document covers the basics of data types in Python, including Booleans, Integers, and Strings. It explains how to create, manipulate, and convert these data types, as well as the operations that can be performed on them. By the end of the lecture, students should be able to identify and apply various data types in Python programming.

Uploaded by

amnouyporn-pra67
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

02 - Working with data types

Working with data types


Learning Outcomes
By the end of this lecture, students will be able to:
Explain basics understanding of data types.
Identify type concept in Python.
Apply variety of data types in Python.

Numbers
Python’s simplest built-in data types:
Booleans (which have the value True or False )
Integers (whole numbers such as 42 and 100000000 )
Floats (numbers with decimal points such as 3.14159, or sometimes exponents
like 1.0e8, which means one times ten to the eighth power, or 100000000.0 )

Booleans
In Python, the only values for the boolean data type are True and False.
The special Python function bool() can convert any Python data type to a boolean.
Nonzero numbers are considered True:

1 bool(True)
2 bool(1)
3 bool(45)
4 bool(-45)

True
True
True
True

And zero-valued ones are considered False:

1 bool(False)
2 bool(0)
3 bool(0.0)

False
False
False

Integers
Integers are whole numbers—no fractions, no decimal points, nothing fancy.
Any sequence of digits in Python represents a literal integer: Try this?

1 5
2 0
3 05

You can start an integer with 0b, 0o, or 0x. See “Bases”.
Try more:

1 123
2 +123
3 -123
4 1,000,000
5 1_000_000
6 1_2_3

Integer Operations
Operator Description Example Result
+ Addition 5+8 13
- Subtraction 90 - 10 80
* Multiplication 4*7 28
/ Floating-point division 7/2 3.5
// Integer (truncating) division 7 // 2 3
% Modulus (remainder) 7%3 1
** Exponentiation 3 ** 4 81
Integers and Variables
All of the preceding examples used literal integers.
You can mix literal integers and variables that have been assigned integer values:

1 a = 95
2 print(a)
3 print(a - 3)

95
92

If you wanted to change a, you would do this:

1 a = 95
2 a = a - 3
3 print(a)

92

Again, this would not be a legal math equation, but it’s how you reassign a value to a
variable in Python.
In Python, the expression on the right side of the = is calculated first, and then assigned
to the variable on the left side.
If it helps, think of it this way:
Subtract 3 from a
Assign the result of that subtraction to a temporary variable
Assign the value of the temporary variable to a:

1 a = 95
2 temp = a - 3
3 a = temp

You can combine the arithmetic operators with assignment by putting the operator
before the =.
Here, a -= 3 is like saying a = a - 3:

1 a = 95
2 a -= 3
3 print(a)

92

You can apply to + * / // and %


Precedence
What would you get if you typed the following?

1 2 + 3 * 4

14

In Python, as in most languages, multiplication has higher precedence than addition.


It’s much easier to just add parentheses to group your code as you intend the
calculation to be carried out:

1 2 + (3 * 4)

14

Base
Integers are assumed to be decimal (base 10) unless you use a prefix to specify
another base.
You might never need to use these other bases, but you’ll probably see them in Python
code somewhere, sometime.
In Python, you can express literal integers in three bases besides decimal with these
integer prefixes:
0b or 0B for binary (base 2).
0o or 0O for octal (base 8).
0x or 0X for hex (base 16).
Try this:

1 print(0b10)
2 print(0o10)
3 print(0x10)

2
8
16

You can go the other direction, converting an integer to a string with any of these
bases:

1 value = 65
2 print(bin(value))
3 print(oct(value))
4 print(hex(value))

'0b1000001'
'0o101'
'0x41'

The chr() function converts an integer to its single-character string equivalent:


And ord() goes the other way:

1 print(chr(65))
2 print(ord('A'))

'A'
65

Type Conversions
To change other Python data types to an integer, use the int() function.
The int() function takes one input argument and returns one value, the integer-ized
equivalent of the input argument.
This will keep the whole number and discard any fractional part.
Python’s simplest data type is the boolean, which has only the values True and False.
When converted to integers, they represent the values 1 and 0:

1 print(int(True))
2 print(int(False))

1
0

Turning this around, the bool() function returns the boolean equivalent of an integer:

1 print(bool(1))
2 print(bool(0))

True
False

Converting a floating-point number to an integer just lops off everything after the
decimal point:
1 print(int(98.6))
2 print(int(1.0e4))

98
10000

If the string represents a nondecimal integer, you can include the base:

1 int('10', 2) # binary
2 int('10', 8) # octal
3 int('10', 16) # hexadecimal

2
8
16

Try this:

1 int('99 bottles of beer on the wall')

How Big Is an int?


In Python 2, the size of an int could be limited to 32 or 64 bits, depending on your CPU;
32 bits can store store any integer from –2,147,483,648 to 2,147,483,647.
A long had 64 bits, allowing values from –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
In Python 3, the long type is long gone, and an int can be any size—even greater than
64 bits.
You can play with big numbers like a googol (one followed by a hundred zeroes, named
in 1920 by a nine-year-old boy):

1 googol = 10**100
2 print(googol)
3 print(googol * googol)

1000000000000000000000000000000000000000000000000000000000000000000000000
00000 00000000000000000000000
1000000000000000000000000000000000000000000000000000000000000000000000000
00000
0000000000000000000000000000000000000000000000000000000000000000000000000
00000 000000000000000000000000000000000000000000000
In many languages, trying this would cause something called integer overflow, where
the number would need more space than the computer allowed for it, with various bad
effects.
Python handles googoly integers with no problem.

Text Strings
Computer books often give the impression that programming is all about math.
Actually, most programmers work with strings of text more often than numbers.
Logical (and creative!) thinking is often more important than math skills.
Strings are our first example of a Python sequence.
In this case, they’re a sequence of characters. But what’s a character?
It’s the smallest unit in a writing system, and includes letters, digits, symbols,
punctuation, and even white space or directives like linefeeds.

Create with Quotes


You make a Python string by enclosing characters in matching single or double
quotes:

1 print('Snap')
2 print("Crackle")

'Snap'
'Crackle'

The interactive interpreter echoes strings with a single quote, but all are treated exactly
the same by Python.

==Why have two kinds of quote characters? ==


The main purpose is to create strings containing quote characters.
You can have single quotes inside double-quoted strings, or double quotes inside
single-quoted strings:

1 print("'Nay!' said the naysayer. 'Neigh?' said the horse.")


2 print('The rare double quote in captivity: ".')
3 print('A "two by four" is actually 1 1/2" × 3 1/2".')
4 print("'There's the man that shot my paw!' cried the limping hound.")
"'Nay!' said the naysayer. 'Neigh?' said the horse."
'The rare double quote in captivity: ".'
'A "two by four" is actually 1 1/2" × 3 1/2".'
"'There's the man that shot my paw!' cried the limping hound."

If you have multiple lines within triple quotes, the line ending characters will be
preserved in the string.
If you have leading or trailing spaces, they’ll also be kept:

1 poem2 = '''I do not like thee, Doctor Fell.


2 The reason why, I cannot tell.
3 But this I know, and know full well:
4 I do not like thee, Doctor Fell.
5 '''
6 print(poem2)

I do not like thee, Doctor Fell.


The reason why, I cannot tell.
But this I know, and know full well:
I do not like thee, Doctor Fell.

By the way, there’s a difference between the output of print() and the automatic echoing
done by the interactive interpreter:

1 poem2

'I do not like thee, Doctor Fell.\n The reason why, I cannot tell.\n But this I know, and know
full well:\n I do not like thee, Doctor Fell.\n'

Create with str()


You can make a string from another data type by using the str() function:

1 print(str(98.6))
2 print(str(1.0e4))
3 print(str(True))

'98.6'
'10000.0'
'True'

Python uses the str() function internally when you call print() with objects that are not
strings and when doing string formatting.
Escape with \
Python lets you escape the meaning of some characters within strings to achieve
effects that would otherwise be difficult to express.
By preceding a character with a backslash (), you give it a special meaning.
The most common escape sequence is \n, which means to begin a new line.
With this you can create multiline strings from a one-line string:

1 palindrome = 'A man,\nA plan,\nA canal:\nPanama.'


2 print(palindrome)

A man,
A plan,
A canal:
Panama.

Combine by Using +
You can combine literal strings or string variables in Python by using the + operator:

1 print('Release the kraken! ' + 'No, wait!')

'Release the kraken! No, wait!'

Python does not add spaces for you when concatenating strings, so in some earlier
examples, we needed to include spaces explicitly.
Python does add a space between each argument to a print() statement and a newline
at the end.

1 a = 'Duck.'
2 b = a
3 c = 'Grey Duck!'
4 print(a + b + c)
5 print(a, b, c)

'[Link] Duck!'
Duck. Duck. Grey Duck!

Duplicate with *
You use the * operator to duplicate a string.
Try typing these lines into your interactive interpreter and see what they print:

1 start = 'Na ' * 4 + '\n'


2 middle = 'Hey ' * 3 + '\n'
3 end = 'Goodbye.'
4 print(start + start + middle + end)

Notice that the * has higher precedence than +, so the string is duplicated before the
line feed is tacked on.

Get a Character with []


To get a single character from a string, specify its offset inside square brackets after the
string’s name.
The first (leftmost) offset is 0, the next is 1, and so on.
The last (rightmost) offset can be specified with –1, so you don’t have to count; going to
the left are –2, –3, and so on:

1 letters = 'abcdefghijklmnopqrstuvwxyz'
2 print(letters[0])
3 print(letters[25])
4 print(letters[len(letters) - 1])

'a'
'z'
'z'

Try this:

1 print(letters[100])

Because strings are immutable, you can’t insert a character directly into one or change
the character at a specific index.
Let’s try to change 'Henny' to 'Penny' and see what happens:

1 name = 'Henny'
2 name[0] = 'P'

Instead you need to use some combination of string functions such as replace() or a
slice (which we look at in a moment):
1 name = 'Henny'
2 print([Link]('H', 'P'))
3 print('P' + name[1:])

'Penny'
'Penny'

Get a Substring with a Slice


You can extract a substring (a part of a string) from a string by using a slice.
You define a slice by using square brackets, a start offset, an end offset, and an
optional step count between them.
You can omit some of these. The slice will include characters from offset start to one
before end:
[ : ] extracts the entire sequence from start to end.
[ start : ] specifies from the start offset to the end.
[ : end ] specifies from the beginning to the end offset minus 1.
[ start : end ] indicates from the start offset to the end offset minus 1.
[ start : end : step ] extracts from the start offset to the end offset minus 1,
skipping characters by step.
Try and observe this:

1 letters = 'abcdefghijklmnopqrstuvwxyz'
2 print(letters[:]) # the entire string
3 print(letters[20:]) # from offset 20 to the end
4 print(letters[10:]) # from offset 10 to the end
5 print(letters[12:15]) # offset 12 through not include the end offset in
the slice
6 print(letters[-3:]) # three last characters
7 print(letters[18:-3]) # offset 18 to the fourth before the end
8 print(letters[-6:-2]) # extract from 6 before the end to 3 before the end
9 print(letters[::7]) # from the start to the end, in steps of 7 characters
10 print(letters[4:20:3]) # from offset 4 to 19, by 3
11 print(letters[19::4]) # from offset 19 to the end, by 4
12 print(letters[:21:5]) # from the start to offset 20 by 5
13 print(letters[-1::-1]) # step backward. this starts at the end and ends at
the start, skipping nothing
14 print(letters[::-1]) # same as above

Split with split()


Unlike len(), some functions are specific to strings.
To use a string function, type the name of the string, a dot, the name of the function,
and any arguments that the function needs: [Link](arguments).
You can use the built-in string split() function to break a string into a list of smaller
strings based on some separator.
A list is a sequence of values, separated by commas and surrounded by square
brackets:

1 tasks = 'get gloves,get mask,give cat vitamins,call ambulance'


2 [Link](',')

['get gloves', 'get mask', 'give cat vitamins', 'call ambulance']

In the preceding example, the string was called tasks and the string function was called
split(), with the single separator argument ','.
If you don’t specify a separator, split() uses any sequence of white space characters—
newlines, spaces, and tabs:

1 [Link]()

['get', 'gloves,get', 'mask,give', 'cat', 'vitamins,call', 'ambulance']

More with [Link]()


Combine by Using join()
Substitute by Using replace()
Strip with strip()
Search and Select
Case
Alignment
Formatting

String Formatting
Python has three ways of formatting strings:
old style (supported in Python 2 and 3)
new style (Python 2.6 and up)
f-strings (Python 3.6 and up)
Newest Style: f-strings
f-strings appeared in Python 3.6, and are now the recommended way of formatting
strings.
To make an f-string:
Type the letter f or F directly before the initial quote.
Include variable names or expressions within curly brackets ({}) to get their
values into the string.

1 thing = 'wereduck'
2 place = 'werepond'
3 print(f'The {thing} is in the {place}')
4 print(f'The {[Link]()} is in the {[Link](20)}')

'The wereduck is in the werepond'


'The Wereduck is in the werepond'

References
Lubanovic, B. (2019). Introducing Python: Modern Computing in Simple Packages.
O’Reilly Media.

You might also like