KEMBAR78
Data Types | PDF | Data Type | Boolean Data Type
0% found this document useful (0 votes)
33 views60 pages

Data Types

Uploaded by

2508525
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)
33 views60 pages

Data Types

Uploaded by

2508525
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/ 60

MINN2020A: COMPUTER PROGRAMMING FOR

MINING

Data types
“Education is the passport to the future, for
tomorrow belongs to those who prepare for it
today.” —Malcolm X
Ms Milka Madahana
x77572
Milka.Madahana@wits.ac.za
School of Mining Engineering
Data Types
Data Types
• In programming, data type is an important concept.
• Variables can store data of different types, and different
types can do different things.
• Python has the following data types built-in by default,
in these categories:

2
Data Types

• Text Type: str


• Numeric Types: int, float, complex
• Sequence Types: list, tuple, range
• Mapping Type: dict

3
Data types

Set Types: set, frozenset


Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType

4
Data type
• You can get the data type of any object by using the
type() function:
Print the data type of the variable x:

5
Setting the Data Type

Setting the Data Type


• In Python, the data type is set when you assign a value
to a variable(s)

6
Data types
x = "Hello World" str
x = 20 int
x = 20.5 float

x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") Tuple
x = range(6) Range
x = {"name" : "John", "age" : 36} Dict

x = {"apple", "banana", "cherry"} Set


x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview

x = None NoneType

7
Setting the Specific Data Type
• If you want to specify the data type, you can use the
following constructor functions

8
Numbers
Python Numbers
There are three numeric types in Python:
• int
• float
• Complex
Variables of numeric types are created when you assign a
value to them:

9
Data types
• To verify the type of any object in Python, use the type()
function:

Int
Int, or integer, is a whole number, positive or negative,
without decimals, of unlimited length.

10
Floating Numbers
Float, or "floating point number" is a number, positive or negative, containing
one or more decimals

11
Float can also be scientific numbers with an "e" to indicate the power of 10.

12
Complex

Complex numbers are written with a "j" as the imaginary part:

13
Type conversion
Type Conversion
• You can convert from one type to another with the int(),
float(), and complex() methods:

14
Random Numbers
Random Numbers
• Python does not have a random() function to make a
random number, but Python has a built-in module called
random that can be used to make random numbers:
Example
• Import the random module, and display a random
number between 1 and 9:

15
Casting- Specify a Variable Type
Specify a Variable Type

There may be times when you want to specify a type on to a variable. This
can be done with casting. Python is an object-orientated language, and as
such it uses classes to define data types, including its primitive types.

Casting in python is therefore done using constructor functions:

• int() - constructs an integer number from an integer literal, a float literal


