Week 2: Data and Expressions PDF
Document Details
Uploaded by UnboundGyrolite7239
University of Wolverhampton
Yogesh Bikram Shah
Tags
Summary
This document provides an introduction to programming concepts in Python, specifically covering variables, operators, and data types. It explains the fundamentals, including concepts like literals, expressions, and how they function in the programming language. The document is suitable for introductory-level programming students.
Full Transcript
Introductory Programming and Problem-Solving Skills Week - 2 Yogesh Bikram Shah 1. Let’s Recap Navigation 1. Let’s Recap Module Structure How to think like computer? Problem Solving Skills...
Introductory Programming and Problem-Solving Skills Week - 2 Yogesh Bikram Shah 1. Let’s Recap Navigation 1. Let’s Recap Module Structure How to think like computer? Problem Solving Skills Algorithm, Flowchart and Pseudo code Introduction Python The IDLE Editor Python Standard Library 1.1 Researched? Navigation 1. Let’s Recap What is variable? 1.1 Researched? What is arithmetic operator? How To Take Input From User? How To Display Output To The User? 1.2 Let’s Discuss!! Navigation 1. Let’s Recap What is variable? 1.1 Researched? 1.2 Variable A variable is “a name that assigned to a value”, as shown below. n = 50 Variable n is assigned the value 50 Now, whenever variable n appears in a calculation, it is the value of n is that is used: n + 20 (5 + 20) 1.2 Let’s Discuss!! Navigation 1. Let’s Recap What is arithmetic operator? 1.1 Researched? 1.2 Variable Arithmetic Operators are operators (symbols) used to 1.3 Arithmetic Operator perform mathematical calculations. Addition, subtraction, and division use standard mathematical notation. For example, 2+5, 5-2, 4/2. Multiplication and exponential (*) is used. For example, 5 * 10 (5 times 10), 2** 4 (2 to the 4th power.) 1.4 Let’s Discuss!! Navigation 1. Let’s Recap ⮚ How To Take Input From User? 1.1 Researched? 1.2 Variable The program that we will request and get information from the 1.3 Arithmetic Operator 1.4 Basic Input user. In Python, the input function is used for this purpose. name = input('What is your name?: ') Characters within quotes are called Strings. This particular use of a string, for requesting input from the user, is called a prompt. The input function displays the string on the screen to prompt the user for input, What is your name?: Jeffrey 1.5 Let’s Discuss!! Navigation 1. Let’s Recap ⮚ How To Display Output To The User? 1.1 Researched? 1.2 Variable The print function is used to display information on the screen 1.3 Arithmetic Operator 1.4 Basic Input in Python. 1.5 Basic Output >>> print ('Welcome to My First Program!') Welcome to My First Program! or used to output the value of a variable you have defined: >>> n = 10 >>> print(n) 10 We will learn more about variables, operators, and input/output in further slides. Data and Expression 2. Introduction Navigation 1. Let’s Recap The generation, collection, and analysis of data is driving 1.1 Researched? force in today’s world. The01sheer amount of data is being 2. Introduction created is immense. For instances - Chain stores generates terabytes of customer information, looking for shopping patterns - Facebook users have created 40 billion photos requiring more than a petabyte of storage. [Interesting Fact]: The amount of data created each year is estimated to be almost to zetabytes (1021 or 1,000,000,000,000,000,000,000 bytes), more than doubling every two years Today, we will explore how data is represented and manipulated in Python. 3. Literals Navigation 1. Let’s Recap To take something literally is to take it at “face value”. The 1.1 Researched? 01 same is true of literals in programming. 2. Introduction 3. Literals Literals [Definition]: A literal is a sequence of one or more characters that stands for itself such as the literal 12. In Python, literals are the raw data that is assigned to variables or constants during programming. 3.1 Numeric Literals Navigation 1. Let’s Recap [Definition]: A numeric literal is a literal containing only the 1.1 Researched? 01 digit 0-9, an optional sign characters (+ or -), and a possible 2. Introduction decimal point. (The letter e is also used in exponential 3. Literals notation, shown next) 3.1 Numeric Literal Floating Point [Definition]: If a numeric literal contains a decimal point, then it denotes as floating-point values or commonly known as float. For example: 10.24 Integer [Definition]: If a numeric literal contains whole number then it is known to be integer. For example: 10 Note: Commas are never used in numeric literals 3.1.1 Let’s Understand Through Example Navigation 1. Let’s Recap 1.1 Researched? 01 2. Introduction 3. Literals 3.1 Numeric Literal 3.1.1 Example 3.1.2 Let’s Try!! Navigation 1. Let’s Recap 1.1 Researched? 01 2. Introduction Which of the following are valid numeric 3. Literals 3.1 Numeric Literal 3.1.1 Example literals in Python? 3.1.2 Try Out >>> 1024 >>> -1024 >>>.1024 >>> 1,024 >>> 0.01024 >>> 1,024.46 3.2 String Literals Navigation 1. Let’s Recap [Definition]: A string literal or “string”, represent a sequence 1.1 Researched? of characters: 01 2. Introduction 3. Literals 'Hello' 'Smith, John' "Baltimore, Maryland 21210" 3.1 Numeric Literal 3.2 String Literal In Python, string literals may be delimited (surrounded) by a matching pair of either single(‘’) or double(“”) quotes. String must be contained all on one line (except when delimited by triple quotes). 3.2.1 What’s inside quotes? Navigation 1. Let’s Recap A string may contain zero or more characters, including 1.1 Researched? 01 and blanks. letters, digits, special characters, 2. Introduction 3. Literals A string may also be empty which is different from blank 3.1 Numeric Literal 3.2 String Literal string. Empty strings consists of only a pair of matching 3.2.1 String, Quotes quotes (with nothing in between) whereas blank string contains a space inside matching quotes. Both empty and blank spaces have their own uses. Note: String may also contain quote characters as long as different quotes (single vs. double) are used to delimit the string. 3.2.2 Let’s Understand Through Example Navigation 1. Let’s Recap 1.1 Researched? 01 2. Introduction 3. Literals 3.1 Numeric Literal 3.2 String Literal 3.2.1 String, Quotes 3.2.2 Example 3.2.3 Let’s Try!! Navigation 1. Let’s Recap 1.1 Researched? 01 2. Introduction What will be displayed by each of 3. Literals 3.1 Numeric Literal 3.2 String Literal the following? 3.2.1 String, Quotes 3.2.2 Example 3.2.3 Try Out How will computer understand the Navigation 3. Literals 3.1 Numeric Literal characters? The answer is Unicode 01 3.2 String Literal encoding Unicode scheme [Definition]: Unicode is actually a 3.3 Unicode encoding scheme collection of different encoding schemes utilizing between 8 and 32 bits for each character. The default encoding Python uses UTF-8, an 8-bit encoding compatible with ASCII, an older, still widely used encoding Currently, there are over 100,000 Unicode- scheme. defined characters for many of the languages around the world. Unicode is capable of defining more than 4 billion characters. Thus, every languages can encoded in Unicode. 3.3.1 Representing Character Navigation 3. Literals Values 3.1 Numeric Literal 01 3.2 String Literal 3.3 Unicode encoding scheme 3.3.1 UTF Table UTF-8 encoded characters that have an ordering with sequential numerical values. For example, ‘A’ is encoded as 010000001 (65). This is also true for digit characters, ‘0’ is encoded as 48, ‘1’ as 49, etc. 3.3.2 Numeric Representation Navigation 3. Literals Vs. String Note the difference between a numeric 3.1 Numeric Literal representation 01 (thatcan be used in 3.2 String Literal 3.3 Unicode encoding arithmetic calculations) vs. a number scheme represented as a string of digit characters 3.3.1 UTF Table 3.3.2 Numeric (note used in calculation) Representation vs. String Explanation: Here, the binary representation of 124 is the binary number for that value. The string representation ‘124’ consists of longer sequences of bits, eight bits (one byte) for each 3.3.3 ord Function and chr Navigation Python has means of converting between a 3. Literals 3.1 Numeric Literal Function 01 3.2 String Literal character and its encoding: 3.3 Unicode encoding scheme The ord function: gives the UTF-8 (ASCII) 3.3.1 UTF Table encoding of a given character. For example, 3.3.2 Numeric Representation vs. ord('A')is 65 String 3.3.3 ord and chr The chr function: gives the character for a given encoding value, thus chr(65)is ‘A’ However, in general there is no need to know the specific encoding of a given character, there are times when such knowledge can be 3.3.4 What are Control Navigation Control characters [Definition]: Special 3. Literals 3.1 Numeric Literal Characters? characters which 01 are not displayed but, 3.2 String Literal 3.3 Unicode encoding rather control the display of output (among scheme other things.) Control characters do not have 3.3.1 UTF Table 3.3.2 Numeric corresponding keyboard character, and thus Representation vs. are represented by a combination of characters String called Escape escape sequence. sequence begin with an escape 3.3.3 ord and chr 3.3.4 Escape Character character that causes the characters following to “escape” their normal meaning. The backslash (\) serves as the escape character in Hello Python. Yogesh Bikram print ('Hello \nYogesh Bikram Shah') Shah Let’s Try!! Navigation 3. Literals 3.1 Numeric Literal 01 3.2 String Literal 3.3 Unicode encoding scheme >>> print(’Hello World’) >>> print(‘Hello\nWorld’) 3.3.1 UTF Table 3.3.2 Numeric >>> print(‘Hello World\n’) >>> print(‘Hello\n\nWorld’) Representation vs. >>> print (‘Hello World\n\n\’) >>> print(1, ‘\n’, 2, ‘\n’, 3) String 3.3.3 ord and chr >>> print (‘\nHello World’) >>> print(‘\n’, 1, ‘\n’, 2) 3.3.4 Escape Character Tryout Variables and Identifiers 4 Variable, True Usefulness Navigation 3. Literals So far, we have only01looked at literal values in 3.1 Numeric Literal 3.2 String Literal programs. However, the true usefulness of a 3.3 Unicode encoding scheme computer program is the ability to operate on different 4 Variable values each time the program is executed. This is provided by the notion of variable. Note: We will look at variables and identifiers next. 4.1 What is Variable? Navigation 3. Literals A variable is a name (identifier) 01 that is associated with 4 Variable, True Usefulness a value and can be used to store data. 4.1 Variable? Each variable must have a unique identifier value. A variable can be assigned different values during program’s execution, hence the num = 10. 4.2 Variable Assignment Navigation When a variable is appears01 in a program (except on the left- 3. Literals 4 Variable, True hand side of an assignment statement), it is the value Usefulness 4.1 Variable? associated with the variable used, and not the variable’s name. 4.2 Variable Assignment Variables are assigned values by use of the assignment operator, = 4.3 Does Not Make Sense!! Navigation Assignment statements 01often looks wrong to new 3. Literals 4 Variable, True programmers. Usefulness 4.1 Variable? Mathematically, 4.2 Variable Assignment num = num + 1 4.3 Does Not Make Sense!! 10 = 10 + 1 10 = 11??? Mathematically, it does not make sense. However, in programming it is used to increase value by 1 and assigned to the num variable. Note: This can be said to increment variable 4.4 Assignment Operator Navigation Let think this in steps: 3. Literals 01 4 Variable, True - The right side of the assignment is evaluated first. Usefulness 4.1 Variable? - The result is assigned to variable on the left. 4.2 Variable Assignment 4.3 Does Note Make Sense!! 4.4 Assignment Operator An arrow symbol is not used simply because there is no such characters on a standard computer keyboard. There are other assignment operators as well which we use to increase or decrease the variable. 4.5 Variable as Value Navigation Variables may also be assigned 3. Literals 01 to the value of another variable: 4 Variable, True Usefulness 4.1 Variable? 4.2 Variable Assignment 4.3 Does Not Make Sense!! Variables num and k are both associated with the same literal 4.4 Assignment Operator value 10 in memory. 4.5 Variable as Value 4.6 Dynamic Typing Navigation Finally, in Python the same01 variable can be associated with the 4.3 Does Not Make Sense!! values of different type during program execution: 4.4 Assignment Operator 4.5 Variable as Value 4.6 Dynamic Typing The ability of a variable to be assigned values of different type is referred as dynamic typing, introduced later in a discussion on data types Many other programming languages such as Java use static typing, in which variable must be defined at a compile time and cannot be changed at runtime. 5. What is an Identifier? Navigation An identifier is a sequence01 of one or more characters used to 4.3 Does Not Make Sense!! provide a name for a given program element. Variable names 4.4 Assignment Operator line and num_credits are identifiers. 4.5 Variable as Value 4.6 Dynamic Typing Python is case sensitive, thus Line is different from line. 5. Identifier The underscore character, _, can be used to aid in the readability of long identifier names. It should not be used as the first character, however as identifiers beginning with an underscore have a special meaning in Python. Navigation 5.1 Identifier Example 4.3 Does Not Make Sense!! 4.4 Assignment 01 Operator 4.5 Variable as Value 4.6 Dynamic Typing 5. Identifier 5.1 Example Spaces are not allowed as part of an identifier. This is a common error since some operating system allows spaces within the file names. In Python, however, spaces are used to delimit (separate) distinct syntactic entities. Thus, any identifier containing a space character would be considered two separate identifiers. 3.3 Let’s Try!! Navigation 4.3 Does Not Make Sense!! 01 4.4 Assignment What is displayed by each of Operator 4.5 Variable as Value the following? 4.6 Dynamic Typing 5. Identifier 5.1 Example Tryout Can we use and as variable? Navigation In Python, there are various 4.3 Does Not Make 01words which are predefined and Sense!! have a special meaning to that name. Such words are said to be 4.4 Assignment Operator keywords and cannot be used as regular identifiers. 4.5 Variable as Value 4.6 Dynamic Typing >>> and = 10 5. Identifier 5.1 Example 5.2 Predefined words as SyntaxError: invalid syntax variable identifier Since, and is a logical operator and has a special meaning in python, so when attempt to assign the identifier as and then a syntax error is thrown. Python Keywords Navigation The keywords in Python are01 listed below: 4.3 Does Not Make Sense!! 4.4 Assignment Operator 4.5 Variable as Value 4.6 Dynamic Typing 5. Identifier 5.1 Example To display the keywords in python, type help() in the Python 5.2 Predefined words as shell, then type words. variable identifier 5.3 Python Keywords A simple way to check whether a specific identifier is keyword in Python is as follows: >>> 'exit' in dir(__builtins__) True Operators 6. Operators Navigation Operator [Definition]: An operators is a symbol that represents 5. Identifier 01 6. Operators an operation that may be performed on one or more operands. Some of the operators of python are listed below: 1. Arithmetic Operator 2. Assignment Operator 3. Comparison Operator 4. Logical Operator 5. Identity Operator 6. Membership Operator 7. Bitwise Operator 6.1 Arithmetic Operators Navigation Arithmetic Operator [Definition]: Arithmetic operators are 5. Identifier 01 6. Operators binary operators which are used with numeric values to perform 6.1 Arithmetic Operator common mathematical operations. Arithmetic Operators Description Example Result -X Negation -10 -10 X+Y Addition 10 + 25 35 X-Y Subtraction 10 - 25 -15 X*Y Multiplication 10 * 5 50 X/Y Division 25 / 10 2.5 X // Y Truncating Division 25 // 10 2 X%Y Modulus 25 % 10 5 X ** Y Exponentiation 10 ** 2 100 Let’s Understand Through Example Navigation 5. Identifier 01 6. Operators 6.1 Arithmetic Operator Example Output Assignment Operators Navigation Assignment Operator [Definition]: Assignment operators are 5. Identifier 01 6. Operators binary operators which are used to assign the value to the 6.1 Arithmetic Operator 6.2 Assignment variable. Operator Some assignme nt operators 3.2 Let’s Understand Through Example Navigation 5. Identifier 01 6. Operators 6.1 Arithmetic Operator 6.2 Assignment Operator Example Output 6.3 Comparison Operators Navigation Comparison Operator [Definition]: Comparison operators are 5. Identifier 01 6. Operators binary operators which are used to check the relationship 6.1 Arithmetic Operator 6.2 Assignment between two operands. Operator 6.3 Comparison Operator Some comparis on operators 3.2 Let’s Understand Through Example Navigation 5. Identifier 01 6. Operators 6.1 Arithmetic Operator 6.2 Assignment Operator 6.3 Comparison Operator Example Output Logical Operators Navigation Logical Operator [Definition]: 5. Identifier 01 Logical operators are binary 6. Operators operators which are used to check either the expression is 6.1 Arithmetic Operator 6.2 Assignment true or false. Basically, they are used during the decision Operator 6.3 Comparison making scenario Operator Logical Operators Description Example 6.4 Logical Operator and Returns true when both x < 5 and x < 10 condition is true logical operators or Return true when any x < 5 or x < 10 one condition is true not Reverse the condition not(x < 5 and x < result 10) Let’s Understand Through Example Navigation 5. Identifier 01 6. Operators 6.1 Arithmetic Operator 6.2 Assignment Operator 6.3 Comparison Operator 6.4 Logical Operator Output Example Expression and Data Types 7. What is an Expression? Navigation An expression is a combination 6. Operators 01 of symbols that evaluates to a 7 Expression value. Expression, most commonly, consist of a combination of operators and operands. E.g. 4 + (3 * k) An expression can also consist of a single literal or variable. Thus 4, 3 and k are each expression. This expression has two subexpression, 4 and (3 * k). Subexpression (3 * k) itself has two sub expression, 3 and k. Note: Expression that evaluates to a numeric type are called arithmetic expression. Let’s Try!! Navigation 6. Operators 7 Expression Translate the following01 into Python algebraic or Tryouts Boolean expressions and then evaluate them: A. The difference between Annie’s age (25) and Ellie’s (21) B. The total of £14.99, £27.95, and £19.83 C. The area of a rectangle of length 20 and width 15 D. 2 to the 10th power E. The minimum of 3, 1, 8, -2, 5, -3, and 0 7.1 Operator Precedence Navigation The way we commonly represent expressions, in 6. Operators which operators appear 01 between their operands, 7 Expression 7.1 Operator is referred to as infix notation. For example, the Precedence expression 4 + 3 is in infix notation since the + operator appears between its two operands, 4 and 3. There are other ways of representing expressions called prefix and The expression postfix notation.4 + (3 * 5) is also in infix notation. It contains two operators,+ and *. The parentheses denote that (3 * 5) is a subexpression. Therefore, 4 and (3 * 5) are the operands of the addition operator, and thus the overall expression evaluates to 19. What if the parentheses were omitted, as given 4+3*5 below? Two Possibilities!! Navigation 4 + 3 * 5 -> 4 + 15 -> 19 4 + 3 * 5 -> 7 * 5 -> 35 6. Operators 01 7 Expression Some might say that the first version is the correct one by the 7.1 Operator Precedence conventions mathematics. However, each programming 7.2 Two Possibilities language has its own rules for the order that operators are applied, called operator precedence. This may or may not be same as in mathematics. Below the operator precedence table or Python operators discussed so far 7.3 Data Types Navigation 6. Operators A data type is a set of values, 7 Expression 01 and a set of operators that 7.1 Operator may be applied to those values. For example, integer data Precedence type consist of the set of integers, and operators for addition, 7.2 Two Possibilities subtraction, multiplication, and division among others. 7.3 Data Types Integer, floats and strings are part of a set of predefined data types in Python called the built-in-types. There are other built- in data types as well such Boolean, Collections and so on. For example, it does not make sense to try to divide a string by two, 'Hello' / 2. The programmer knows this by common sense. Python knows it because 'Hello' belongs to the string data type, which does not include the division operation. 7.4 Static Typing Vs. Dynamic Typing Navigation 6. Operators As we discussed, there are01 two approaches to data typing in 7 Expression 7.1 Operator programming language. In static typing, a variable is declared Precedence as a certain types before it is used, and can only be assigned 7.2 Two Possibilities values of that type. 7.3 Data Types 7.4 static vs. dynamic In dynamic typing, the data type of a variable depends only typing on the type of value that the variable is currently holding. Thus, the same variable may be assigned values of different type during the execution of a program. Python uses dynamic typing. 7.5 Mixed Type Expression Navigation 6. Operators A mixed-type expression is an expression containing 7 Expression 01 7.1 Operator operands of different type. Precedence 7.2 Two Possibilities The CPU can only perform operations on values with the 7.3 Data Types same internal representation scheme, and thus only on 7.4 static vs. dynamic typing operands of the same type. 7.5 Mixed Type Expression? Operands of mixed-type expressions therefore must be converted to a common type. Values can be converted in one of two ways—by implicit (automatic) conversion, called coercion, or by explicit type conversion. 7.6 Implicit Conversion (Coercion) Navigation 6. Operators Coercion is the implicit (automatic) conversion of operands to a 7 Expression 01 7.1 Operator common type. Coercion is automatically performed on Precedence mixed-type expressions only if the operands can be safely 7.2 Two Possibilities converted, that is, if no loss of information will result. 7.3 Data Types 7.4 static vs. dynamic The conversion of integer 2 to floating-point 2.0 below is a safe typing conversion—the conversion of 4.5 to integer 4 is not, since the 7.5 Mixed Type Expression? decimal digit would be lost, 7.6 Implicit 2 + 4.5 ➝ 2.0 + 4.5 ➝ 6.5 safe (automatic conversion of int to float) int float float float float 7.7 Explicit Conversion (Type Conversion) Navigation 7 Expression 7.1 Operator 01 conversion of operands to a Type conversion is the explicit Precedence 7.2 Two Possibilities specific type. Type conversion can be applied even if loss of 7.3 Data Types 7.4 static vs. dynamic information results. Python provides built-in type conversion typing functions int() and float(), with the int() function truncating 7.5 Mixed Type Expression? results. 7.6 Implicit 7.7 Explicit Explicit Conversion (Type Conversion) Navigation 7 Expression 7.1 Operator 01 int() and float() Type conversion functions Precedence 7.2 Two Possibilities 7.3 Data Types 7.4 static vs. dynamic typing 7.5 Mixed Type Expression? 7.6 Implicit 7.7 Explicit Note that numeric strings can also be converted to a numeric type. In fact, we have already been doing this when using int or float with the input function, >>> num_credits = int(input('How many credits do you have? ')) 8. Types of Errors Navigation 7 Expression Compile Time Error 7.1 Operator 01 Precedence Syntax Errors 7.2 Two Possibilities 7.3 Data Types Spelling, Capitalization, punctuation 7.4 static vs. dynamic Ordering of statements, matching of typing 7.5 Mixed Type braces/parenthesis… Expression? 7.6 Implicit Correct first error listed, then compile 7.7 Explicit 8. Bonus Topic again 8. Types of Errors Navigation 7 Expression 7.1 Operator Run Time Error 01 Precedence 7.2 Two Possibilities Logical Errors. 7.3 Data Types 7.4 static vs. dynamic Program runs, but produces unintended typing 7.5 Mixed Type results. Expression? 7.6 Implicit Program may crash. 7.7 Explicit 8. Bonus Topic