Python Data Types Expressions, Variables, and Assignments Strings

Slides:



Advertisements
Similar presentations
CS 100: Roadmap to Computing Fall 2014 Lecture 0.
Advertisements

Types and Arithmetic Operators
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Introduction to Computing Using Python Imperative Programming  Python Programs  Interactive Input/Output  One-Way and Two-Way if Statements  for Loops.
Introduction to C Programming
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
1 Chapter 3 Arithmetic Expressions. 2 Chapter 3 Topics l Overview of Java Data Types l Numeric Data Types l Declarations for Numeric Expressions l Simple.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Introduction to C Programming
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
CS 100: Roadmap to Computing Fall 2014 Lecture 01.
Introduction to Computing Using Python Python  Python is an interactive language.  Java or C++: compile, run  Also, a main function or method  Python:
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Introduction to Python
Lists in Python.
Computing with Numbers Zelle - Chapter 3 Charles Severance - Textbook: Python Programming: An Introduction to Computer Science, John.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
Introduction to Computing Using Python Straight-line code  In chapter 2, code was “straight-line”; the Python statements in a file (or entered into the.
Input, Output, and Processing
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Built-in Data Structures in Python An Introduction.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
10. Python - Lists The list is a most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between.
Introduction to Computing Using Python for loop / def- ining a new function  Execution control structures ( if, for, function call)  def -ining a new.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Introduction to Programming Python Lab 3: Arithmetic 22 January PythonLab3 lecture slides.ppt Ping Brennan
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Introduction to Python Developed by Dutch programmer Guido van Rossum Named after Monty Python Open source development project Simple, readable language.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
String and Lists Dr. José M. Reyes Álamo.
Fundamentals of Programming I Overview of Programming
Topics Designing a Program Input, Processing, and Output
CS 100: Roadmap to Computing
Chapter 3 Instructor: Zhuojun Duan
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Python Data Types Expressions, Variables, and Assignments Strings
IDENTIFIERS CSC 111.
Introduction to C++ Programming
Ruth Anderson University of Washington CSE 160 Spring 2018
A First Book of ANSI C Fourth Edition
CS 100: Roadmap to Computing
String and Lists Dr. José M. Reyes Álamo.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Introduction to Computer Science
CS 100: Roadmap to Computing
CS 100: Roadmap to Computing
Data Types and Expressions
Data Types and Expressions
Introduction to Computer Science
Presentation transcript:

Python Data Types Expressions, Variables, and Assignments Strings Introduction to Computing Using Python Python Data Types Expressions, Variables, and Assignments Strings Lists Objects and Classes Python Standard Library

Algebraic expressions Introduction to Computing Using Python The Python interactive shell can be used to evaluate algebraic expressions >>> 2 + 3 5 >>> 7 - 5 2 >>> 2*(3+1) 8 >>> 2 + 3 5 >>> 7 - 5 2 >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 2 + 3 5 >>> 7 - 5 2 >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 >>> 2 + 3 5 >>> 7 - 5 2 >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 >>> 14//3 4 >>> 14%3 >>> 2**3 >>> 2 + 3 5 >>> 7 - 5 2 >>> 2 + 3 5 >>> 2 + 3 5 >>> 7 - 5 2 >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 >>> 14//3 4 >>> 14%3 >>> 2**3 >>> abs(-3.2) 3.2 >>> min(23,41,15,24) 15 >>> max(23,41,15,24) 41 >>> 2 + 3 5 >>> 7 - 5 2 >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 >>> 14//3 4 >>> 14%3 >>> 2 + 3 5 >>> 7 - 5 2 >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 >>> 14//3 4 >>> 14%3 >>> 2**3 >>> abs(-3.2) 3.2 >>> min(23,41,15,24) 15 >>> 2 + 3 5 >>> 7 - 5 2 >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 >>> 14//3 4 >>> 14%3 >>> 2**3 >>> abs(-3.2) 3.2 14//3 is the quotient when 14 is divided by 3 and 14%3 is the remainder 2**3 is 2 to the 3rd power abs(), min(), and max() are functions abs() takes a number as input and returns its absolute value min() (resp., max()) take an arbitrary number of inputs and return the “smallest” (resp., “largest”) among them

Boolean expressions In addition to algebraic expressions, Introduction to Computing Using Python In addition to algebraic expressions, Python can evaluate Boolean expressions Boolean expressions evaluate to True or False Boolean expressions often involve comparison operators <, >, ==, !=, <=, and >= >>> 2 < 3 True >>> 2 > 3 False >>> 2 == 3 >>> 2 != 3 >>> 2 <= 3 >>> 2 >= 3 >>> 2+4 == 2*(9/3) In a an expression containing algebraic and comparison operators: Algebraic operators are evaluated first Comparison operators are evaluated next

Boolean operators In addition to algebraic expressions, Introduction to Computing Using Python >>> 2<3 and 3<4 True >>> 4==5 and 3<4 False >>> False and True >>> True and True >>> 4==5 or 3<4 >>> False or True >>> False or False >>> not(3<4) >>> not(True) >>> not(False) >>> 4+1==5 or 4-1<4 In addition to algebraic expressions, Python can evaluate Boolean expressions Boolean expressions evaluate to True or False Boolean expressions may include Boolean operators and, or, and not In a an expression containing algebraic, comparison, and Boolean operators: Algebraic operators are evaluated first Comparison operators are evaluated next Boolean operators are evaluated last

Exercise Introduction to Computing Using Python Translate the following into Python algebraic or Boolean expressions and then evaluate them: The difference between Annie’s age (25) and Ellie’s (21) The total of $14.99, $27.95, and $19.83 The area of a rectangle of length 20 and width 15 2 to the 10th power The minimum of 3, 1, 8, -2, 5, -3, and 0 3 equals 4-2 The value of 17//5 is 3 The value of 17%5 is 3 284 is even 284 is even and 284 is divisible by 3 284 is even or 284 is divisible by 3 >>> 25 - 21 4 >>> 14.99 + 27.95 + 19.83 62.769999999999996 >>> 20*15 300 >>> 2**10 1024 >>> min(3, 1, 8, -2, 5, -3, 0) -3 >>> 3 == 4-2 False >>> 17//5 == 3 True >>> 17%5 == 3 >>> 284%2 == 0 >>> 284%2 == 0 and 284%3 == 0 >>> 284%2 == 0 or 284%3 == 0

Variables and assignments Introduction to Computing Using Python Just as in algebra, a value can be assigned to a variable, such as x When variable x appears inside an expression, it evaluates to its assigned value >>> x = 3 >>> x 3 >>> 4*x 16 >>> y Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> y NameError: name 'y' is not defined >>> y = 4*x >>> >>> x = 3 >>> x 3 >>> 4*x 16 >>> y Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> y NameError: name 'y' is not defined >>> x = 3 >>> x 3 >>> 4*x 16 >>> >>> x = 3 >>> >>> x = 4 >>> x 4 >>> 4*x 16 >>> y Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> y NameError: name 'y' is not defined >>> y = 4*x >>> y 16.0 A variable (name) does not exist until it is assigned The assignment statement has the format <expression> is evaluated first, and the resulting value is assigned to variable <variable> <variable> = <expression>

Naming rules (Variable) names can contain these characters: Introduction to Computing Using Python (Variable) names can contain these characters: a through z A through Z the underscore character _ digits 0 through 9 >>> My_x2 = 21 >>> My_x2 21 >>> 2x = 22 SyntaxError: invalid syntax >>> new_temp = 23 >>> newTemp = 23 >>> counter = 0 >>> temp = 1 >>> price = 2 >>> age = 3 >>> My_x2 = 21 >>> My_x2 21 >>> My_x2 = 21 >>> My_x2 21 >>> 2x = 22 SyntaxError: invalid syntax >>> new_temp = 23 >>> newTemp = 23 >>> >>> My_x2 = 21 >>> My_x2 21 >>> 2x = 22 SyntaxError: invalid syntax >>> Names cannot start with a digit though For a multiple-word name, use either the underscore as the delimiter or camelCase capitalization Short and meaningful names are ideal

Strings 'Hello, World!' "Hello, World!" Introduction to Computing Using Python >>> 'Hello, World!' 'Hello, World!' >>> s = 'rock' >>> t = 'climbing' >>> >>> 'Hello, World!' 'Hello, World!' >>> In addition to number and Boolean values, Python support string values 'Hello, World!' "Hello, World!" A string value is represented as a sequence of characters enclosed within quotes A string value can be assigned to a variable String values can be manipulated using string operators and functions

String operators To view all operators, use the help() tool Usage Introduction to Computing Using Python >>> 'Hello, World!' 'Hello, World!' >>> s = 'rock' >>> t = 'climbing' >>> s == 'rock' True >>> s != t >>> s < t False >>> s > t >>> s + t 'rockclimbing' >>> s + ' ' + t 'rock climbing' >>> 5 * s 'rockrockrockrockrock' >>> 30 * '_' '______________________________' >>> 'o' in s >>> 'o' in t >>> 'bi' in t >>> len(t) 8 Usage Explanation x in s x is a substring of s x not in s x is not a substring of s s + t Concatenation of s and t s * n, n * s Concatenation of n copies of s s[i] Character at index i of s len(s) (function) Length of string s To view all operators, use the help() tool >> help(str) Help on class str in module builtins: class str(object) | str(string[, encoding[, errors]]) -> str ...

Exercise Introduction to Computing Using Python Write Python expressions involving strings s1, s2, and s3 that correspond to: 'll' appears in s3 the blank space does not appear in s1 the concatenation of s1, s2, and s3 the blank space appears in the concatenation of s1, s2, and s3 the concatenation of 10 copies of s3 the total number of characters in the concatenation of s1, s2, and s3 >>> s1 'good' >>> s2 'bad' >>> s3 'silly' >>> 'll' in s3 True >>> ' ' not in s1 >>> s1 + s2 + s3 'goodbadsilly’ >>> ' ' in s1 + s2 + s3 False >>> 10*s3 'sillysillysillysillysillysillysillysillysillysilly' >>> len(s1+s2+s3) 12 >>> >>> s1 'good' >>> s2 'bad' >>> s3 'silly' >>>

Index and indexing operator Introduction to Computing Using Python The index of an item in a sequence is its position with respect to the first item The first item has index 0, The second has index 1, The index of an item in a sequence is its position with respect to the first item The first item has index 0, The second has index 1, The third has index 2, … The index of an item in a sequence is its position with respect to the first item The index of an item in a sequence is its position with respect to the first item The first item has index 0, The indexing operator [] takes a nonnegative index i and returns a string consisting of the single character at index i 'A p p l e' s = 1 2 3 4 s[0] = 'A' s[1] = 'p' >>> s = 'Apple' >>> s[0] 'A' >>> s[1] 'p' >>> s[4] 'e' s[2] = 'p' s[3] = 'l' s[4] = 'e'

Negative index 'A p p l e' 'e' 'l' 'A' Introduction to Computing Using Python A negative index is used to specify a position with respect to the “end” The last item has index -1, The second to last item has index -2, The third to last item has index -3, … -5 -4 -3 -2 -1 'A p p l e' s = 1 2 3 4 s[-1] = 'e' s[-2] = 'l' >>> s = 'Apple' >>> s[-1] 'e' >>> s[-2] 'l' >>> s[-5] 'A' s[-5] = 'A'

Exercise String s is defined to be 'abcdefgh' Introduction to Computing Using Python String s is defined to be 'abcdefgh' Write expressions using s and the indexing operator [] that return the following strings: 'a' 'c' 'h' 'f' >>> s = 'abcdefgh' >>> s[0] 'a' >>> s[2] 'c' >>> s[7] 'h' >>> s[-1] >>> s[-3] 'f' >>> >>> s = 'abcdefgh' >>>

Lists ['ant', 'bat', 'cod', 'dog', 'elk'] Introduction to Computing Using Python In addition to number, Boolean, and string values, Python supports lists ['ant', 'bat', 'cod', 'dog', 'elk'] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [0, 1, 'two', 'three', [4, 'five']] A comma-separated sequence of items enclosed within square brackets The items can be numbers, strings, and even other lists >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> lst = [0, 1, 'two', 'three', [4, 'five']] >>> nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> lst = [0, 1, 'two', 'three', [4, 'five']] >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk’] >>>

