CSc 120 Introduction to Computer Programing II Adapted from slides by

Slides:



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

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.
Adapted from John Zelle’s Book Slides
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
An Introduction to Python – Part II Dr. Nancy Warter-Perez.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Introduction to Computing Using Python Python  Python is an interactive language.  Java or C++: compile, run  Also, a main function or method  Python:
Introduction to Python
Programming for Linguists An Introduction to Python 24/11/2011.
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
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.
Programming in Python Part III Dr. Fatma Cemile Serçe Atılım University
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
Python Conditionals chapter 5
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
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.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Variables, Types, Expressions Intro2CS – week 1b 1.
Python Strings. String  A String is a sequence of characters  Access characters one at a time with a bracket operator and an offset index >>> fruit.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
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.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Strings … operators Up to now, strings were limited to input and output and rarely used as a variable. A string is a sequence of characters or a sequence.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
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.
Mr. Crone.  Use print() to print to the terminal window  print() is equivalent to println() in Java Example) print(“Hello1”) print(“Hello2”) # Prints:
String and Lists Dr. José M. Reyes Álamo.
CSc 120 Introduction to Computer Programing II Adapted from slides by
Chapter 6 JavaScript: Introduction to Scripting
Catapult Python Programming Wednesday Morning session
Introduction to Python
Computer Programming Fundamentals
COMPSCI 107 Computer Science Fundamentals
CS 100: Roadmap to Computing
Python: Control Structures
CSc 120 Introduction to Computer Programing II
CS-104 Final Exam Review Victor Norman.
Multiple variables can be created in one declaration
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
CSc 110, Autumn 2017 Lecture 5: The for Loop and user input
While Loops in Python.
CSc 110, Spring 2017 Lecture 8: input; if/else
Advanced Programming Behnam Hatami Fall 2017.
Introduction to Python
And now for something completely different . . .
Chapter 2 - Introduction to C Programming
An Introduction to Python
Data types Numeric types Sequence types float int bool list str
T. Jumana Abu Shmais – AOU - Riyadh
CS 100: Roadmap to Computing
String and Lists Dr. José M. Reyes Álamo.
CSc 110, Spring 2018 Lecture 5: The for Loop and user input
Margaret Derrington KCL Easter 2014
Chapter 2 - Introduction to C Programming
Rocky K. C. Chang September 18, 2018 (Based on Zelle and Dierbach)
CSc 110, Spring 2018 Lecture 5: Loop Figures and Constants
Basic String Operations
CHAPTER 3: String And Numeric Data In Python
Chapter 2 - Introduction to C Programming
Chopin’s Nocturne.
Introduction to C Programming
CS 100: Roadmap to Computing
Control 9 / 25 / 19.
Presentation transcript:

CSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray 01-a: Python review

python review: variables, expressions, assignment

python basics >>> x = 4 >>> y = 5 >>> z = x + y >>> x 4 >>> y 5 >>> z 9 >>> y = z * 2 18 >>>

python basics >>> : python interpreter's prompt >>> x = 4 >>> y = 5 >>> z = x + y >>> x 4 >>> y 5 >>> z 9 >>> y = z * 2 18 >>> >>> : python interpreter's prompt black: user input (keyboard) blue: python interpreter output

python basics >>> x = 4 >>> y = 5 >>> z = x + y >>> x 4 >>> y 5 >>> z 9 >>> y = z * 2 18 >>> variables

python basics >>> x = 4 >>> y = 5 >>> z = x + y >>> x 4 >>> y 5 >>> z 9 >>> y = z * 2 18 >>> expressions

python basics >>> x = 4 >>> y = 5 >>> z = x + y >>> x 4 >>> y 5 >>> z 9 >>> y = z * 2 18 >>> assignment statements

python basics >>> x = 4 >>> y = 5 >>> z = x + y >>> x 4 >>> y 5 >>> z 9 >>> y = z * 2 18 >>> typing in an expression causes its value to be printed

python basics >>> x = 4 >>> y = 5 >>> z = x + y >>> x 4 >>> y 5 >>> z 9 >>> y = z * 2 18 >>> variables: names begin with letter or '_' don't have to be declared in advance type determined at runtime expressions: all the usual arithmetic operators

