SlideShare a Scribd company logo
Programming Fundamentals
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
• Selection
– If-then, if-then-else and else-if statements
– Boolean expressions
– Comparison operators and logical operators
2
Textbook
• Starting Out with Python, 4th Edition (Global)
– 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
3
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 briefly 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) in a program 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 values of a certain data type,
e.g. round() needs a float and an integer: round(2.327, 2)
5
Data Types
• The most common data types are:
• 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 used to represent a string
Type Description Examples
integer (int) Whole numbers 2, -500, 4294967296
float (float) Numbers with a fractional part 3.14159, -0.3, 25.0
string (str) A sequence of characters 'Hello, World!', '25', ' '
boolean (bool) A true or false value True, False
6
“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 easier to mix different data types together and
converting between them automatically wherever appropriate
• 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 by the programmer
• 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
7
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 a string of 'cat' to an int
– Some conversions may involve a loss of data, e.g. converting 3.14 to an int
• Many languages do implicit (automatic) conversion between compatible data
types as needed, where possible; This is known as coercion
– Integers are commonly coerced to floats, e.g. 5 + 2.5 would become 5.0 + 2.5
– Languages like PHP can coerce numeric strings, e.g. 1 + '2' + 3.4 = 6.4
8
• “Static typing” is when a language requires you to declare (and adhere to) the
data type of every variable you create. C and Java are statically typed
– Trying to assign a value of a different type will result in an error (or coercion)
– Helps program optimisation and to prevent type-related bugs
• “Dynamic typing” is when the data type of a variable is determined by the value
it currently refers to, which can change. Python and PHP are dynamically typed
– You do not “declare” a data type for the variable, you just assign a value to it
– Convenient, particularly in languages which coerce data types automatically
Static and Dynamic Typing
String value; // declare a string
value = 1; // assign int to string
Error: Incompatible types
Java value = 1 # int
1
value = 'Potato' # string
'Potato'
value = -2.74 # float
-2.74
Python
int value; // declare an int
value = 3.14; // assign float to int
3
C
9
total
HELLO, my name is…
Type Conversion Example – Numbers
• What is happening in these examples?
– 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 integer portion only
– In Python (and other “weakly typed” languages), the result of dividing two integers is
automatically coerced to a float
10
int value1 = 15;
int value2 = 20;
float result = value1 / value2;
System.out.println(result);
0.0
Java value1 = 15
value2 = 20
result = value1 / value2
print(result)
0.75
Python
Type Conversion Example – Numbers
• In this version, we explicitly convert value_one to a float
– We use (float) to convert value_one, an integer, to a float – 15.0
• Java will coerce value_two 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 / float = float
11
int value_one = 15;
int value_two = 20;
float result = (float) value_one / value_two; // convert value1 to float
System.out.println(result);
0.75
Java
• float / int = float
• int / float = float
Type Conversion Example – String Concatenation
• What is happening in these examples?
– Both of them are trying to combine a string and a float
• In the first one, the error message says that concatenation can only be performed
between strings, not between a string and a float
• 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,
i.e. 'The total is 79.4' or '79.4 is the total'
• The solution to both is to convert total to a string: str(total)
12
total = 79.4
output = 'The total is ' + total
TypeError: can only concatenate str (not "float") to str
output = total + ' is the total'
TypeError: unsupported operand type(s) for +: 'float' and 'str'
Python
Type Conversion Example – String Concatenation
• In this version, we explicitly convert total to a string
– 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 without any problems
• Reminder: The total variable still refers to a float of 79.4 – the str() function simply
produces a string version of the value – it does not change the variable itself
– Concatenating numbers and strings is an area that languages handle differently
• We’ll look at some examples on the next slide!
13
total = 79.4
output = 'The total is ' + str(total)
'The total is 79.4'
output = str(total) + ' is the total'
'79.4 is the total'
Python
– PHP avoids ambiguity by using
“.” for concatenation
– It can also detect variables
inside strings due to the “$” at
the start of variable names
Type Conversion Example – String Concatenation
– JavaScript always coerces both values
to strings and concatenate them
– Even if one of the strings contains a
number…
var num = 79.4;
alert(num + ' is the total')
'79.4 is the total'
var string_num = '25';
alert(num + string_num)
'79.425'
JavaScript $total = 79.4;
echo 'The total is ' . $total;
'The total is 79.4'
echo "$total is the total";
'79.4 is the total'
PHP
total = 79.4
print(total, 'is the total. The total is', total)
'79.4 is the total. The total is 79.4'
Python
– As covered last week, Python’s print() function offers yet another way of
combining strings and numbers…
14
Type Conversion Example – Boolean Values
• True and False are the only two boolean values, but values of other data types
can always be converted to a boolean value
– The bool() function converts a value to a boolean value
• The rule that most languages follow when converting to a boolean value is:
– Values equivalent to 0, or empty/blank values are considered False
– All other values are considered True
• As always, there can be subtle differences between languages…
e.g. '0' (a string of the “zero” character) is True in Python, but False in PHP
15
bool(0) # int of 0
False
bool(0.0) # float of 0.0
False
bool('') # empty string
False
bool([]) # an empty "list"
False
Python
bool(5) # positive int
True
bool(-245.271) # negative float
True
bool('False') # string of 'False'
True
bool('0') # string of 0
True
Python
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!
16
Selection
Selection
• When a program is run, it runs the statements in the source code from start to
end (unless it encounters an error)
– Certain statements allow for a choice between different blocks of code to run based
upon the result of checking for a specific condition
– These are known as selection statements
– In this example, the beeping noise only occurs if the timer value is 0
• We will examine the most common selection statement – “if-then” (aka just “if”)
– Can be extended upon with “else” and “else-if”
– Another selection statement, “switch”, is covered in Reading 2.4
If timer value is 0
Make beeping noise
Pseudocode
18
If-Then Statements
• An if-then statement will run a block of code only if a condition
(known as a “boolean expression”) evaluates to True
– Often used run certain code in response to user input
19
condition
True
False
only run if true
// tax free threshold check
int income;
printf("Enter income: ");
scanf("%d", &income);
if(income <= 18200)
{
printf("No tax for you!");
}
C
# tax free threshold check
income = int(input('Enter income: '))
if income <= 18200:
print('No tax for you!')
Python
If-Then Statements
• The structure of an if-then statement is largely the same in most languages,
although Python strives for readability and uses indentation
– Most languages:
if (<boolean expression>)
{
<code to run if True>
}
– Python:
if <boolean expression>:
<code to run if True>
20
Boolean expression
in parentheses
No parentheses, but
a colon at the end
True-code controlled by indentation
(4 spaces is the standard/default)
True-code enclosed by braces (curly brackets)
If-Then Statements
• There are some subtle nuances that you should be aware of…
(remember, we’re learning a concept, not a language)
– In languages that use braces (curly brackets), they are usually optional if only one
statement is to be run when the expression is true:
if (<boolean expression>)
<single statement to run if True>
<code to run regardless>
– Some languages use (or just allow) “endif” instead of braces:
if (<boolean expression>)
<code to run if True>
endif
21
Boolean Expressions & Comparison Operators
• Selection statements choose which code to run based upon the result of a
boolean expression – i.e. An expression that results in either True or False
• You can compare values and receive a True or False result by using a
comparison operator
– Many functions will return (result in) either True or False
– A non-boolean value can be coerced to either True or False
22
Comparison Operator Description Example Example Result
< Less than 7 < 2 False
<= Less than or equal to 5 <= 5 True
> Greater than 7 > 2 True
>= Greater than or equal to 7 >= 2 True
== Equal to 7 == 2 False
!= Not equal to 7 != 2 True
If-Then / Boolean Expression Examples
• Example 1: Comparing a numeric variable to a number:
– The input was converted to a float (using the float() function), so that the
“less than” comparison with a number works as intended
• Example 2: Using a function in a comparison:
– The built-in function len() returns the “number of items in an object” (in this case,
the number of characters in the string)
– We are using a “not equal to” comparison (!=) to check if the length of the string is
not equal to 5
23
Prompt user to type exactly 5 characters
If input length != 5
Show error message
Pseudocode
value = input('Enter exactly 5 characters: ')
if len(value) != 5:
print('Error: Incorrect number of characters.')
Python
Prompt user for a score out of 100
If score < 50
Show 'You fail!'
Pseudocode
score = float(input('Enter a score out of 100: '))
if score < 50:
print('You fail!')
Python
If-Then / Boolean Expression Examples
• Example 3: Using a boolean value returned from a function:
– .isupper() is a function that can only be used on strings, hence why it is
“attached to the end” of the string variable instead of being “wrapped around it”
– .isupper() returns True if all of the letters in the string are uppercase
• Example 4: Using a coerced boolean value:
– The value variable is coerced to a boolean value (see earlier slide):
An empty string ('') is False, anything else is True
24
Prompt user to type something in upper case
If user typed something in upper case
Congratulate user
Pseudocode
value = input('Enter something in upper case: ')
if value.isupper():
print('Congratulations on typing in upper case!')
Python
Prompt user to type anything
If user typed at least one character
Congratulate user
Pseudocode
value = input('Type anything!: ')
if value:
print('Well done!')
Python
Logical Operators
• Often you will need to make multiple comparisons in a boolean expression.
For this we use logical operators
– e.g. “is A and B True?”, or “is A or B True?”
– You may also find situations where you want to know if something is not true, i.e.
turn False into True and vice-versa
– For added readability, Python uses “and”, “or” and “not” for logical operators.
Many languages use “&&”, “||” and “!”
Logical Operator
Description Example
Example
Result
Python Alternate
and && True if both comparisons are true, otherwise false 1 < 5 and 4 == 6 False
or ||
True if either (or both) comparison is true,
false if they are both false
1 < 5 or 4 == 6 True
not ! Reverse/Flip true and false not (1 < 5) False
25
Logical Operator Truth Tables & Evaluation
• These “truth tables” illustrate which situations will result in which outcome when
using logical operators:
– An “and” will only be True if both expressions are True; If either (or both) are False,
the end result is False
– An “or” will be True if either (or both) expressions are True
• Logical operators are evaluated after evaluating the expressions on either side
of them to True/False
26
and True False
True True False
False False False
or True False
True True True
False True False
5 > 2
and
6 < 4
True
and
False
False
If-Then / Logical Operator Examples
• Example 1: Using “and”:
• Example 2: Using “or”:
– count() is a function that can be used on strings. It returns the number of
occurrences of a specified string within another string
• Example 3: Using “not”:
– .isalpha() is another function that can only be used on strings.
It returns True if all of the characters in the string are letters
27
Prompt user to a number between 5 and 15
If number is between 5 and 15
Congratulate user
Pseudocode
value = float(input('Enter a number between 5 and 15: '))
if value >= 5 and value <= 15:
print('Well done!')
Python
Prompt user to type at least 5 characters, no spaces
If input length < 5 or input contains spaces
Show 'Better luck next time!'
Pseudocode
value = input('Enter at least 5 characters, with no spaces: ')
if len(value) < 5 or value.count(' ') > 0:
print('Better luck next time!')
Python
Prompt user to type something that isn't a letter
If input is not a letter
Congratulate user
Pseudocode
value = input('Type something that is not a letter: ')
if not value.isalpha():
print('Well done!')
Python
Terrible Programmer Joke Break!
Mum said, “Please go to the market and get a bottle of milk,
and if they have eggs, get six.”
I came back with six bottles of milk.
Mum asked, “Why did you get six bottles of milk?!”
I replied, “Because they had eggs!”
28
Boolean Expression & Logical Operator Notes
• Each side of an “and” or an “or” must be a full comparison
– x == 0 or 1 ✘
• Boolean expressions can have multiple logical operators
– Order of operations: “not” first, then “and”, then “or”
– e.g. True or False and not True
– Parentheses can be used to alter order of operations
– e.g. (True or False) and not True (result is False)
– Even if not altering the order of operations, parentheses are a good way to make
your code clearer and more readable
x == 0 or x == 1 ✔
True or False and False (not evaluated)
True or False (and evaluated)
True (or evaluated)
31
If-Then-Else Statements
• An if-then-else statement runs one block of code if the boolean expression is
true, and another block if it is false – it is an extension of an if-then statement
32
# test result check
result = int(input('Enter your result: '))
if result >= 50:
print('You passed!')
else:
print('You failed!')
Python
condition
True False
only run if true only run if false
// checkbox check
if (document.form.checkbox.checked)
{
alert('Checkbox checked!')
}
else
{
alert('Checkbox not checked!')
}
JavaScript
If-Then-Else Statements
• An if-then-else statement uses the word “else” to indicate the block of code to be
run if the expression is False
– Everything we have discussed regarding if-then is relevant to if-then-else
(e.g. optional braces for single statements)
– Most languages:
33
if (<boolean expression>)
{
<code to run if True>
}
else
{
<code to run if False>
}
if <boolean expression>:
<code to run if True>
else:
<code to run if False>
– Python:
If-Then-Else Examples
– Prompt user to type their name
– If the name consists of only alphabetic
characters, print “Letters!”
– Otherwise print “Not all letters!”
– total_mark is an integer
– exam_passed is a boolean
– If both conditions are True (&& is and),
“You passed!” otherwise “You failed!”
• The else applies to all other outcomes
(one or both conditions False)
if (total_mark >= 50 && exam_passed)
{
System.out.println("You passed!");
}
else
{
System.out.println("You failed!");
}
Java
name = input('Name: ')
if name.isalpha():
print('Letters!')
else:
print('Not all letters!')
Python
34
Nested If-Then-Else Statements
• If-Then-Else statements can be “nested” within one another
– This allows you to test multiple conditions and run different code depending on which
ones are met, to implement whatever sequences of checks your program needs…
35
if <condition 1>:
<run if condition 1 True>
else:
if <condition 2>:
<run if condition 1 False
and condition 2 True>
else:
<run if both False>
Python if (<condition 1>)
{
<run if condition 1 True>
}
else
{
if (<condition 2>)
{
<run if condition 1 False
and condition 2 True>
}
else
{
<run if both False>
}
}
Most Languages
(This is just one example of how
selection statements can be nested:
Any desired flow of logic possible!)
Else-If
• If-Then can be also expanded by using an Else-If
– This allows you to “chain” selection statements together
– Only the code following the first condition that is True is run
36
condition
1
True
False
only run if
condition 1 true
condition
2
condition
3
False
False
True only run if
condition 3 true
True only run if
condition 2 true
only run if all
conditions false
• Languages use slightly different
else-if syntax:
– “else if”
• C, C++, Java, PHP, JavaScript…
– “elseif”
• PHP, Visual Basic…
– “elsif”
• Ada, Perl, Ruby…
– “elif”
• Python, Bash…
Else-If
• While the word used for else-if may differ between languages, it works the same
in pretty much all of them
– Remember, Python uses indentation instead of braces (“{}”)!
37
if <condition 1>:
<run if condition 1 True>
elif <condition 2>:
<run if condition 2 True>
elif <condition 3>:
<run if condition 3 True>
elif <condition 4>:
<run if condition 4 True>
else:
<run if all conditions False>
Python
if (<condition 1>) {
<run if condition 1 True>
}
else if (<condition 2>) {
<run if condition 2 True>
}
else if (<condition 3>) {
<run if condition 3 True>
}
else if (<condition 4>) {
<run if condition 4 True>
}
else {
<run if all conditions False>
}
Most Languages
Placing the opening brace after the
condition/else instead of on a separate
line is a common space-saving technique
Else-If Example
• Here’s an (overused) example for grade calculation:
# calculate grade from mark
mark = float(input('Enter your mark: '))
if mark >= 80:
grade = 'HD (High Distinction)'
elif mark >= 70:
grade = 'D (Distinction)'
elif mark >= 60:
grade = 'CR (Credit)'
elif mark >= 50:
grade = 'P (Pass)'
else:
grade = 'F (Fail)'
print('Your grade is:', grade)
Python
PROMPT for mark
IF mark >= 80
SET grade to 'HD'
ELSE IF mark >= 70
SET grade to 'D'
ELSE IF mark >= 60
SET grade to 'CR'
ELSE IF mark >= 50
SET grade to 'P'
ELSE
SET grade to 'F'
DISPLAY grade
Pseudocode
38
Else-If Example
• A flowchart for this program would look like:
39
mark
>= 80
True
False
Set grade to HD
mark
>= 70
mark
>= 50
False
False
True
Set grade to P
True
Set grade to D
Set grade to F
Prompt for
mark
mark
>= 60
True
Set grade to CR
False Display
grade
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…
• If-Then statements allow you to make a choice in your code
– Controlled by boolean expressions, which can involve comparison operators and
logical operators
– If-Then-Else to do one thing or another
– Else-If to chain multiple comparisons together
40

