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

Lecture 2 Data_Types - Part A

The lecture covers fundamental programming concepts related to data types, including integers, floats, strings, and booleans, as well as the differences between weak and strong typing. It emphasizes the importance of understanding type conversion and coercion, static vs. dynamic typing, and how different programming languages handle these concepts. The session also highlights the necessity for programmers to be aware of data types to avoid bugs and security vulnerabilities.

Uploaded by

ashwin68732007
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)
5 views

Lecture 2 Data_Types - Part A

The lecture covers fundamental programming concepts related to data types, including integers, floats, strings, and booleans, as well as the differences between weak and strong typing. It emphasizes the importance of understanding type conversion and coercion, static vs. dynamic typing, and how different programming languages handle these concepts. The session also highlights the necessity for programmers to be aware of data types to avoid bugs and security vulnerabilities.

Uploaded by

ashwin68732007
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/ 17

CSP1150/CSP5110:

Programming Principles
Lecture 2: Data Types and Selection
This Lecture

• Data types
– Common data types: integer, float, string and boolean
– Weak/Strong typing and type conversion
– Implicit and explicit conversion
– Static and dynamic typing
– Numeric, string and boolean conversions
Textbook

• Starting Out with Python, 3rd Edition


– Tony Gaddis

• Reading the chapter(s) is required


– Read the indicated chapter(s) before class

• This week covers the following textbook chapter(s):


– Chapter 3 – Decision Structures and Boolean Logic

– Note: You may also wish to revise parts of Chapter 2


regarding data types
Data Types
Data Types

• Last week we introduced the concept of variables


– Assigning a name to data stored in memory for later use

• We also mentioned data types – the “categories” of data


– Integers, floating point numbers (floats), strings…
– The difference can be subtle; 3.14 is a float, '3.14' is a string
– All data (and hence every variable) has a data type

• The data type essentially tells the language/computer how


to interpret the values that are stored in memory
– It determines what can and cannot be done with the data,
e.g. Arithmetic works on integers and floats, but not strings
– Functions often require parameters of a certain data type, e.g.
round() needs a float and an integer, e.g. round(2.327, 2)
Data Types

• The most common data types are:


Type Description Examples
integer Whole numbers 2, -500, 4294967296
float Numbers with a fractional part 3.14159, -0.3, 25.0
string A sequence of characters 'Hello, World!', '25', ' '
boolean A true or false value True, False

• Some languages divide numeric data types further


– Data types for very large numbers, e.g. “long” in Java, or
numbers with large fractional parts, e.g. “double” in Java

• Some languages, such as C, do not support strings


– Such languages typically have a “character” or “char” data
type, representing a single character. An “array” of multiple
characters can be created when a string is needed
“Weak” and “Strong” Typing

• Different languages take different approaches to whether


data types can be mixed and converted automatically

• “Weakly typed” languages focus on being convenient


– Generally achieved by making it easy to mix different data
types together and convert between them automatically
• The programming language tries to work things out for you

• “Strongly typed” languages focus on being safe


– Generally achieved by limiting the ability to mix different data
types together – conversions must be done explicitly
• The programmer must consider and convert types manually

• Languages allow and disallow things based on their design,


often ending up somewhere between weak and strong
Data Type Conversion and Coercion

• Some values can be converted between different data types


– e.g. 100 (int), 100.0 (float) and '100' or '100.0' (strings)

• All languages provide ways to convert between data types


– e.g. The int(), float() and str() functions in Python
– Some languages use “(typename) value”, e.g. (int) 3.14
– Conversion will fail (or give unexpected results) if it doesn’t
make sense, e.g. trying to convert the string of 'cat' to an int
– Some conversions may involve a loss of data, e.g. 3.14 to int

• Many languages do implicit (automatic) conversion between


compatible data types as needed; This is known as coercion
– Ints are commonly coerced to floats, e.g. 5 + 2.5 = 7.5
– Languages like PHP can coerce strings, e.g. '1' + 2 + 3.4 = 6.4
Static and Dynamic Typing

• “Static typing” is when a language requires you to declare


(and adhere to) the data type of variables, e.g. C and Java
– Assigning a different type will result in an error (or coercion)
– Helps program optimisation and to prevent type-related bugs

• “Dynamic typing” is when a language does not require you


to specify the data type of variables, e.g. Python and PHP
– The variable’s data type is determined by the data assigned
– Convenient, particularly in languages which coerce data types

String value; Java value = 1 # int Python


