SEQUENCES:STRINGS,LISTS AND TUPLES. SEQUENCES Are items that are ordered sequentially and accessible via index offsets into its set of elements. Examples:

Slides:



Advertisements
Similar presentations
Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 15 Tuples 5/02/09 Python Mini-Course: Day 4 – Lesson 15 1.
Advertisements

CS 100: Roadmap to Computing Fall 2014 Lecture 0.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Variables and I/O. Types Strings –Enclosed in quotation marks –“Hello, World!” Integers –4, 3, 5, 65 Floats –4.5, 0.7 What about “56”?
Python November 14, Unit 7. Python Hello world, in class.
Variables and I/O. Types Strings –Enclosed in quotation marks –“Hello, World!” Integers –4, 3, 5, 65 Floats –4.5, 0.7 What about “56”?
Introduction to Python
INLS 560 – V ARIABLES, E XPRESSIONS, AND S TATEMENTS Instructor: Jason Carter.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
The if statement and files. The if statement Do a code block only when something is True if test: print "The expression is true"
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
Input, Output, and Processing
For. for loop The for loop in Python is more like a foreach iterative-type loop in a shell scripting language than a traditional for conditional loop.
Strings CS303E: Elements of Computers and Programming.
Outline  Why should we use Python?  How to start the interpreter on a Mac?  Working with Strings.  Receiving parameters from the command line.  Receiving.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Variables When programming it is often necessary to store a value for use later on in the program. A variable is a label given to a location in memory.
Programming, an introduction to Pascal
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
ITEC 109 Lecture 7 Operations. Review Variables / Methods Functions Assignments –Purpose? –What provides the data? –What stores the data? –What type of.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
INPUT & VARIABLES.
Strings in Python. Computers store text as strings GATTACA >>> s = "GATTACA" s Each of these are characters.
Variables and Expressions CMSC 201. Today we start Python! Two ways to use python: You can write a program, as a series of instructions in a file, and.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
A Tutorial on the Python Programming Language. Overview Running Python and Output Data Types Input and File I/O Control Flow Functions.
COMP 110: Spring Announcements Lab 1 due Wednesday at Noon Assignment 1 available on website Online drop date is today.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Literals A literal (sometimes called a constant) is a symbol which evaluates to itself, i.e., it is what it appears to be. Examples: 5 int literal
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.
SEQUENCES:STRINGS,LISTS AND TUPLES. SEQUENCES Are items that are ordered sequentially and accessible via index offsets into its set of elements. Examples:
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.
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.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Input, Output and Variables GCSE Computer Science – Python.
ENGINEERING 1D04 Tutorial 2. What we’re doing today More on Strings String input Strings as lists String indexing Slice Concatenation and Repetition len()
Agenda Introduction Computer Programs Python Variables Assignment
Topics Designing a Program Input, Processing, and Output
Python Variable Types.
Input and Output Upsorn Praphamontripong CS 1110
CSc 120 Introduction to Computer Programing II Adapted from slides by
String Processing Upsorn Praphamontripong CS 1110
Variables, Expressions, and IO
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
CHAPTER THREE Sequences.
An Introduction to Python
8 – Lists and tuples John R. Woodward.
CS 100: Roadmap to Computing
Wednesday 09/23/13.
Rocky K. C. Chang September 18, 2018 (Based on Zelle and Dierbach)
Topics Designing a Program Input, Processing, and Output
Python Basics with Jupyter Notebook
CISC101 Reminders Assignment 2 due today.
Topics Designing a Program Input, Processing, and Output
Introduction to Python Strings in Python Strings.
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
CS 100: Roadmap to Computing
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

SEQUENCES:STRINGS,LISTS AND TUPLES

SEQUENCES Are items that are ordered sequentially and accessible via index offsets into its set of elements. Examples: strings, lists and tuples String – consists of a sequence of characters String =“Hello” The first character of string “Hello” is ‘H’ HELLO Figure2-1:How sequence of elements are stored and accessed