More Related Content

Similar to ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf

Chapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptxChapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptx
lemonchoos
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
marvellous2
 
Programming Basics.pptx
Programming Basics.pptxProgramming Basics.pptx
Programming Basics.pptx
mahendranaik18
 
Literals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiersLiterals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiers
Tanishq Soni
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
Madishetty Prathibha
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
BG Java EE Course
 
Escape Sequences and Variables
Escape Sequences and VariablesEscape Sequences and Variables
Escape Sequences and Variables
yarkhosh
 
01 Java Language And OOP PART I
01 Java Language And OOP PART I01 Java Language And OOP PART I
01 Java Language And OOP PART I
Hari Christian
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
Connex
 
Python Data-Types
Python Data-TypesPython Data-Types
Python Data-Types
Akhil Kaushik
 
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdfPy-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
shetoooelshitany74
 
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
notwa dfdfvs gf fdgfgh  s thgfgh frg regggnotwa dfdfvs gf fdgfgh  s thgfgh frg reggg
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
Godwin585235
 
chapter-1-review-of-python-basics-copy.pdf
chapter-1-review-of-python-basics-copy.pdfchapter-1-review-of-python-basics-copy.pdf
chapter-1-review-of-python-basics-copy.pdf
SangeethManojKumar
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1
Devashish Kumar
 