Multiple (aka parallel) assignment >>> >>> x, y, z = 11, 22, 33 >>> x 11 >>> y 22 >>> z 33 Assigns to multiple variables at the same time x1, x2, ..., xn = exp1, exp2, ..., expn Behavior: exp1, ..., expn evaluated (L-to- R) x1, ..., xn are assigned (L-to-R)

Comparison and Booleans >>> x, y, z = 11, 22, 33 >>> x 11 >>> y 22 >>> z 33 >>> x < y True >>> y == z False Comparision operations: <, >, ==, >=, <=, != Lower precedence than arithmetic operations. Yield boolean values: True False

EXERCISE >>> x = 3 >>> y = 4 >>> z = (2*x – 1 == y+1) >>> z ← what value is printed out for z?

EXERCISE >>> x = 3 >>> y = 4 >>> sum, diff, prod = x + y, x – y, x * y >>> prod+diff ← what is the value printed out?

python review: reading user input I: input()

Reading user input I: input() >>> x = input() 13579 >>> x '13579' >>> y = input('Type some input: ') Type some input: 23 >>> y '23' >>> z = input('More input: ') More input: 567 >>> z '567' >>>

Reading user input I: input() >>> x = input() 13579 >>> x '13579' >>> y = input('Type some input: ') Type some input: 23 >>> y '23' >>> z = input('More input: ') More input: 567 >>> z '567' >>> input statement: reads input from the keyboard returns the value read (a string)

Reading user input I: input() >>> x = input() 13579 >>> x '13579' >>> y = input('Type some input: ') Type some input: 23 >>> y '23' >>> z = input('More input: ') More input: 567 >>> z '567' >>> input statement: reads input from the keyboard returns the value read (a string) takes an optional argument if provided, serves as a prompt

Reading user input I: input() >>> >>> x = input() 12 >>> x '12' >>> y = x / 2 Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> y = x / 2 TypeError: unsupported operand type(s) for /: 'str' and 'int' the value read in is represented as a string string ≡ sequence of characters

Reading user input I: input() >>> >>> x = input() 12 >>> x '12' >>> y = x / 2 Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> y = x / 2 TypeError: unsupported operand type(s) for /: 'str' and 'int' the value read in is represented as a string string ≡ sequence of characters TypeError: indicate an error due to wrong type

Reading user input I: input() >>> >>> x = input() 12 >>> x '12' >>> y = x / 2 Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> y = x / 2 TypeError: unsupported operand type(s) for /: 'str' and 'int' >>> y = int (x) / 2 >>> y 6.0 the value read in is represented as a string string ≡ sequence of characters TypeError: indicates an error due to a wrong type Fix: explicit type conversion

python review: basics of strings

Basics of strings >>> x = "abcd" >>> y = 'efgh' >>> z = "efgh" >>>

Basics of strings >>> x = "abcd" >>> y = 'efgh' >>> z = "efgh" >>> either single-quotes (at both ends) or double-quotes (at both ends)

Basics of strings >>> text = input('Enter a string: ') Enter a string: abcdefghi >>> text 'abcdefghi' >>> text[0] 'a' >>> text[1] 'b' >>> text[27] Traceback (most recent call last): File "<pyshell#153>", line 1, in <module> text[27] IndexError: string index out of range >>> a string is a sequence (array) of characters we can index into a string to get the characters

Basics of strings >>> text = input('Enter a string: ') Enter a string: abcdefghi >>> text 'abcdefghi' >>> text[0] 'a' >>> text[1] 'b' >>> text[27] Traceback (most recent call last): File "<pyshell#153>", line 1, in <module> text[27] IndexError: string index out of range >>> a string is a sequence (array) of characters we can index into a string to get the characters indexing beyond the end of the string gives an IndexError error

Basics of strings >>> text = input('Enter a string: ') Enter a string: abcdefghi >>> text 'abcdefghi' >>> text[0] 'a' >>> text[1] 'b' >>> text[27] Traceback (most recent call last): File "<pyshell#153>", line 1, in <module> text[27] IndexError: string index out of range >>> a string is a sequence (array) of characters we can index into a string to get the characters each character is returned as a string of length 1 Intuitively, a character is a single letter, digit, punctuation mark, etc. E.g.: 'a' '5' '$'

