Lecture 2.2_ Expressions and Types.pdf

Full Transcript

Lecture 2.2 Expressions and Types Lecture Overview 1. Expressions 2. Types 3. Example Program: Temperature Converter 2 1. Expressions 3 What Are Expressions? ◎ An expression is a small piece of code that resolves to a value. ◎ Some extremely simple examples are: ○ 42 (a literal resolves to...

Lecture 2.2 Expressions and Types Lecture Overview 1. Expressions 2. Types 3. Example Program: Temperature Converter 2 1. Expressions 3 What Are Expressions? ◎ An expression is a small piece of code that resolves to a value. ◎ Some extremely simple examples are: ○ 42 (a literal resolves to itself). ○ my_var (a variable resolves to its value). 4 What Are Expressions? ◎ The highlighted parts of the code shown on the right are expressions. ◎ Note that only the right hand side of assignment is an expression. ○ The left hand side must be an identifier (e.g. a variable name). >>> 33.33 33.33 >>> artist = 'Avenade' >>> albums = 1 >>> albums 1 >>> new_albums = albums + 1 >>> new_albums 2 5 What Are Expressions? ◎ Expressions can use operators to compute a result. ◎ A combination of numeric values, operators, and sometimes parenthesis (). ○ 3.5 - 0.75 (resolves to 2.75). ○ x + y (resolves to the sum of x and y). ○ r + 1 (resolves to the value of r plus one). 6 Operators Numeric Operators OPERATOR NAME + Addition - Subtraction * Multiplication / Division ** Exponentiation % Modulo // Integer division ◎ An asterisk (*) denotes multiplication. ○ 2 * 3 (gives 6) ◎ A forward slash (/) denotes division. ○ 5 / 2 (gives 2.5) ◎ // Integer division ○ 5 / 2 (gives 2) ◎ A double asterisk (**) denotes "to the power of". ○ 2 ** 3 (gives 8) 7 Integer Division and Modulo ◎ Recall performing division by hand in school. ○ We would get two results: the quotient, and the remainder. ◎ For example, when evaluating 7 ÷ 2, we might say: "2 goes into 7 three times, with a remainder of one". ○ The quotient is 3. ○ The remainder is 1. 8 Integer Division and Modulo ◎ In Python: ○ Integer division (//) calculates the quotient. ○ Modulo (%) calculates the remainder. ◎ Examples: ○ 7 // 2 (gives 3) ○ 7 % 2 (gives 1) ◎ Can also think of integer division as regular division with the result rounded down. 9 Combining Expressions ◎ Multiple expressions can be combined: ○ e.g. 3 + 2 * 6 – 1 ◎ But how does Python decide which operator goes first? ○ In the above example, how does Python choose whether to do 3 + 2, 2 * 6, or 6 - 1 first? 10 Operator Precedence ◎ Each of the operators in Python has a certain precedence ("priority"). ◎ This is similar to mathematics. ○ Remember learning PEMDAS (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction) in school? ◎ Operators with higher precedence are evaluated first. ◎ Operators with the same precedence are evaluated leftto-right. 11 Operator Precedence OPERATOR () NAME Higher Parentheses ** Exponentiation *, /, %, // Multiplication, etc. +, - Lower Addition, etc. ◎ Similar order to mathematics (PEMDAS). ◎ Since parentheses have highest precedence, you can always explicitly group things. 12 Check Your Understanding Q. What does the expression 2 + 5 * 7 // (1 + 1) evaluate to? OPERATOR NAME () Parentheses ** Exponentiation *, /, %, // Multiplication, etc. +, - Addition, etc. 13 Check Your Understanding Q. What does the expression 2 + 5 * 7 // (1 + 1) evaluate to? A. 19. 1. 2 + 5 * 7 // (1 + 1) 2. 2 + 5 * 7 // 2 3. 2 + 35 // 2 4. 2 + 17 5. 19 OPERATOR NAME () Parentheses ** Exponentiation *, /, %, // Multiplication, etc. +, - Addition, etc. 14 2. Types 15 Primitive Types In Python, we can assign different values of different variables, and different types can do different things. The assigned values are known as Data Types. TYPE NAME DESCRIPTION EXAMPLE str String A string of characters (text). 'Hello' int Integer A whole number. -43 float Float A number with a decimal point. 23.6 bool Boolean A boolean (true/false) value. True Today we will discuss integers, floats, and strings. We will cover booleans in the next lecture. 16 Different Types of Numbers ◎ Integers (type int) represent whole numbers. ◎ Often used to represent counts of things: ○ Inventory levels ○ Age (in years) ○ Attendance ◎ -43, 0, and 10000 are all integers. ◎ Floating point numbers, or "floats", (type float) have a decimal point and fractional part. ◎ Often used to represent precise measurements: ○ Temperature ○ Percentages ○ Prices. ◎ 22.5, 0.0, and -0.9999 are all floats. 17 Strings ◎ String (type str) literals (snippets of text) are written between matched quotation marks. ○ e.g. 'text' or "text". >>> x = “1” >>> type(x) <class ‘str'> >>> type(‘hi’) <class ‘str’> >>> x=20 >>> print (str(x)) >>>’20’ 18 String Concatenation ◎ String concatenation means joining two pieces of text ("strings") together. ○ 'bed' + 'room' (gives 'bedroom’) ◎ Can be used to build a message to show the user. >>> name = 'Jeremiah' >>> print('Hello ' + name) Hello Jeremiah 19 String Concatenation Beware! You can't combine a string and a number using the "+" operator. We'll discuss how to avoid this error in the next part of the lecture as we learn about types. >>> 'My age is: ' + 28 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str 20 Determining Types ◎ Python can tell us the type of a value. ◎ Simply use the type() function. ◎ Especially useful in interactive sessions. >>> x = 1 >>> type(x) <class 'int'> >>> type(3.4) <class 'float'> >>> type(x + 3.4) <class 'float’> >>> type(“Hi CSE4P”) <class ‘str’> 21 Different Types Behave Differently ◎ There is a difference between 20, 20.0, and '20': ○ 20 is an integer. ○ 20.0 is a float. ○ '20' is a string. ◎ Python sees these values differently. ◎ Values of different types behave differently. ○ Python chooses what operators do based on types. 22 Check Your Understanding Q. What does the expression '1' + '2' evaluate to? 23 Check Your Understanding Q. What does the expression '1' + '2' evaluate to? A. The string '12'. Since both '1' and '2' are strings---not floats or integers--Python treats them as text and not numbers. So, when Python sees the + operator, it performs string concatenation instead of numerical addition. This is the same behaviour as our earlier example of 'bed' + 'room'. 24 Automatic Type Conversion ◎ Type conversion is the process of deriving a value of a different type from an existing value. ◎ Sometimes Python will automatically convert types. ◎ For example, when an integer and a float are added, the integer is automatically converted into a float. >>> x = 1 >>> x + 3.4 4.4 # Python converts the 1 to 1.0 25 Explicit Type Conversion ◎ Python doesn't always know how types should be converted, so there are times when you need to convert types explicitly. ◎ This can be achieved using the int(), float(), str(), and bool() functions. 26 Converting Numbers to Strings ◎ Converting numbers to strings can be useful for building output messages. ◎ Converting a float to a string will always include the decimal part, even if it is zero. >>> age = 28 >>> 'My age is: ' + str(age) 'My age is: 28' >>> str(420.0) '420.0' 27 Converting Strings to Numbers ◎ Converting strings to numbers can be useful for accepting input. ◎ If the string does not represent a number, Python will raise an error. >>> age = input('Enter your age: ') Enter your age: 28 >>> int(age) + 7 35 >>> float('apple') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: could not convert string to float: 'apple' 28 Check Your Understanding Q. What value does the following expression evaluate to? str(9 + 1.0) + '0' 29 Check Your Understanding Q. What value does the following expression evaluate to? str(9 + 1.0) + '0' A. The string '10.00'. 1. Python implicitly converts the 9 to 9.0, and adds 1.0 to get 10.0. 2. The str() function converts the float 10.0 to the string '10.0’. 3. Finally, the string '10.0' is concatenated with '0' to get '10.00'. 30 3. Example Program: Temperature Converter 31 Task Definition Create a program which converts a temperature value from degrees Celsius (C) to degrees Fahrenheit (F) using the following conversion formula, where C is the temperature in degrees Celsius and F is the temperature in degrees Fahrenheit: 32 Identifying Inputs and Outputs ◎ Input: C, the temperature in degrees Celsius. ◎ Output: F, the temperature in degrees Fahrenheit. ◎ Examples: ○ 0 °C → 32 °F ○ 100 °C → 212 °F ○ 22.5 °C → 68.9 °F 33 Identifying Processing Steps Example ◎ Input: 100 → C=100 ◎ Processing: 1. 100 × 9 = 900 2. 900 ÷ 5 = 180 3. 180 + 32 = 212 ◎ Output: 212 34 Drawing a Flowchart Start Input number Multiply by 9 Divide by 5 Add 32 Output number Stop Example ◎ Input: 100 ◎ Processing: 1. 100 × 9 = 900 2. 900 ÷ 5 = 180 3. 180 + 32 = 212 ◎ Output: 212 35 Translating to Python Code Start Input number Multiply by 9 Divide by 5 tc = input('Enter Celsius: ') x = float(tc) ◎ The input is initially read in as a string (type str). ◎ We convert it into a number (type float). Add 32 Output number Stop 36 Translating to Python Code Start Input number Multiply by 9 x = x * 9 ◎ The asterisk (*) "multiply" in Python. means Divide by 5 Add 32 Output number Stop 37 Translating to Python Code Start Input number Multiply by 9 x = x / 5 ◎ The forward slash (/) means "divide" in Python. Divide by 5 Add 32 Output number Stop 38 Translating to Python Code Start x = x + 32 Input number Multiply by 9 Divide by 5 Add 32 Output number Stop 39 Translating to Python Code Start Input number Multiply by 9 Divide by 5 tf = str(x) print('Fahrenheit: ' + tf) ◎ We convert our number (type float) into a string (type str) so that we can build our output message. Add 32 Output number Stop 40 The Final Program Start Input number Multiply by 9 Divide by 5 # Input tc = input('Enter Celsius: ') x = float(tc) # Processing x = x * 9 # Multiply by 9 x = x / 5 # Divide by 5 x = x + 32 # Add 32 # Output tf = str(x) print('Fahrenheit: ' + tf) Add 32 Output number Stop 41 Check Your Understanding Q. After reading user input, we converted the value into a float: x = float(tc) Why didn't we convert to an integer instead? x = int(tc) 42 Check Your Understanding Q. After reading user input, we converted the value into a float: x = float(tc) Why didn't we convert to an integer instead? A. Type int only supports whole numbers. Therefore using int() would not allow the user to input fractional temperatures, like 20.5. x = int(tc) 43 Live Coding Demo ◎ Let's say that you have to calculate a bunch of hypotenuse lengths (a totally normal thing that normal people have to do). ◎ You could use a calculator like a peasant, or you could write a program like a non-genderspecific member of the royal family! 😅 c a b 44 Live Coding Demo # a b c File: hypotenuse.py = float(input('Enter a: ')) = float(input('Enter b: ')) = (a ** 2 + b ** 2) ** 0.5 print('Hypotenuse: ' + str(c)) $ python hypotenuse.py Enter a: 3 Enter b: 4 Hypotenuse: 5.0 c a b 45 Summary 46 In This Lecture We... ◎ Explored simple expressions in Python and how they can be crafted using operators. ◎ Learnt about different basic data types in Python. ◎ Worked through the steps of solving a real problem with Python code. 47 Next Lecture We Will... ◎ Learn about the boolean type, comparison operators, and logical expressions. 48 Thanks for your attention! The slides and lecture recording will be made available on LMS. The “Cordelia” presentation template by Jimena Catalina is licensed under CC BY 4.0. PPT Acknowledgement: Dr Aiden Nibali, CS&IT LTU. 49

Use Quizgecko on...
Browser
Browser