value = 1; // int into string 1
Error: Incompatible types
value = 'Potato' # string
C 'Potato'
int value;
value = 3.14; // float into int value = -2.74 # float
3 -2.74
Type Conversion Example – Numbers

• What is happening in these examples?


int value1 = 15; Java value1 = 15 Python
int value2 = 20; value2 = 20

float result = value1 / value2; result = value1 / value2

System.out.println(result); print(result)
0.0 0.75

– In Java (and some other “strongly typed” languages),


dividing an integer by another integer results in an integer
• The result was truncated to 0, then stored as a float of 0.0
• No rounding was performed; It simply kept the int portion only

– In Python (and other “weakly typed” languages), the result


of dividing two integers is automatically coerced to a float
Type Conversion Example – Numbers

• In this version, we explicitly convert value1 to a float


int value1 = 15; Java
int value2 = 20;

float result = (float) value1 / value2; // convert value1 to float

System.out.println(result);
0.75

– We use (float) to convert value1, an int, to a float – 15.0


• Java will coerce value2 to match, and give the result as a float

– In Java, the result of any arithmetic is “widened” to the more


encompassing data type; int < long < float < double… e.g.
• int / int = int
• float / int = float
• int / float = float
• float / float = float
Type Conversion Example – String Concatenation

• What is happening in these examples?


total = 79.4 Python

output = 'The total is ' + total


TypeError: Can't convert 'float' object to str implicitly

output = total + ' is the total'


TypeError: unsupported operand type(s) for +: 'float' and 'str'

– Both of them are trying to combine a string and a float


• In the first one, the error message says that the float cannot be
implicitly converted to a string (in order to attach it to the end)
• In the second one, the error message says that you cannot add a
float and a string together – that’s not how arithmetic works!

– The goal is the same in both – concatenating them together


into a single string, e.g. 'The total is 79.4'
• The solution to both is to convert total to a string: str(total)
Type Conversion Example – String Concatenation

• In this version, we explicitly convert total to a string


total = 79.4 Python

output = 'The total is ' + str(total)


'The total is 79.4'

output = str(total) + ' is the total'


'79.4 is the total'

– We use the str() function to convert total to a string


• Now that there are strings on both sides of the “+”, Python can
determine that you want to concatenate them and do so

– This is another area that different languages handle differently


• We’ll look at some examples on the next slide!
Type Conversion Example – String Concatenation
var num = 79.4; JavaScript $total = 79.4; PHP
alert(num + ' is the total') echo 'The total is ' . $total;
'79.4 is the total' 'The total is 79.4'

var stringNum = '25'; echo "$total is the total";


alert(num + stringNum) '79.4 is the total'
'79.425'

– JavaScript always coerces – PHP avoids ambiguity by


both values to strings and using “.” for concatenation
concatenate them – It can also detect variables
– Even if one of the strings inside strings due to the “$”
contains a number… at start of variable names

total = 79.4 Python


print(total, 'is the total. The total is', total)
'79.4 is the total. The total is 79.4'

– As covered last week, Python’s print() function offers yet


another way of combining strings and numbers…
Type Conversion Example – Boolean Values

• True and False are the only two boolean values, but values
of other data types can be converted to boolean values
– The bool() function converts a value to a boolean value
bool(5) # positive number Python bool(0) # int of 0 Python
True False
bool(-245.271) # negative number bool(0.0) # float of 0.0
True False
bool('False') # string of False bool('') # empty string
True False
bool('0') # string of 0 bool([]) # an empty "list"
True False

• The general rules that most languages follow are:


– Values equivalent to 0, or empty/blank values are False
– All other values are True
• As always, there are subtle differences between languages…
e.g. '0' (zero in a string) is True in Python, but False in PHP
Data Types / Type Conversion Summary

• While there are general concepts such as “weak” and


“strong” typing, our examples have demonstrated that…
– Almost every language handles things slightly differently!

– Regardless of what a language allows and supports,


a good programmer should always consider data types
• Know what type your data is, and how it can be used
• Learn how your language behaves when mixing/coercing types
• Failing to do so can result in bugs and security vulnerabilities

– Always test your code thoroughly to ensure it is working


• Particularly in weakly typed languages or ones you’re new to
• You won’t always receive an error message to let you know!
Conclusion

• It is important to be aware of data types, even in languages


which make it convenient to mix them implicitly
– Know how your language coerces things, what it allows and
doesn’t allow, how to convert things explicitly, etc…

– End of Part A

You might also like