Basics of strings >>> x = '0123456789' >>> '0' >>> x[1] '1' >>> x[2] '2' >>> x[-1] '9' >>> x[-2] '8' >>> x[-3] '7' x[ i ] : if i  0 (i.e., non-negative values): indexing is done from the beginning of the string the first letter has index 0 x[ i ] : if i < 0 (i.e., negative values): indexing is done from the end of the string the last letter has index -1

Basics of strings >>> x = '0123456789' >>> '0' >>> x[1] '1' >>> x[2] '2' >>> x[-1] '9' >>> x[-2] '8' >>> x[-3] '7' x[ i ] : if i  0 (i.e., non-negative values): indexing is done from the beginning of the string the first letter has index 0 x[ i ] : if i < 0 (i.e., negative values): indexing is done from the end of the string the last letter has index -1

EXERCISE >>> x = 'a' >>> x == x[0] what do you think will be printed here?

EXERCISE >>> x = 'apple' >>> x[2] == x[-2] what do you think will be printed here?

Basics of strings >>> >>> x = "5" >>> x '5' >>> x == 5 False Inside a computer, a character is represented as a number (its "ASCII value")

Basics of strings >>> >>> x = "5" >>> x '5' >>> x == 5 False Inside a computer, a character is represented as a number (its "ASCII value") the ASCII value of a digit is not the same as the digit itself: '5' ≠ 5

EXERCISE >>> x = 27 >>> y = 'x' >>> x == y What do you think will be printed here? Why?

Basics of strings >>> x = input() abcDE_fgHIJ_01234 >>> x 'abcDE_fgHIJ_01234' >>> >>> len(x) 17 >>> y = x.lower() >>> y 'abcde_fghij_01234' >>> x = y.upper() >> x 'ABCDE_FGHIJ_01234' len(x) : length of a string x

Basics of strings >>> x = input() abcDE_fgHIJ_01234 >>> x 'abcDE_fgHIJ_01234' >>> >>> len(x) 17 >>> y = x.lower() >>> y 'abcde_fghij_01234' >>> x = y.upper() >> x 'ABCDE_FGHIJ_01234' len(x) : length of a string x x.lower(), x.upper() : case conversion on the letters in a string x note that non-letter characters are not affected

Basics of strings >>> x = input() abcDE_fgHIJ_01234 >>> x 'abcDE_fgHIJ_01234' >>> >>> len(x) 17 >>> y = x.lower() >>> y 'abcde_fghij_01234' >>> x = y.upper() >> x 'ABCDE_FGHIJ_01234' len(x) : length of a string x x.lower(), x.upper() : case conversion on the letters in a string x note that non-letter characters are not affected Python supports a wide variety of string operations see www.tutorialspoint.com/python3/ python_strings.htm

Basics of strings >>> x = input() abcdefgh >>> x 'abcdefgh' >>> x[3] 'd' >>> >>> x[3] = 'z' Traceback (most recent call last): File "<pyshell#193>", line 1, in <module> x[3] = 'z' TypeError: 'str' object does not support item assignment

Basics of strings >>> x = input() abcdefgh >>> x 'abcdefgh' >>> x[3] 'd' >>> >>> x[3] = 'z' Traceback (most recent call last): File "<pyshell#193>", line 1, in <module> x[3] = 'z' TypeError: 'str' object does not support item assignment strings are immutable, i.e., cannot be modified or updated

Basics of strings >>> x = "abcd" >>> y = 'efgh' >>> z = 'efgh' >>> y == z True >>> x == y False >>> >>> w = x + y >>> w 'abcdefgh' >>> u = x * 5 >>> u 'abcdabcdabcdabcdabcd' + applied to strings does concatenation

Basics of strings >>> x = "abcd" >>> y = 'efgh' >>> z = 'efgh' >>> y == z True >>> x == y False >>> >>> w = x + y >>> w 'abcdefgh' >>> u = x * 5 >>> u 'abcdabcdabcdabcdabcd' + applied to strings does concatenation '*' applied to strings: does repeated concatenation if one argument is a number generates an error otherwise