codingtechniques1.ppt
codingtechniques1.pptcodingtechniques1.ppt
codingtechniques1.ppt
azida3
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
Tushar B Kute
 
OOP - Lecture04 - Variables, DataTypes and TypeConversion.pptx
OOP - Lecture04 - Variables, DataTypes and TypeConversion.pptxOOP - Lecture04 - Variables, DataTypes and TypeConversion.pptx
OOP - Lecture04 - Variables, DataTypes and TypeConversion.pptx
AhmedMehmood35
 
unit1 python.pptx
unit1 python.pptxunit1 python.pptx
unit1 python.pptx
TKSanthoshRao
 
C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1
Ali Raza Jilani
 
Introduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh SinghIntroduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh Singh
singhadarsh
 

Similar to ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf (20)

Chapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptxChapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptx
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Programming Basics.pptx
Programming Basics.pptxProgramming Basics.pptx
Programming Basics.pptx
 
Literals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiersLiterals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiers
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
Escape Sequences and Variables
Escape Sequences and VariablesEscape Sequences and Variables
Escape Sequences and Variables
 
01 Java Language And OOP PART I
01 Java Language And OOP PART I01 Java Language And OOP PART I
01 Java Language And OOP PART I
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
 
Python Data-Types
Python Data-TypesPython Data-Types
Python Data-Types
 
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdfPy-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
 
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
notwa dfdfvs gf fdgfgh  s thgfgh frg regggnotwa dfdfvs gf fdgfgh  s thgfgh frg reggg
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
 