C ONTINUE.. Sequence types works with all standard type operators (*,/,+,**) There are operators belongs to sequence type operators as below: Sequence operatorFunction seq [ ind ]Element located at index ind of seq seq [ ind1:ind2 ]Elements from ind1 up to but not including ind2 of seq seq * expr seq repeated expr times seq1 + seq2 Concatenates sequences seq1 and seq2 Obj in seq Tests if obj is a member of sequence seq Obj not in seq Tests if obj is not a member of sequence seq

STRINGS Strings can be created by enclosing characters in quotes. Single ‘ ’, double ‘” ” are same in Python Python used raw_string operator to create literal quotes Strings are a literal or scalar type means that they are treated by the interpreter as a singular value and not are not containers that hold other Python objects. String are immutable meaning that changing an element of a string requires creating a new string.

C REATING AND ASSIGNING STRINGS Can assign using scalar value or having str ( ) factory function make one and assigning it to a variable. examples: >>> aString =‘Hello world!’ >>> anotherString =“Python is cool!” Print aString Hello world >>>anotherString ‘Python is cool!’ >>> s=str(range(4)) >>> s ‘[0,1,2,3]’

U PDATE STRING String can be update by reassigning a variable to another string. The new value can be related to its previous value or to a completely new string Example: >>>aString =‘Hello World!’ >>>aString=aString[:6] +’Python!’ >>> aString ‘Hello Python!’ >>>aString =‘new string’ >>>aString ‘new string’

R EMOVE CHARACTERS AND STRINGS Recall- string are immutable meaning that it individual characters cannot be remove from an existing string. To allow this, the string needs to be empty or put together another string that drops the pieces that were not interested in. Example: we want to remove one letter from “Hello World!”, sat letter l. >>>aString =‘Hello World!’ >>>aString= aString[:3]+aString[4:] >>>aString ‘Helo World!’

C ONTINUE.. To clear or remove a string, assign an empty string or use the del statement. Examples: >>>aString=‘ ‘ >>>aString ‘ >>>del aString

S TRINGS AND OPERATORS >>> str1=‘abc’ >>>str2=‘lmn’ >>>str3=‘xyz’ >>>str1<str2 True >>>str2 !=str3 True >>>str1<str3 and str2==‘xyz’ False Strings are compared lexicographically (ASCII value order)

M EMBERSHIP 2 operators –in, not in The membership asks whether a string / sub string appears in another string. If that character appears in the string, return True else False Membership operation is not used to determine if a substring is within a string. To determine substring in string used the string methods or string module functions such as find()/index() (and their brethren rfind() and rindex()).

C ONTINUE.. >>> ‘bc’ in ‘abcd’ True >>>’n’ in ‘abcd’ False >>>’nm’ not in ‘abcd’ True

B UILT - IN FUNCTIONS Standard type functions – cmp() Similar to value comparison operators, the cmp() build-in function also performs a lexicographic (ASCII value –based) comparison for strings. >>>str1=‘abc’ >>>str2=‘lmn’ >>>str3=‘xyz’ >>>cmp(str1,str2) -11 [ =-11, based on character a=97, l=108] >>>cmp(str3,str1) 23 >>>cmp(str2,’lmn’) 0