Basics of strings >>> x = "abcd" >>> y = 'efgh' >>> z = 'efgh' >>> >>> w = x + y >>> w 'abcdefgh' >>> u = x * 5 >>> u 'abcdabcdabcdabcdabcd' >>> x - y Traceback (most recent call last): File "<pyshell#39>", line 1, in <module> x - y TypeError: unsupported operand type(s) for -: 'str' and 'str' + applied to strings does concatenation * applied to strings: does repeated concatenation if one argument is a number generates an error otherwise not all arithmetic operators carry over to strings

Basics of strings >>> x = "abcdefg" >>> y = 'hijk' >>> >>> x[3:6] 'def' >>> x[2:5] 'cde' >>> x[:2] 'ab' >>> x[4:] 'efg' >>> x[4:] + y[:2] 'efghi' slicing: produces substrings characters from 3 (included) to 6 (excluded) characters from 2 (included) to 5 (excluded) characters from the beginning to 2 (excluded) characters from 4 (included) to the end

EXERCISE >>> x = "whoa!" >>> y = x[2] * len(x) >>> z = x[3] + x[0] + y >>> z what is printed here? awooooo

EXERCISE >>> x = input() >>> y = x + x >>> int(x) == int(y) True what input value(s) will cause this to work as shown?

python review: conditionals

Conditional statements: if/elif/else >>> var1 = input() 100 >>> var2 = input() 200 >>> x1 = int(var1) >>> x2 = int(var2) >>> >>> if x1 > x2: print('x1 is bigger than x2') elif x1 == x2: print('x1 and x2 are equal') else: print('x1 is smaller than x2') x1 is smaller than x2

Conditional statements: if/elif/else >>> var1 = input() 100 >>> var2 = input() 200 >>> x1 = int(var1) >>> x2 = int(var2) >>> >>> if x1 > x2: print('x1 is bigger than x2') elif x1 == x2: print('x1 and x2 are equal') else: print('x1 is smaller than x2') x1 is smaller than x2 if-statement syntax: if BooleanExpr : stmt … elif BooleanExpr : elif … else: elifs are optional (use as needed)

Conditional statements: if/elif/else >>> var1 = input() 100 >>> var2 = input() 200 >>> x1 = int(var1) >>> x2 = int(var2) >>> >>> if x1 > x2: print('x1 is bigger than x2') elif x1 == x2: print('x1 and x2 are equal') else: print('x1 is smaller than x2') x1 is smaller than x2 if-statement syntax: if BooleanExpr : stmt … elif BooleanExpr : elif … else: elifs are optional (use as needed) else is optional

python review: while loops

Loops I: while >>> n = input('Enter a number: ') Enter a number: 5 >>> limit = int(n) >>> i = 0 >>> sum = 0 >>> while i <= limit: sum += i i += 1 >>> sum 15 >>>

Loops I: while >>> n = input('Enter a number: ') Enter a number: 5 >>> limit = int(n) >>> i = 0 >>> sum = 0 >>> while i <= limit: sum += i i += 1 >>> sum 15 >>> while-statement syntax: while BooleanExpr : stmt1 … stmtn stmt1 … stmtn are executed repeatedly as long as BooleanExpr is True

EXERCISE >>> text = "To be or not to be, that is the question." >>> c = "o" Write the code to count the number of times c occurs in text.

python review: lists (aka arrays)

Lists >>> x = [ 'item1', 'item2', 'item3', 'item4' ] >>> >>> x[0] 'item1' >>> x[2] 'item3' >>> len(x) 4 >>> x[2] = 'newitem3' >>> x ['item1', 'item2', 'newitem3', 'item4'] >>> x[1:] ['item2', 'newitem3', 'item4'] >>> x[:3] ['item1', 'item2', 'newitem3']

Lists >>> x = [ 'item1', 'item2', 'item3', 'item4' ] >>> >>> x[0] 'item1' >>> x[2] 'item3' >>> len(x) 4 >>> x[2] = 'newitem3' >>> x ['item1', 'item2', 'newitem3', 'item4'] >>> x[1:] ['item2', 'newitem3', 'item4'] >>> x[:3] ['item1', 'item2', 'newitem3'] a list (or array) is a sequence of values

EXERCISE >>> x = [ “abc”, “def”, “ghi”, “jkl” ] >>> x[1] + x[-1] what do you think will be printed here?

