Download presentation
Presentation is loading. Please wait.
Published byYuliana Indradjaja Modified over 6 years ago
1
Intro to Programming using Python Lecture #2
Yosef Mendelsohn With many thanks to Dolores Kalayta for the original version of these notes.
2
Strings In addition to number and Boolean values, Python supports string values ( i.e. non-numeric values)
3
Strings A string value is represented as a sequence of characters enclosed within quotes: 'Hello, how are you?' A string value can be assigned to a variable. greeting = 'Hello, how are you?' word1 = "rock" word2 = "climbing" String values can be manipulated using string operators and functions word1 + word2 "rockclimbing" word1 + ' ' + word2 rock climbing + is the string concatenation operator String and generally enclosed in single quotes, but double quotes are acceptable. Double quotes are necessary if you have a single quote within the string For example print (“That’s all folks”)
4
Strings: indexing and slicing
greeting = 'Hello, how are you?' word1 = "rock" word2 = "climbing" word1[0] 'r' --> this is known as 'indexing' word1[0:2] 'ro' --> this is known as 'slicing' Note that the second number is exclusive word1[-1] 'k' + is the string concatenation operator String and generally enclosed in single quotes, but double quotes are acceptable. Double quotes are necessary if you have a single quote within the string For example print (“That’s all folks”)
5
Concatenation Adding two or more strings together to make a longer string is known as concatenation This is used a lot in programming Only string data can be concatenated Example: >>> age = 16 >>> print('Adam is ' + age + ' years of age') TypeError: must be str, not int Key point: Since the data type of 'age' is int, we get an error. Recall that we can only concatenate strings. >>> age = 16 >>> print ('Adam is ' + age + ' years of age') Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> print ('Adam is ' + age + ' years of age') TypeError: must be str, not int >>> print ('Adam is ' + str(age) + ' years of age') Ad Adam is 16 years of age There are many, many more operations and functions for strings,
6
Explicit conversion of int to string
One very common solution when dealing with conflicting data types, is to attempt to convert one data type to another. The works for some (but only some!) values. Converting "10" to 10 --> sure! Converting "ten" to 10 --> not possible! To change an int data type to a string use str() >>> age = > 'age' holds an integer >>> age = str(age) --> 'age' now holds an string! >>> age = 16 >>> print ('Adam is ' + age + ' years of age') Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> print ('Adam is ' + age + ' years of age') TypeError: must be str, not int >>> print ('Adam is ' + str(age) + ' years of age') Ad Adam is 16 years of age There are many, many more operations and functions for strings,
7
Explicit conversion of int to string
One very common solution when dealing with conflicting data types, is to attempt to convert one data type to another. The works for some (but only some!) values. Converting "10" to 10 --> sure! Converting "ten" to 10 --> not possible! To change an int data type to a string use str() >>> age = 16 >>> print('Adam is ' + age + ' years of age') TypeError: must be str, not int >>> print ('Adam is ' + str(age) + ' years of age') Adam is 16 years of age >>> age = 16 >>> print ('Adam is ' + age + ' years of age') Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> print ('Adam is ' + age + ' years of age') TypeError: must be str, not int >>> print ('Adam is ' + str(age) + ' years of age') Ad Adam is 16 years of age There are many, many more operations and functions for strings,
8
Casting Casting refers to converting between data types. It is very important in programming. As mentioned a few moments ago, sometimes casting is possible (e.g. "10" to 10), and sometimes it isn't (e.g. "ten" to 10). Numeric types / constructors Converting something to an integer: int(value) x = "322" y = int(x) --> y holds the integer 322 Converting a value to a float: float(value) x = "3.14" --> x holds the string "3.14" y = float(x) --> y holds the float 3.14 x = 3 --> x holds the integer 3 y = float(x) --> y holds the float 3.0
9
Checking the data type type()
Because data types are so important, you might want to keep in mind the function type() which will tell you the data type of an object. x = "322" y = int(x) --> y holds the integer 322 type(y) --> will output 'int' x = 3 --> x holds the integer 3 y = float(x) --> y holds the float 3.0 type(x) --> outputs 'int' type(y) --> outputs 'float'
10
Boolean expressions and operators
11
Boolean Expressions How does Python interpret an expression like the following? >>> 5 <= 18 Python can evaluate Boolean expressions, i.e. expression whose value is TRUE or FALSE Python interprets 5 <= 18 as a statement whose truth is being questioned True
12
bool Boolean data types, i.e. True or False, are called bool in Python
Boolean expressions often contain COMPARISON operators Operator Meaning < Less than > Greater than == Equal to (TWO equal signs) != Not equal to <= Less than or equal to >= Greater than or equal to See notes: Examples in IDLE 3 < 2 False 1 = 1 Syntax: can’t assign to literal # = is the assignment operator # == is the Equal operator 1 == 1 True 1 != 1 == 12 n = 17 n/2 # this evaluates immediately to 8.5 8.5 >>> n// 2 8 >>> n == (n//2) * 2 do you know what is the value of n? Is this T or F? Answer is FALSE
13
Boolean operators and, or, not and, or are binary operator
You have seen (or will see) these in discrete math classes and, or are binary operator expression1 and expression2 expression1 or expression2 not is a unary operator ie: applies to a single value not an expression Boolean expressions can be combined into fairly complex statements using various combinations of boolean operators
14
Boolean operators expression1 and expression2
True if both expressions are true False if any of the two expressions is false expression1 or expression2 True if any of the two expressions are false False if both expression are false not expression True if the expression is false False if the expression is true
15
Operator Precedence ** * / // % + - <, >, ==, <=, >=, !=
Arithmetic then comparison then boolean ** * / // % + - <, >, ==, <=, >=, != not and or Extra In IDLE >>> 3 < 8 and 4 >= 12 False >>> 3 < 8 or 7 >=15 True >>> 3 < 8 and 7 >=15 False >>> not (3 < 2) False >>> 5 % 2 == 2 or 24 // 7 == 3 True
16
Try in IDLE 2 < 3 and 3 < 4 4 == 5 and 3 < 4 False and True
True and True not(3 < 4) not(True) not(False) 4 + 1 == 5 or 4 – 1 < 4 4 + 1 == 5 and < 4
17
First interactive Python program
Allowing the user to interact with our programs
18
Variables: assignment statements
Formula for calculating compound interest A is the value after t periods P is the principal amount (initial investment) r is the annual nominal interest rate ( not reflecting the compounding) n is the number of times the interest is compounded per year t is the number of years the money is invested Recall our compound interest program Given: n = 12 months, t = 10 years, p = 5000, r = 1/100
19
compound_interest_v1.py RESULTS:
======= RESTART: C:\Users\ymendels\Dropbox\401\compound_interest_v1.py ======= The investment balance is The interest amount is >>>
20
Problem Calculate the new balance and the interest earned based on the values specified by the user Need to get from the user: Initial investment, P Annual interest rate, r (expressed as float) Number of times the interest is compounded per year, n The number of years the money is invested, t Return to user New balance Amount of interest earned There are various ways of getting input from the user. We will start with input() and eval()
21
input() function / Casting
To have the user input data: input('Enter name: ') # input() function returns a string value To save the data input, assign it to a variable firstName = input('Enter name: ') x = input('Enter number: ') Important: Note that input() function returns a string User types 4 – this is saved as the string '4' However, we can not do mathematical calculations on text (string) data! To convert a string to a number use the eval() function num = int(num) converts to an int num = float(num) converts to a float This is known as “casting”. See compound_interest_interactive_casting.py Do in IDLE #See compound_interest_interactive.py # ask user for input values P = eval(input('Enter initial investment: ')) r = eval(input('Enter annual interest rate: ')) n = eval(input('Enter number times interest is compounded per year: ')) t = eval(input('Enter the number of years: ')) A = P * ( 1 + (r/n)) ** (n * t) balance = round(A, 2) interest = round((balance - P),2) print ('The investment balance is ', balance) print ('The interest amount is ', interest) Now – what if I got a 5% interest rate Balance is Interest is input() and eval() are built-in functions
22
Practice Problem You scored x/100, y/100, z/100 on homework
What is your total homework percentage? Modify the previous program to get the input from the user. Calculate the area of a circle; let the user specify the radius of the circle. See notes: Try this practice problem asking the user to enter their 3 scores. Assume that all the homeworks are worth 100 points each. ( x + y + z)/300 (x + y + z) - Min (x, y z) /200 leave this for a homework exercise: The instructor drops the lowest homework score; what is your homework percentage? Using variable for radius of a circle, calculate the area of a circle – saved as practice_area_circle # example using math library # Area = pi * radius ** 2 import math radius = eval(input('Input circle radius: ')) area = math.pi * (radius ** 2) print ('Area of the circle is ',area)
23
Lists Another Python object Another type of object Float Integer
String Boolean Now we look at Lists
24
List A sequence of objects
Numbers Strings Combination of numbers and string Other lists Represented as a comma-separated sequence of objects enclosed within square-brackets [ ] Example: List of numbers [1,4,30, 16] List of strings on next slide
25
Lists Lists are created by placing a series of values (or variables) inside square brackets Each item in the list is separate form the following item by a comma Lists are ordered names = ['Betty', 'Veronica', 'Jughead'] exam_scores = [87, 96, 72, 48, 93] letter_grades = ['A', 'C', 'A', 'D'] random_stuff = ['Hello there!', 3.14, names] Note some things about the last list, random_stuff: It has different data types in it. This is fine, but not very common. One of the items in the list is another list! Also perfectly fine. More common than lists of varying data types, but still not as common. Most lists – though by no means all – tend to contain a single data type.
26
Difference between strings and lists
The built-in Python function: type() is a good one to know. It comes in handy surprisingly often when debugging. Notation: String – sequence of characters enclosed in quotes alphaString = ‘abcdefg’ List – is a sequence of objects alphaList – [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’] Strings are immutable objects Lists are mutable objects – I can change the items in an existing list, but, I cannot change the characters in an existing string
27
Operators Strings and Lists
28
+ operator Concatenation of lists >>> s = ['he']
Concatenation of strings >>> 'he' + 'llo' 'hello' >>> s = 'Hello' >>> t = 'World' >>> s + t 'HelloWorld' How do you get the space between Hello and World? Concatenation of lists >>> s = ['he'] >>> t = ['llo'] >>> s + t ['he', 'llo'] >>> s = [1, 2, 3] >>> t = [4, 5, 6] [1, 2, 3, 4, 5, 6] Joins the 2 strings or joins 2 lists Can only join a list to a list and a string to a string >>> s = ‘Hello’ >>> t = ‘World’ Get space >>> s + ‘ ‘ + t #result of >>> ‘3’ + ‘5” # is not 8 35 List1 + List2 = List >>> '3' + '5'
29
Indexing Operator [] Individual characters of a string and items in a list can be accessed using the indexing operator [ ] s =['Apple','Orange', 'Peach'] s = ' A p p l e ' 0 1 2 >>> s[0] 'A' >>> s[4] 'e' >>> s[-1] What is returned from s[1:4]? s[1:]? s[:-1]? s[::-1]? 3 4 >>> s[0] 'Apple' >>> s[2] 'Peach' >>> s[-1] >>> 'Peach' 1 2 S[1:4] returns ‘ppl’ start at index 1 and go up to but do not include index 4 = substring or slicing S[:5] returns ‘Apple’ all characters before index 5 5 is the length of the string S[:len(5)] returns ‘Apple’ S[1:] returns ‘pple starts at index 1 to the end S[:-1] returns ‘Appl’ starts at index 0 up to but not containing index[-1] S[::-1] returns ‘elppA’ start at index -1 and returns the rest of the string – reverse order List question S[1][4] returns g in Orange item at index 1 and character at index [4] s[: 2] returns [‘Apple’, ‘Orange’] starts at index 0 and does not include item at index 2 S[1:] returns [‘Orange’, ‘Peach’] includes items beginning at 1 and to the end of the list What is returned from s[1][4]?
30
String and List Operators
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 String Operators >>> help(str) 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 S = ‘Orange’ ‘r’ in S ‘a’ in S ‘b’ in S ‘b’ not in S S * 3 lst = [‘a’, ‘b’, ‘c’] ‘a’ in lst ‘x’ not in lst Lst * 3 [‘a’, ‘b’, ‘c’, ‘a’, ‘b’, ‘c’, ‘a’, ‘b’, ‘c’] List Operators >>> help(list)
31
Commonly used String and List functions
Usage Explanation len(s) (function) Length of string s Usage Explanation 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 S = ‘Orange’ Len(s) returns 6 S= [‘Apple’, ‘Orange’, ‘Peach’] Len(s) return 3 # items Max(s) returns Peach – the last item in the list Min(s) returns Apple – the first item in the list Sum(s) unsupported operand types(s) – cannot sum strings N = [3,2,4,1] list of integers Sum(n) return 10 Min(n) returns 1 Max (n) returns 4 You can use min and max with a string, but not sum – get unsupported error Method is the object-oriented word for function. That’s pretty much all there is to it (i.e. no real difference) Functions are defined outside of a classes, while methods are defined inside or part of classes.
32
Count Method Method lst.count(item)
Returns the number of occurrences of item in list lst s.count(target) The number of occurrences of substring target in string s >>> ages = [25, 21, 35, 34, 24, 23, 24, 21,21,35] Ages.count(25) returns 1 Ages.count(21) returns 3 Rhyme = ‘Mary has a little lamb its fleece was white as snow. Everywhere that Mary went the lamb was sure to go’ Rhyme.count(‘the’) returns 1 Rhyme.count(‘Mary’) return 2 Rhyme.count(‘was) returns 2 Num = [1,2,3,4,5,1,2,3,4,4,] Num.count(1) returns 2 Num.count(4) returns 3 S = ‘abcabcabcde’ s.count(‘ab’) returns 3
33
Variables and assignments
Mutable and immutable types We need to understand how values are created in memory (RAM) – Python’s memory management
34
How variables are stored in memory
A value will have only one copy in memory and all the variables having this value will refer to this memory location. Example: Suppose you have the variables x, y and z having a value 10. This does not mean that there will be 3 copies of 10s in memory. In fact, there will be only one 10 and all three variables x,y, z will point (reference) this value. Once a variable is updated, say x = x + 1 a new value will be allocated in memory and x will point(reference) this value. A useful function when trying to understand this concept is: id() The function returns a form of the address where the value is stored in memory. >>> a = 10 >>> b = 10 >>> c = 10 >>> id(a), id(b), id(c) ( , , ) >>> a += 1 >>> id(a) id() will return an objects memory address (object’s identity). As you have noticed, when you assign the same integer value to the Variables, we see the same ids.
35
Mutable vs Immutable List Contents of a list can be changed - mutable
>>> s = ['Apple', 'Orange', 'Peach'] >>> print (s) ['Apple', 'Orange', 'Peach'] >>> t = s >>> print (t) >>> s[1] = 'Pear' >>> print(s) ['Apple', 'Pear', 'Peach'] String Contents of a string cannot be changed - immutable >>> s = 'Apple , Orange, Peach' >>> print (s) Apple, Orange, Peach >>> s[1] = 'Pear' TypeError: 'str' object does not support item assignment >> > s[1] = 'P' What do we need to do to replace the first p in Apple with an uppercase P? Draw the object diagram >>> s = [‘Apple’, ‘Orange’, ‘Peach’] >>> print(s) t = s >>> print (s) [‘Apple’, ‘Orange’, ‘Peach’] >>> print(t) STRING >>> s = ‘Apple, Orange, Peach’ To replace p with P >>> s= ‘APple, Orange, Peach’ >>>Print (s) APple, Orange, Peach >>>Print(t) Apple, Orange, Peach S = ‘APple, Orange, Peach’ T = ‘Apple, Orange, Peach’ Now have two lists in memory
36
Assignment 3 4.5 'hello' [1, 2, 3] >>> a = 3
>>> type(a) It is not the identifier (variable) that has a type. Rather it is the object assigned to that variable that has the type. <class ‘int’> >>> b = 4.5 >>> c = 'hello' >>> d = [1, 2, 3] a b c d If the object is mutable, replace value in the current object (list) If the object is immutable, create a new object for the variable (string) type(a) returns <class ‘int’> int is immutable Assignment statement creates the object in memory and binds the name (variable) to the object int float str list 3 4.5 'hello' [1, 2, 3] Object a is of type int = object a belongs to class int
37
Example – mutable object
b is a list – mutable At step 2 a and b refer to the same object At step 4 change number in index 2 to 4 b is now [1,2,4] a is now [1,2,4] Because a list is mutable you can replace one number with another. To variable pointing to the same mutable object changes the value for both variable objects >>> a >>> a = 10 >>> a >>> b
38
Example – immutable object
>>> y = x >>> y = 100 >>> x >>> y 23 is an integer and is immutable At step 2 x and y refer to the same object At step 3 for y to 100 – cannot make the change, need to create a new object x is now 23 y is now 100] Because a an integer is immutable, you can not change the object value. Python will create a new object for the new value.
39
Swapping: The Traditional Approach
>>> x = 3 >>> y=4 >>> temp = x >>> y = temp Objective: We want to swap the values of x and y i.e. assign the value of y to x, and assign the value of x to y Traditional approach required 5 steps In python: multiple assignment statement x,y = y, x Because a an integer is immutable, you can not change the object value. Python will create a new object for the new value.
40
Swapping: A Python Approach
>>> x=3 >>> y=4 >>> x,y = y,x Objective: We want to swap the values of x and y Python gives us a really nice shortcut: Traditional approach required 5 steps In python: multiple assignment statement x,y = y, x
41
Change the flow of control
Decision Structures Change the flow of control A Python program is a sequence of statements that are executed in succession; in order starting from the statement in line 1 and the next statement in succession. That is not what we usually experience when using an application on a computer. The IF statement can control which statements are executed based on some input.
42
Decisions if condition: Comparisons using relational operators
• ==, != • <, <= • >, >= Condition - comparison expression that evaluates to a Boolean value (True or False) Comparisons using boolean operators and or not Boolean variables Python: Comparisons using in operator x in s (x substring of s) x not in s( x substring of s) List x in lst (x object in list) x not in lst ( x object in list) What objects may be in a list? String Decisions are based on a condition evaluating to True or False You can compare numbers, strings , lists, Booleans. Do the following in IDLE If x < y and y < z uses relational operators and boolean operator – compound comparison X = 3, y = 9, z = 10 print (‘yes’) returns yes X = 3, y = 9, z = 6 print (‘yes’) returns empty words = [‘hello’, ‘the’, ‘their’, ‘world’, ‘bye’, ‘good’] S = ‘hello the their world bye good’ ‘the’ in words True ‘the’ in s s.count(‘the’) returns 2 Words.count(‘the’) returns 1 Objects in a list may be strings, numbers (int, float) Operand Operations A B A and B A or B Not A True False
43
<indented code block>
One-Way Decisions if <condition>: <indented code block> <non-indented statement> Condition described on previous slide block of statements when condition tests true must be indented. Examples 1,2,3,4 Indented code block is one or more python statements; may be another if statement
44
Two-Way Decisions if <condition>:
<indented code block 1> else: <indented code block 2> <non-indented statement> if <condition 1>: <indented code block 1> elif <condition 2>: <indented code block 2> <non-indented statement> Examples 5 and 6
45
Series of IFs if <condition_1>: <indented code block 1>
<non-indented statement> Month = eval(input(‘enter month number: ‘) If month == 1: print (“January”) If month ==2: print(“February”) If month Print (“month is an invalid number”)
46
Nested IFs if <condition_1>: if <condition_A>:
<indented code block A> else: <indented code block not A> <indented code block 1> <non-indented statement> temperature = eval(input(‘temperature: ‘) If temperature > = 50: if temperature >= 80: print (‘Good day for swimming’) else: print (“Good day for golfing’) Else: (‘Good day to play tennis’)
47
Practice Examples 1 - 4
48
Algorithms IMPORTANT!!!!! Watch out for the "yeah yeahs"…
49
Example 1 Problem: If age is greater than 62, print ‘You are eligible for social security benefits Describe the algorithm Get a number from the user Determine if number is > 62 If number < Print message Key Knowledge: Do a numeric comparison input() function returns a string; need to convert to integer def example1(): ' test for social security eligibility ' age = eval(input('Enter your age ')) # do first without eval if age > 62: print('You are eligible for social security benefits')
50
Example 2 Problem: If the value of variable name is in the list [‘Mozart’, ‘Puccini’, ‘Rossini’, ‘Wagner’, ‘Verdi’, ‘Strauss’], print ‘One of the 6 most popular opera composers’ Describe the algorithm Define a list of composer names Get a composer name (string) from the user Determine if composer name is in the list Print the message Key Knowledge: Input from user is stored in the variable name def example2(): ' opera composers' composers = ['Mozart', 'Puccini', 'Rossini', 'Wagner', 'Verdi', 'Strauss'] name = input('Enter your favorite opera composer ') if name in composers: # list operator - in operator print(name, 'is one of the 6 most popular opera composers')
51
Example 3 Problem: If a substring of characters appears more than 2 times in the string values associated with the variable report, then print ‘Yes’ Define the algorithm Create and store a sequence of meaningful characters Get sequence of characters from the user i.e. substring Determine number of times substring occurs in the sequence If number of occurrences is > Print the message Key knowledge: Store sequence of meaningful characters as a string in the variable report String type has a count method def example3(): ' test for substring ' report = 'the rabbit jumped over the fence and there is no stopping her. \nif she does it again, then we will have to bring her into the barn.' print(report) letters = input('Enter string to search for ') ct = report.count(letters) #if report.count(letters) > 2: #print('Yes', letters, 'occurs ' + str(report.count(letters)) + ' times') if ct > 2: print('Yes', letters, 'occurs ' + str(ct) + ' times')
52
Example 4 Problem: if at least one of the Boolean variables north, south, east, west is True, print ‘I can escape’ Describe the algorithm Initialize Boolean variables to True or False Determine Boolean operator that returns True if at least one value in the Boolean variables is True If True Print the message Key knowledge: Boolean operator that returns True if at least one of the Boolean variables is True in ‘or’. Review truth tables. Test case 1: all variables are False Test case 2: all variables are True Test case 3: two variable are False Test case 4: three variables are False Use: def example4(): north = False south = False east = False west = False If north or south or east or west: print(‘I can escape’) def example4a(): # output directions that you can escape from if there is time. north = False south = True east = False west = True if north == True: print ('I can escape north') else: print ('I cannot escape north') if south == True: print ('I can escape south') print('I cannot escape south') if east == True: print ('I can escape east') print ('I cannot escape east') if west == True: print ('I can escape west') print ('I cannot escape west')
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.