chapter-1-review-of-python-basics-copy.pdf
chapter-1-review-of-python-basics-copy.pdfchapter-1-review-of-python-basics-copy.pdf
chapter-1-review-of-python-basics-copy.pdf
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1
 
codingtechniques1.ppt
codingtechniques1.pptcodingtechniques1.ppt
codingtechniques1.ppt
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
OOP - Lecture04 - Variables, DataTypes and TypeConversion.pptx
OOP - Lecture04 - Variables, DataTypes and TypeConversion.pptxOOP - Lecture04 - Variables, DataTypes and TypeConversion.pptx
OOP - Lecture04 - Variables, DataTypes and TypeConversion.pptx
 
unit1 python.pptx
unit1 python.pptxunit1 python.pptx
unit1 python.pptx
 
C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1
 
Introduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh SinghIntroduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh Singh
 

More from lailoesakhan

ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdfProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
lailoesakhan
 
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdfProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
lailoesakhan
 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
lailoesakhan
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
lailoesakhan
 
ProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdfProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdf
lailoesakhan
 
ProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdfProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdf
lailoesakhan
 
ProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdfProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdf
lailoesakhan
 

More from lailoesakhan (7)

ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdfProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
 
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdfProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
 
ProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdfProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdf
 
ProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdfProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdf
 
ProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdfProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdf
 

Recently uploaded

bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
Divyam548318
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
IJNSA Journal
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
University of Maribor
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
MIGUELANGEL966976
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt
PuktoonEngr
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
nooriasukmaningtyas
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
mahammadsalmanmech
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
ihlasbinance2003
 

Recently uploaded (20)

bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
 

ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf

  • 1. Programming Fundamentals Lecture 2: Data Types and Selection
  • 2. 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 • Selection – If-then, if-then-else and else-if statements – Boolean expressions – Comparison operators and logical operators 2
  • 3. Textbook • Starting Out with Python, 4th Edition (Global) – 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 3
  • 5. Data Types • Last week we introduced the concept of variables – Assigning a name to data stored in memory for later use • We also briefly 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) in a program 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 values of a certain data type, e.g. round() needs a float and an integer: round(2.327, 2) 5
  • 6. Data Types • The most common data types are: • 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 used to represent a string Type Description Examples integer (int) Whole numbers 2, -500, 4294967296 float (float) Numbers with a fractional part 3.14159, -0.3, 25.0 string (str) A sequence of characters 'Hello, World!', '25', ' ' boolean (bool) A true or false value True, False 6
  • 7. “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 easier to mix different data types together and converting between them automatically wherever appropriate • 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 by the programmer • 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 7
  • 8. 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 a string of 'cat' to an int – Some conversions may involve a loss of data, e.g. converting 3.14 to an int • Many languages do implicit (automatic) conversion between compatible data types as needed, where possible; This is known as coercion – Integers are commonly coerced to floats, e.g. 5 + 2.5 would become 5.0 + 2.5 – Languages like PHP can coerce numeric strings, e.g. 1 + '2' + 3.4 = 6.4 8
  • 9. • “Static typing” is when a language requires you to declare (and adhere to) the data type of every variable you create. C and Java are statically typed – Trying to assign a value of a different type will result in an error (or coercion) – Helps program optimisation and to prevent type-related bugs • “Dynamic typing” is when the data type of a variable is determined by the value it currently refers to, which can change. Python and PHP are dynamically typed – You do not “declare” a data type for the variable, you just assign a value to it – Convenient, particularly in languages which coerce data types automatically Static and Dynamic Typing String value; // declare a string value = 1; // assign int to string Error: Incompatible types Java value = 1 # int 1 value = 'Potato' # string 'Potato' value = -2.74 # float -2.74 Python int value; // declare an int value = 3.14; // assign float to int 3 C 9 total HELLO, my name is…
  • 10. Type Conversion Example – Numbers • What is happening in these examples? – 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 integer portion only – In Python (and other “weakly typed” languages), the result of dividing two integers is automatically coerced to a float 10 int value1 = 15; int value2 = 20; float result = value1 / value2; System.out.println(result); 0.0 Java value1 = 15 value2 = 20 result = value1 / value2 print(result) 0.75 Python
  • 11. Type Conversion Example – Numbers • In this version, we explicitly convert value_one to a float – We use (float) to convert value_one, an integer, to a float – 15.0 • Java will coerce value_two 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 / float = float 11 int value_one = 15; int value_two = 20; float result = (float) value_one / value_two; // convert value1 to float System.out.println(result); 0.75 Java • float / int = float • int / float = float
  • 12. Type Conversion Example – String Concatenation • What is happening in these examples? – Both of them are trying to combine a string and a float • In the first one, the error message says that concatenation can only be performed between strings, not between a string and a float • 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, i.e. 'The total is 79.4' or '79.4 is the total' • The solution to both is to convert total to a string: str(total) 12 total = 79.4 output = 'The total is ' + total TypeError: can only concatenate str (not "float") to str output = total + ' is the total' TypeError: unsupported operand type(s) for +: 'float' and 'str' Python
  • 13. Type Conversion Example – String Concatenation • In this version, we explicitly convert total to a string – 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 without any problems • Reminder: The total variable still refers to a float of 79.4 – the str() function simply produces a string version of the value – it does not change the variable itself – Concatenating numbers and strings is an area that languages handle differently • We’ll look at some examples on the next slide! 13 total = 79.4 output = 'The total is ' + str(total) 'The total is 79.4' output = str(total) + ' is the total' '79.4 is the total' Python
  • 14. – PHP avoids ambiguity by using “.” for concatenation – It can also detect variables inside strings due to the “$” at the start of variable names Type Conversion Example – String Concatenation – JavaScript always coerces both values to strings and concatenate them – Even if one of the strings contains a number… var num = 79.4; alert(num + ' is the total') '79.4 is the total' var string_num = '25'; alert(num + string_num) '79.425' JavaScript $total = 79.4; echo 'The total is ' . $total; 'The total is 79.4' echo "$total is the total"; '79.4 is the total' PHP total = 79.4 print(total, 'is the total. The total is', total) '79.4 is the total. The total is 79.4' Python – As covered last week, Python’s print() function offers yet another way of combining strings and numbers… 14
  • 15. Type Conversion Example – Boolean Values • True and False are the only two boolean values, but values of other data types can always be converted to a boolean value – The bool() function converts a value to a boolean value • The rule that most languages follow when converting to a boolean value is: – Values equivalent to 0, or empty/blank values are considered False – All other values are considered True • As always, there can be subtle differences between languages… e.g. '0' (a string of the “zero” character) is True in Python, but False in PHP 15 bool(0) # int of 0 False bool(0.0) # float of 0.0 False bool('') # empty string False bool([]) # an empty "list" False Python bool(5) # positive int True bool(-245.271) # negative float True bool('False') # string of 'False' True bool('0') # string of 0 True Python
  • 16. 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! 16
  • 18. Selection • When a program is run, it runs the statements in the source code from start to end (unless it encounters an error) – Certain statements allow for a choice between different blocks of code to run based upon the result of checking for a specific condition – These are known as selection statements – In this example, the beeping noise only occurs if the timer value is 0 • We will examine the most common selection statement – “if-then” (aka just “if”) – Can be extended upon with “else” and “else-if” – Another selection statement, “switch”, is covered in Reading 2.4 If timer value is 0 Make beeping noise Pseudocode 18
  • 19. If-Then Statements • An if-then statement will run a block of code only if a condition (known as a “boolean expression”) evaluates to True – Often used run certain code in response to user input 19 condition True False only run if true // tax free threshold check int income; printf("Enter income: "); scanf("%d", &income); if(income <= 18200) { printf("No tax for you!"); } C # tax free threshold check income = int(input('Enter income: ')) if income <= 18200: print('No tax for you!') Python
  • 20. If-Then Statements • The structure of an if-then statement is largely the same in most languages, although Python strives for readability and uses indentation – Most languages: if (<boolean expression>) { <code to run if True> } – Python: if <boolean expression>: <code to run if True> 20 Boolean expression in parentheses No parentheses, but a colon at the end True-code controlled by indentation (4 spaces is the standard/default) True-code enclosed by braces (curly brackets)
  • 21. If-Then Statements • There are some subtle nuances that you should be aware of… (remember, we’re learning a concept, not a language) – In languages that use braces (curly brackets), they are usually optional if only one statement is to be run when the expression is true: if (<boolean expression>) <single statement to run if True> <code to run regardless> – Some languages use (or just allow) “endif” instead of braces: if (<boolean expression>) <code to run if True> endif 21
  • 22. Boolean Expressions & Comparison Operators • Selection statements choose which code to run based upon the result of a boolean expression – i.e. An expression that results in either True or False • You can compare values and receive a True or False result by using a comparison operator – Many functions will return (result in) either True or False – A non-boolean value can be coerced to either True or False 22 Comparison Operator Description Example Example Result < Less than 7 < 2 False <= Less than or equal to 5 <= 5 True > Greater than 7 > 2 True >= Greater than or equal to 7 >= 2 True == Equal to 7 == 2 False != Not equal to 7 != 2 True
  • 23. If-Then / Boolean Expression Examples • Example 1: Comparing a numeric variable to a number: – The input was converted to a float (using the float() function), so that the “less than” comparison with a number works as intended • Example 2: Using a function in a comparison: – The built-in function len() returns the “number of items in an object” (in this case, the number of characters in the string) – We are using a “not equal to” comparison (!=) to check if the length of the string is not equal to 5 23 Prompt user to type exactly 5 characters If input length != 5 Show error message Pseudocode value = input('Enter exactly 5 characters: ') if len(value) != 5: print('Error: Incorrect number of characters.') Python Prompt user for a score out of 100 If score < 50 Show 'You fail!' Pseudocode score = float(input('Enter a score out of 100: ')) if score < 50: print('You fail!') Python
  • 24. If-Then / Boolean Expression Examples • Example 3: Using a boolean value returned from a function: – .isupper() is a function that can only be used on strings, hence why it is “attached to the end” of the string variable instead of being “wrapped around it” – .isupper() returns True if all of the letters in the string are uppercase • Example 4: Using a coerced boolean value: – The value variable is coerced to a boolean value (see earlier slide): An empty string ('') is False, anything else is True 24 Prompt user to type something in upper case If user typed something in upper case Congratulate user Pseudocode value = input('Enter something in upper case: ') if value.isupper(): print('Congratulations on typing in upper case!') Python Prompt user to type anything If user typed at least one character Congratulate user Pseudocode value = input('Type anything!: ') if value: print('Well done!') Python
  • 25. Logical Operators • Often you will need to make multiple comparisons in a boolean expression. For this we use logical operators – e.g. “is A and B True?”, or “is A or B True?” – You may also find situations where you want to know if something is not true, i.e. turn False into True and vice-versa – For added readability, Python uses “and”, “or” and “not” for logical operators. Many languages use “&&”, “||” and “!” Logical Operator Description Example Example Result Python Alternate and && True if both comparisons are true, otherwise false 1 < 5 and 4 == 6 False or || True if either (or both) comparison is true, false if they are both false 1 < 5 or 4 == 6 True not ! Reverse/Flip true and false not (1 < 5) False 25
  • 26. Logical Operator Truth Tables & Evaluation • These “truth tables” illustrate which situations will result in which outcome when using logical operators: – An “and” will only be True if both expressions are True; If either (or both) are False, the end result is False – An “or” will be True if either (or both) expressions are True • Logical operators are evaluated after evaluating the expressions on either side of them to True/False 26 and True False True True False False False False or True False True True True False True False 5 > 2 and 6 < 4 True and False False
  • 27. If-Then / Logical Operator Examples • Example 1: Using “and”: • Example 2: Using “or”: – count() is a function that can be used on strings. It returns the number of occurrences of a specified string within another string • Example 3: Using “not”: – .isalpha() is another function that can only be used on strings. It returns True if all of the characters in the string are letters 27 Prompt user to a number between 5 and 15 If number is between 5 and 15 Congratulate user Pseudocode value = float(input('Enter a number between 5 and 15: ')) if value >= 5 and value <= 15: print('Well done!') Python Prompt user to type at least 5 characters, no spaces If input length < 5 or input contains spaces Show 'Better luck next time!' Pseudocode value = input('Enter at least 5 characters, with no spaces: ') if len(value) < 5 or value.count(' ') > 0: print('Better luck next time!') Python Prompt user to type something that isn't a letter If input is not a letter Congratulate user Pseudocode value = input('Type something that is not a letter: ') if not value.isalpha(): print('Well done!') Python
  • 28. Terrible Programmer Joke Break! Mum said, “Please go to the market and get a bottle of milk, and if they have eggs, get six.” I came back with six bottles of milk. Mum asked, “Why did you get six bottles of milk?!” I replied, “Because they had eggs!” 28
  • 29. Boolean Expression & Logical Operator Notes • Each side of an “and” or an “or” must be a full comparison – x == 0 or 1 ✘ • Boolean expressions can have multiple logical operators – Order of operations: “not” first, then “and”, then “or” – e.g. True or False and not True – Parentheses can be used to alter order of operations – e.g. (True or False) and not True (result is False) – Even if not altering the order of operations, parentheses are a good way to make your code clearer and more readable x == 0 or x == 1 ✔ True or False and False (not evaluated) True or False (and evaluated) True (or evaluated) 31
  • 30. If-Then-Else Statements • An if-then-else statement runs one block of code if the boolean expression is true, and another block if it is false – it is an extension of an if-then statement 32 # test result check result = int(input('Enter your result: ')) if result >= 50: print('You passed!') else: print('You failed!') Python condition True False only run if true only run if false // checkbox check if (document.form.checkbox.checked) { alert('Checkbox checked!') } else { alert('Checkbox not checked!') } JavaScript
  • 31. If-Then-Else Statements • An if-then-else statement uses the word “else” to indicate the block of code to be run if the expression is False – Everything we have discussed regarding if-then is relevant to if-then-else (e.g. optional braces for single statements) – Most languages: 33 if (<boolean expression>) { <code to run if True> } else { <code to run if False> } if <boolean expression>: <code to run if True> else: <code to run if False> – Python:
  • 32. If-Then-Else Examples – Prompt user to type their name – If the name consists of only alphabetic characters, print “Letters!” – Otherwise print “Not all letters!” – total_mark is an integer – exam_passed is a boolean – If both conditions are True (&& is and), “You passed!” otherwise “You failed!” • The else applies to all other outcomes (one or both conditions False) if (total_mark >= 50 && exam_passed) { System.out.println("You passed!"); } else { System.out.println("You failed!"); } Java name = input('Name: ') if name.isalpha(): print('Letters!') else: print('Not all letters!') Python 34
  • 33. Nested If-Then-Else Statements • If-Then-Else statements can be “nested” within one another – This allows you to test multiple conditions and run different code depending on which ones are met, to implement whatever sequences of checks your program needs… 35 if <condition 1>: <run if condition 1 True> else: if <condition 2>: <run if condition 1 False and condition 2 True> else: <run if both False> Python if (<condition 1>) { <run if condition 1 True> } else { if (<condition 2>) { <run if condition 1 False and condition 2 True> } else { <run if both False> } } Most Languages (This is just one example of how selection statements can be nested: Any desired flow of logic possible!)
  • 34. Else-If • If-Then can be also expanded by using an Else-If – This allows you to “chain” selection statements together – Only the code following the first condition that is True is run 36 condition 1 True False only run if condition 1 true condition 2 condition 3 False False True only run if condition 3 true True only run if condition 2 true only run if all conditions false • Languages use slightly different else-if syntax: – “else if” • C, C++, Java, PHP, JavaScript… – “elseif” • PHP, Visual Basic… – “elsif” • Ada, Perl, Ruby… – “elif” • Python, Bash…
  • 35. Else-If • While the word used for else-if may differ between languages, it works the same in pretty much all of them – Remember, Python uses indentation instead of braces (“{}”)! 37 if <condition 1>: <run if condition 1 True> elif <condition 2>: <run if condition 2 True> elif <condition 3>: <run if condition 3 True> elif <condition 4>: <run if condition 4 True> else: <run if all conditions False> Python if (<condition 1>) { <run if condition 1 True> } else if (<condition 2>) { <run if condition 2 True> } else if (<condition 3>) { <run if condition 3 True> } else if (<condition 4>) { <run if condition 4 True> } else { <run if all conditions False> } Most Languages Placing the opening brace after the condition/else instead of on a separate line is a common space-saving technique
  • 36. Else-If Example • Here’s an (overused) example for grade calculation: # calculate grade from mark mark = float(input('Enter your mark: ')) if mark >= 80: grade = 'HD (High Distinction)' elif mark >= 70: grade = 'D (Distinction)' elif mark >= 60: grade = 'CR (Credit)' elif mark >= 50: grade = 'P (Pass)' else: grade = 'F (Fail)' print('Your grade is:', grade) Python PROMPT for mark IF mark >= 80 SET grade to 'HD' ELSE IF mark >= 70 SET grade to 'D' ELSE IF mark >= 60 SET grade to 'CR' ELSE IF mark >= 50 SET grade to 'P' ELSE SET grade to 'F' DISPLAY grade Pseudocode 38
  • 37. Else-If Example • A flowchart for this program would look like: 39 mark >= 80 True False Set grade to HD mark >= 70 mark >= 50 False False True Set grade to P True Set grade to D Set grade to F Prompt for mark mark >= 60 True Set grade to CR False Display grade
  • 38. 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… • If-Then statements allow you to make a choice in your code – Controlled by boolean expressions, which can involve comparison operators and logical operators – If-Then-Else to do one thing or another – Else-If to chain multiple comparisons together 40