Lists >>> x = [ 'item1', 'item2', 'item3', 'item4' ] >>> >>> x[0] 'item1' >>> x[2] 'item3' >>> len(x) 4 >>> x[2] = 'newitem3' >>> x ['item1', 'item2', 'newitem3', 'item4'] >>> x[1:] ['item2', 'newitem3', 'item4'] >>> x[:3] ['item1', 'item2', 'newitem3'] a list (or array) is a sequence of values accessing list elements (i.e., indexing), computing length: similar to strings non-negative index values ( 0) index from the front of the list the first element has index 0 negative index values index from the end of the list the last element has index -1

Lists >>> x = [ 'item1', 'item2', 'item3', 'item4' ] >>> >>> x[0] 'item1' >>> x[2] 'item3' >>> len(x) 4 >>> x[2] = 'newitem3' >>> x ['item1', 'item2', 'newitem3', 'item4'] >>> x[1:] ['item2', 'newitem3', 'item4'] >>> x[:3] ['item1', 'item2', 'newitem3'] a list (or array) is a sequence of values accessing list elements (i.e., indexing), computing length: similar to strings lists are mutable, i.e., can be modified or updated different from strings slicing : similar to strings

Lists >>> x = [11, 22, 33] >>> y = [44, 55, 66, 77] >>> >>> x + y [11, 22, 33, 44, 55, 66, 77] >>> x * 3 [11, 22, 33, 11, 22, 33, 11, 22, 33] concatenation (+) : similar to strings multipilication (*) similar to strings

python review: functions

Functions def fn_name ( arg1 , …, argn ) return expr defines a function fn_name with n arguments arg1 , …, argn return expr optional returns the value of the expression expr to the caller fn_name(expr1, …, exprn) calls fn_name with arguments expr1, …, exprn

Functions >>> def double(x): return x + x >>> double(7) 14 >>> >>> def num_occurences(text, c): n, i = 0, 0 while i < len(text): if text[i] == c: n += 1 i += 1 return n >>> num_occurences("To be or not to be, that is the question.", "o") 5 def fn_name ( arg1 , …, argn ) defines a function fn_name with n arguments arg1 , …, argn return expr optional returns the value of the expression expr to the caller

Lists of Lists a list can consist of elements of many types, including lists >>> x = [ [1,2,3], [4], [5, 6]] >>> x [[1, 2, 3], [4], [5, 6]] >>> >>> >>> y = [ ['aa', 'bb', 'cc'], ['dd', 'ee', 'ff'], ['hh', 'ii', 'jj']] >>> >>> y [['aa', 'bb', 'cc'], ['dd', 'ee', 'ff'], ['hh', 'ii', 'jj']] a list of lists is called a 2-d list

Lists of Lists a list can consist of elements of many types, including lists >>> x = [ [1,2,3], [4], [5, 6]] >>> x [[1, 2, 3], [4], [5, 6]] >>> >>> >>> y = [ ['aa', 'bb', 'cc'], ['dd', 'ee', 'ff'], ['hh', 'ii', 'jj']] >>> >>> y [['aa', 'bb', 'cc'], ['dd', 'ee', 'ff'], ['hh', 'ii', 'jj']] a list of lists is called a 2-d list if the number of rows and columns are equal, it is a grid

Lists of Lists a list can consist of elements of many types, including lists >>> y [['aa', 'bb', 'cc'], ['dd', 'ee', 'ff'], ['hh', 'ii', 'jj']] >>> >>> y[0] ['aa', 'bb', 'cc'] >>> y[1] ['dd', 'ee', 'ff'] >>> y[2] ['hh', 'ii', 'jj'] >>> len(y) 3 >>> len(y[0]) a list of lists is called a 2-d list if the number of rows and columns are equal, it is a grid *must check the length of each row

EXERCISE >>> y [['aa', 'bb', 'cc'], ['dd', 'ee', 'ff'], ['hh', 'ii', 'jj']] >>> >>> y[0] ['aa', 'bb', 'cc'] >>> y[1] ['dd', 'ee', 'ff'] >>> y[2] ['hh', 'ii', 'jj'] how do we access 'bb'?

EXERCISE >>> x = [ [1,2,3], [10,20,30], [100,200, 300]] >>> x [[1, 2, 3], [10,20,30], [100,200,300]] >>> write the code to sum the first column of x