List operators and functions Introduction to Computing Using Python >>> lst = [1, 2, 3] >>> lstB = [0, 4] >>> 4 in lst False >>> 4 not in lst True >>> lst + lstB [1, 2, 3, 0, 4] >>> 2*lst [1, 2, 3, 1, 2, 3] >>> lst[0] 1 >>> lst[1] 2 >>> lst[-1] 3 >>> len(lst) >>> min(lst) >>> max(lst) >>> sum(lst) 6 >>> help(list ... Like strings, lists can be manipulated with operators and functions Usage Explanation x in lst x is an item of lst x not in lst x is not an item of lst lst + lstB Concatenation of lst and lstB lst*n, n*lst Concatenation of n copies of lst lst[i] Item at index i of lst len(lst) Number of items in lst min(lst) Minimum item in lst max(lst) Maximum item in lst sum(lst) Sum of items in lst

Lists are mutable, strings are not Introduction to Computing Using Python Lists can be modified; they are said to be mutable Lists can be modified pets = ['ant', 'bat', 'cow', 'dog', 'elk'] pets = ['ant', 'bat', 'cod', 'dog', 'elk'] Strings can’t be modified; they are said to be immutable Strings can’t be modified pet = 'cod' >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets[2] = 'cow' >>> pets ['ant', 'bat', 'cow', 'dog', 'elk'] >>> pet = 'cod' >>> pet[2] = 'w' Traceback (most recent call last): File "<pyshell#155>", line 1, in <module> pet[2] = 'w' TypeError: 'str' object does not support item assignment >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets[2] = 'cow' >>> pets ['ant', 'bat', 'cow', 'dog', 'elk'] >>> pet = 'cod' >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets[2] = 'cow' >>> pets ['ant', 'bat', 'cow', 'dog', 'elk'] >>> The elements can be numbers, strings, and even other lists >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk’] >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> lst = [0, 1, 'two', 'three', [4, 'five']] >>>