CONTINUE Sequence type functions – len() Returns the number of characters in the string >>>str1 = ‘abc’ >>>len(str1) 3 >>>len(‘Hello world!’) 12 max() and min() >>> str2=‘lmn’ >>>str3=‘xyz’ >>>max(str2) ‘n’ >>>min(str3) ‘x’ Max() return the greatest value and min() the smallest value of characters in strings based on lexicographic order >>> min(‘abc12cd’ ‘1’ >>>min(‘ABCDa bcd’) ‘A’

CONTINUE enumerate() - Return an enumerate object Example: s=‘foobar’ >>>For i,t in enumerate (s): … print i,t 0 f 1 o b 4 a 5 r Assign ‘foobar’ to s- enumerate object

CONTINUE zip() - This function returns a list of tuples >>> s,t=‘foa’, ’obr’ >>>zip(s,t) [(‘f’,’o’,),(‘o’,’b’),(‘a’,’r’)] fOa obr

CONTINUE String type functions raw_input() – prompts the user with a given string and accepts and returns a user-input string. >>>user_input = raw_input(“Enter your name: “) Enter your name: John Doe >>>user_input ‘John Doe’ >>>len(user_input) 8

Use input for entering NUMBER Use raw_input for entering string I NPUT AND V ARIABLES num = input("Type in a Number: ") str = raw_input("Type in a string:") print "num =", num print "num * 2 =",num*2 print "str =", str print "str * 2 =",str*2 IMP ORTANT OUTPUT : Type in a Number: Type in a String: Hello num = num * 2 = str = Hello str * 2 = HelloHello

C ONTINUE.. num variable gets data from input str variable gets data from raw_input If you want the user to type in a number use input because it returns a number If you want the user to type in a string use raw_input because it returns a string

C ONTINUE.. Numbers are of type int or float (which are short for ’integer’ and ’floating point’ respectively) Strings are of type string Integers and floats can be worked on by mathematical functions, strings cannot.

E XAMPLE #This programs calculates rate and distance problems print "Input a rate and a distance" rate = input("Rate:") distance = input("Distance:") print "Time:",distance/rate OUTPUT : Input a rate and a distance Rate:5 Distance:10 Time: 2

C ONTINUE.. 5 rate distance 10 10/5=2 time = distance/rate Variables

E XERCISE 1 As a programmer you were asked to write a program that accepts user name, age and gender. Display user name, age and gender. Based on the given problem: Identify the input Determine the data type for each input /output Identify the output Design the solution using flowchart and pseudocode Transform the design to Python language

E XERCISE 2 As a programmer, you were asked to write a program that able to compare the two input strings. Your program must allow user to input both strings and make a comparison on which string is bigger that the other. Based on the given problem: Identify the input Identify the output Design the solution using flowchart and pseudocode Transform the design to Python language

E XERCISE 3 Write a program to convert an input number of nickels and dime into a total number of cents. For example, if the user inputs 3 and 7 for the number of nickels and dimes, respectively, the screen display at the end of the run would be : Enter number of nickels and dimes 3 7 Example output: 3 nickels and 7 dimes = 85 cents. Design the solution with flowchart and transform the flowchart into Python’s code

S OLUTION – EXERCISE 3

S OLUTION – E 3 >>> print ('enter number of nickels and dimes ') enter number of nickels and dimes >>> num1=input('nickles: ') nickles: 3 >>> num2=input('dimes;') dimes;7 >>> total=num1*5+num2*10 >>> print num1,'nickles and ',num2,'dimes =',total 3 nickles and 7 dimes = 85

E XERCISE 4 Design a program using list that allow user to input 5 numbers in a lists and get the average value. Design your solution with a pseudocode and transform the design to Python’s code.

P SEUDOCODE – EXERCISE 4 Begin input 5 numbers in list input first number at index 0 input second number at index 1 input third number at index 2 input fourth number at index 3 input fifth number at index 4 Total = index 0 +index 1+index 2+index 3+index 4 The average is total/5 Print average End

S OLUTION – EXERCISE 4 >>> list=[0,0,0,0,0] >>> list[0]=input('input number at index 0:') input number at index 0:2 >>> list[1]=input ('input number at index 1:') input number at index 1:2 >>> list[2]=input('input number at index 2:') input number at index 2:2 >>> list[3]=input('input number at index 3:') input number at index 3:2 >>> list[4]=input('input number at index 4:') input number at index 4:2 >>> total=list[0]+list[1]+list[2]+list[3]+list[4] print "the average is :",total/5 the average is : 2