(by removing all decimals), or a string literal (providing the string
represents a whole number)
• float() - constructs a float number from an integer literal, a float literal or a
string literal (providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including
strings, integer literals and float literals

16
Integers, floats and strings

17
Python Strings
• Strings in python are surrounded by either single quotation
marks, or double quotation marks.
• 'hello' is the same as "hello".
• You can display a string literal with the print() function

18
Assign String to a Variable

Assign String to a Variable


• Assigning a string to a variable is done with the variable
name followed by an equal sign and the string:

19
Multiline Strings

Multiline Strings
• You can assign a multiline string to a variable by using
three quotes:
• You can use three double quotes:

20
Strings are arrays
Strings are Arrays
• Like many other popular programming languages,
strings in Python are arrays of bytes representing
unicode characters.
• However, Python does not have a character data type, a
single character is simply a string with a length of 1.
• Square brackets can be used to access elements of the
string.

21
• Get the character at position 1 (remember that the first
character has the position 0):

22
Looping Through a string

Looping Through a String


• Since strings are arrays, we can loop through the
characters in a string, with a for loop.
• Loop through the letters in the word "Engineering":

23
String Length

String Length
• To get the length of a string, use the len() function.
• The len() function returns the length of a string:

24
Check String

Check String
• To check if a certain phrase or character is present in a
string, we can use the keyword in.
• Check if "free" is present in the following text:

25
• Use it in an if statement:
• Print only if "free" is present:

26
Check if NOT
• To check if a certain phrase or character is NOT present
in a string, we can use the keyword not in

27
• Use it in an if statement:

28
Slicing

Slicing
• You can return a range of characters by using the slice
syntax.
• Specify the start index and the end index, separated by a
colon, to return a part of the string
• Get the characters from position 2 to position 5 (not
included):

29
Slice from Start

Slice From the Start


• By leaving out the start index, the range will start at the
first character:
• Get the characters from the start to position 5 (not
included):

30
Negative Indexing
Slice To the End
• By leaving out the end index, the range will go to the
end:
Get the characters from position 2, and all the way to the
end:

31
Negative Indexing
• Use negative indexes to start the slice from the end of the
string:
• Get the characters:
• From: "o" in "World!" (position -5)
• To, but not included: "d" in "World!" (position -2):

32
Modify Strings

• Python has a set of built-in methods that you can use on


strings.
Upper Case
The upper() method returns the string in upper case:

33
Modify Strings

Lower Case
The lower() method returns the string in lower case:

34
Modify Strings
Remove Whitespace

Whitespace is the space before and/or after the actual text, and very often
you want to remove this space.

The strip() method removes any whitespace from the beginning or the end:

35
Modify Strings

Replace String
• The replace() method replaces a string with another
string:

36
Modify Strings

Split String
• The split() method returns a list where the text between
the specified separator becomes the list items.
• The split() method splits the string into substrings if it
finds instances of the separator:

37
String Concatenation

String Concatenation
• To concatenate, or combine, two strings you can use the
+ operator.
• Merge variable a with variable b into variable c:

38
String Concatenation

To add a space between them, add a " ":

39
Format Strings

String Format
• As we learned in the Python Variables chapter, we cannot
combine strings and numbers like this:

40
Format Strings

• But we can combine strings and numbers by using the format()


method!
• The format() method takes the passed arguments, formats them, and
places them in the string where the placeholders {} are:
• Use the format() method to insert numbers into strings:

41
Format strings

• The format() method takes unlimited number of arguments, and are


placed into the respective placeholders:

42
Format Strings

• You can use index numbers {0} to be sure the arguments


are placed in the correct placeholders:

43
Escape characters

Escape Character
• To insert characters that are illegal in a string, use an
escape character.
• An escape character is a backslash \ followed by the
character you want to insert.
• An example of an illegal character is a double quote
inside a string that is surrounded by double quotes:

44
Escape Strings

• You will get an error if you use double quotes inside a


string that is surrounded by double quotes:
Example

• To fix this problem, use the escape character \":

45
Escape Strings

• The escape character allows you to use double quotes


when you normally would not be allowed:

• Other escape characters used in Python are given in the


slide to follow

46
Escape characters

Code Result

\' Single Quote

\\ Backslash

\n New Line

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed

\ooo Octal value

\xhh Hex value

47
String Methods

String Methods
• Python has a set of built-in methods that you can use on
strings.
• Note: All string methods return new values. They do not
change the original string.
• Note:
A printed list of string methods will be issued out in class

48
Data type: Booleans

• Booleans represent one of two values: True or False.


• Boolean Values
• In programming you often need to know if an expression is True or
False.
• You can evaluate any expression in Python, and get one of two
answers, True or False.
• When you compare two values, the expression is evaluated and
Python returns the Boolean answer:

49
Boolean

• When you run a condition in an if statement, Python


returns True or False:
• Print a message based on whether the condition is True
or False:

50
Boolean

Evaluate Values and Variables


• The bool() function allows you to evaluate any value,
and give you True or False in return,
• Evaluate a string and a number:

51
Boolean

• Evaluate two variables:

52
Boolean

Most Values are True


• Almost any value is evaluated to True if it has some sort
of content.
• Any string is True, except empty strings.
• Any number is True, except 0.
• Any list, tuple, set, and dictionary are True, except
empty ones.

53
Boolean

The following will return True:

• Some Values are False


• In fact, there are not many values that evaluate to False, except
empty values, such as (), [], {}, "", the number 0, and the value None.
And of course the value False evaluates to False.

54
Boolean

The following will return False:

• One more value, or object in this case, evaluates to False,


and that is if you have an object that is made from a class
with a __len__ function that returns 0 or False:
55
Boolean

Functions can Return a Boolean

You can create functions that returns a Boolean Value:

56
Boolean

You can execute code based on the Boolean answer of a function:

Print "YES!" if the function returns True, otherwise print "NO!":

57
Boolean

Python also has many built-in functions that return a boolean value, like
the isinstance() function, which can be used to determine if an object is of
a certain data type:

Check if an object is an integer or not:

58
• Exercise
Go through the exercise uploaded on Ulwazi

59
MINN2020A: COMPUTER PROGRAMMING FOR
MINING

THE END

Ms Milka Madahana
x77572
Milka.Madahana@wits.ac.za
School of Mining Engineering

You might also like