Lists methods There are also functions that are called on a list; Introduction to Computing Using Python len()and sum() are examples of functions that can be called with a list input argument; they can also be called on other type of input argument(s) There are also functions that are called on a list; such functions are called list methods >>> lst = [1, 2, 3] >>> len(lst) 3 >>> sum(lst) 6 >>> lst.append(7) >>> lst [1, 2, 3, 7] >>> >>> lst = [1, 2, 3] >>> len(lst) 3 >>> sum(lst) 6 >>> ` lst.append(7) variable lst refers to a list object input argument 7 list method append() Method append() can’t be called independently; it must be called on some list object

Lists methods Methods append(), remove(), reverse(), Introduction to Computing Using Python >>> lst = [1, 2, 3] >>> lst.append(7) >>> lst.append(3) >>> lst [1, 2, 3, 7, 3] >>> lst.count(3) 2 >>> lst.remove(2) [1, 3, 7, 3] >>> lst.reverse() [3, 7, 3, 1] >>> lst.index(3) >>> lst.sort() [1, 3, 3, 7] >>> lst.remove(3) [1, 3, 7] >>> lst.pop() 7 [1, 3] Usage Explanation lst.append(item) adds item to the end of lst lst.count(item) returns the number of times item occurs in lst lst.index(item) Returns index of (first occurrence of) item in lst lst.pop() Removes and returns the last item in lst lst.remove(item) Removes (the first occurrence of) item from lst lst.reverse(item) Reverses the order of items in lst lst.sort(item) Sorts the items of lst in increasing order Methods append(), remove(), reverse(), and sort() do not return any value; they, along with method pop(), modify list lst

Exercise Introduction to Computing Using Python List lst is a list of prices for a pair of boots at different online retailers You found another retailer selling the boots for $160.00; add this price to list lst Compute the number of retailers selling the boots for $160.00 Find the minimum price in lst Using c), find the index of the minimum price in list lst Using c) remove the minimum price from list lst Sort list lst in increasing order >>> lst = [159.99, 160.00, 205.95, 128.83, 175.49] >>> lst.append(160.00) >>> lst.count(160.00) 2 >>> min(lst) 128.83 >>> lst.index(128.83) 3 >>> lst.remove(128.83) >>> lst [159.99, 160.0, 205.95, 175.49, 160.0] >>> lst.sort() [159.99, 160.0, 160.0, 175.49, 205.95] >>>

Objects and classes 3 3.0 'three' [1, 2, 3] Introduction to Computing Using Python >>> a = 3 >>> b = 3.0 >>> c = 'three' >>> d = [1, 2, 3] >>> type(a) <class 'int'> >>> type(b) <class 'float'> >>> type(c) <class 'str'> >>> type(d) <class 'list'> >>> a = [] >>> a = 3 >>> b = 3.0 >>> >>> a = 3 >>> b = 3.0 >>> c = 'three' >>> d = [1, 2, 3] >>> >>> a = 3 >>> b = 3.0 >>> c = 'three' >>> >>> a = 3 >>> b = 3.0 >>> c = 'three' >>> d = [1, 2, 3] >>> type(a) <class 'int'> >>> type(b) <class 'float'> >>> type(c) <class 'str'> >>> type(d) <class 'list'> >>> >>> a = 3 >>> In Python, every value, whether a simple integer value like 3 or a more complex value, such as the list ['hello', 4,  5]  is stored in memory as an object. Every object has a value and a type; It is the object that has a type, not the variable! int float str list 3 3.0 'three' [1, 2, 3] An object’s type determines what values it can have and how it can be manipulated Terminology: object X is of type int = object X belongs to class int

Values of number types Introduction to Computing Using Python >>> 0 >>> 2**1024 179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216 >>> 0.0 0.0 >>> 2.0**1024 Traceback (most recent call last): File "<pyshell#38>", line 1, in <module> 2.0**1024 OverflowError: (34, 'Result too large') >>> 2.0**(-1075) >>> 0 >>> 2**1024 179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216 >>> An object’s type determines what values it can have and how it can be manipulated An object of type int can have, essentially, any integer number value The value of an object of type float is represented in memory using 64 bits i.e., 64 zeros and ones This means that only 264 real number values can be represented with a float object; all other real number values are just approximated

Operators for number types Introduction to Computing Using Python An object’s type determines what values it can have and how it can be manipulated Operator […] x[] ** +x, -x *, /, //, % +, - in, not in <,>,<=,>=,==,!= not x and or We already saw the operators that are used to manipulate number types algebraic operators +, -, *, /, //, %, **, abs() comparison operators >, <, ==, !=, <=, >=, … higher precedence Parentheses and precedence rules determine the order in which operators are evaluated in an expression lower precedence

Object constructors Introduction to Computing Using Python >>> x = 3 >>> x 3 >>> x = int(3) >>> x = int() >>> y = float() >>> y 0.0 >>> >>> x = 3 >>> x 3 >>> x = int(3) >>> x = int() >>> y = float() >>> y 0.0 >>> s = str() >>> s '' >>> lst = list() >>> lst [] >>> >>> x = 3 >>> x 3 >>> >>> x = 3 >>> x 3 >>> x = int(3) >>> x = int() >>> y = float() >>> y 0.0 >>> s = str() >>> s '' >>> >>> x = 3 >>> x 3 >>> x = int(3) >>> x = int() >>> An assignment statement can be used to create an integer object with value 3 The type of the object is implicitly defined The object can also be created by explicitly specifying the object type using a constructor function int(): integer constructor (default value: 0) float(): Float constructor (default value: 0.0) str(): string constructor (default value: empty string ’’) list(): list constructor (default value: empty list [])

Type conversion Implicit type conversion Explicit type conversion Introduction to Computing Using Python bool int float Implicit type conversion When evaluating an expression that contains operands of different type, operands must first be converted to the same type Operands are converted to the type that “contains the others” Explicit type conversion Constructors can be used to explicitly convert types >>> 2 + 3.0 5.0 >>> True + 0 1 >>> float('45.6') 45.6 >>> float(2**24) 16777216.0 >>> float(2**1024) Traceback (most recent call last): File "<pyshell#57>", line 1, in <module> float(2**1024) OverflowError: long int too large to convert to float >>> str(345) '345' >>> str(34.5) '34.5' >>> >>> int(2.1) 2 >>> int('456') 456 >>> int('45.6') Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> int('45.6') ValueError: invalid literal for int() with base 10: '45.6’ int() creates an int object from a float object, by removing decimal part from a str object, if it represents an integer float() creates a float object from an int object, if it is not too big from a string, if it represents a number str() creates a str object the string representation of the object value

Class and class methods Introduction to Computing Using Python Once again: In Python, every value is stored in memory as an object, every object belongs to a class (i.e., has a type), and the object’s class determines what operations can be performed on it We saw the operations that can be performed on classes int and float >>> pets = ['goldfish', 'cat', 'dog'] >>> pets.append('guinea pig') >>> pets.append('dog') >>> pets ['goldfish', 'cat', 'dog', 'guinea pig', 'dog'] >>> pets.count('dog') 2 >>> pets.remove('dog') ['goldfish', 'cat', 'guinea pig', 'dog'] >>> pets.reverse() ['dog', 'guinea pig', 'cat', 'goldfish'] >>> fish = ['goldfish'] >>> myPets = ['cat', 'dog'] >>> fish * 3 ['goldfish', 'goldfish', 'goldfish'] >>> pets = fish + myPets >>> pets ['goldfish', 'cat', 'dog'] >>> 'frog' in pets False >>> pets[-1] 'dog' >>> The list class supports: operators such as +, *, in, [], etc. methods such as append(), count(), remove(), reverse(), etc.

Python Standard Library Introduction to Computing Using Python The core Python programming language comes with functions such as max() and sum() and classes such as int, str, and list. Many more functions and classes are defined in the Python Standard Library to support Network programming Web application programming Graphical user interface (GUI) development Database programming Mathematical functions Pseudorandom number generators Media processing, etc. The Python Standard Library functions and classes are organized into components called modules.

Standard Library module math Introduction to Computing Using Python The core Python language does not have a square root function The square root function sqrt() is defined in the Standard Library module math >>> import math >>> math.sqrt(4) 2.0 >>> sqrt(4) Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> sqrt(4) NameError: name 'sqrt' is not defined >>> help(math) Help on module math: … >>> math.cos(0) 1.0 >>> math.log(8) 2.0794415416798357 >>> math.log(8, 2) 3.0 >>> math.pi 3.141592653589793 >>> import math >>> >>> import math >>> math.sqrt(4) 2.0 >>> sqrt(4) Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> sqrt(4) NameError: name 'sqrt' is not defined >>> A module must be explicitly imported into the execution environment: import <module> The prefix math. must be present when using function sqrt() The math module is a library of mathematical functions and constants

Exercise Write a Python expression that assigns to variable c Introduction to Computing Using Python Write a Python expression that assigns to variable c The length of the hypotenuse in a right triangle whose other two sides have lengths 3 and 4 The value of the Boolean expression that evaluates whether the length of the above hypotenuse is 5 The area of a disk of radius 10 The value of the Boolean expression that checks whether a point with coordinates (5, 5) is inside a circle with center (0,0) and radius 7. >>> c = math.sqrt(3**2+4**2) >>> c 5.0 >>> c = (math.sqrt(3**2+4**2) == 5) True >>> c = math.pi*10**2 314.1592653589793 >>> c = (2*5**2 < 7**2) False