UNIT-III. All expressions involving relational and logical operators will evaluate to either true or false
|
|
- Denis Carson
- 5 years ago
- Views:
Transcription
1 UNIT-III BOOLEAN VALUES AND OPERATORS: A boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces if they are equal and False otherwise: >>> 5 == 5 >>> 5 == 6 False and False are special values that belong to the type bool; they are not strings: >>> type() <class 'bool'> >>> type(false) <class 'bool'> The == operator is one of the relational operators; the others are: x!= y # x is not equal to y x > y # x is greater than y x < y # x is less than y x >= y # x is greater than or equal to y x <= y # x is less than or equal to y Note: All expressions involving relational and logical operators will evaluate to either true or false CONDITIONAL (IF): The if statement contains a logical expression using which data is compared and a decision is made based on the result of the comparison. Syntax : if expression: If the boolean expression evaluates to TRUE, then the block of inside the if statement is executed. If boolean expression evaluates to FALSE, then the first set of code after the end of the if is executed. a=10 if a>9: print( A is Greater than 9 ) Output: A is Greater than 9
2 ALTERNATIVE IF(IF-ELSE): An else statement can be combined with an if statement. An else statement contains the block of code (false block) that executes if the conditional expression in the if statement resolves to 0 or a FALSE value. The else statement is an optional statement and there could be at most only one else statement following if. if expression: Flowchart: Example Output B is Greater than A a=10 b=20 if a>b: print( A is Greater than B ) print( B is Greater than A ) CHAINED CONDITIONAL IF:(IF-ELIF-ELSE) The elif statement allows us to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if. if expression1: elif expression2: elif expression3:
3 Flowchart: var = 100 if var == 200: print 1 - Got a true expression value print var elif var == 150: print 2 - Got a true expression value print var elif var == 100: Output: print 3 - Got a true expression value print var print 4 - Got a false expression value print var print Good bye! 3 - Got a true expression value 100 Good bye! Nested Conditionals: One conditional can also be nested within another.
4 if expression1: if expression2: Flowchart: num = float(input( Enter a number: )) if num >= 0: if num == 0: print( Zero ) print( Positive number ) print( Negative Output: number ) Enter a number: 5 Positive number
5 ITERATION: A loop statement allows us to execute a statement or group of statements multiple times. Repeated execution of a set of statements with the help of loops is called iteration. WHILE LOOP: A while loop statement executes a block of statement again and again until the condition will occur false (or) Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body so this technique is known as Entry controlled loop. while expression: Flowchart: count = 0 while (count < 9): print The count is:, count count = count + 1 print Good bye! FOR LOOP: Executes a sequence of statements multiple times for iterating_var in sequence: statements(s)
6 If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating var. Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the block is executed until the entire sequence is exhausted. Flowchart: for letter in Python : print Current Letter :, letter Output: Current Letter : P Current Letter : y Current Letter : t Current Letter : h Current Letter : o Current Letter : n BREAK : Terminates the loop statement and transfers execution to the statement immediately following the loop. The break statement can be used in both while and for loops. for letter in Python : # First Example if letter == h : break print Current Letter :, letter Output: Current Letter : P Current Letter : y Current Letter : t
7 CONTINUE: It returns the control to the next iteration of the loop. The continue statement rejects all the remaining statements in the current iteration of the loop. The continue statement can be used in both while and for loops. for letter in Python : # First Example if letter == h : continue print Current Letter :, letter Output: Current Letter : P Current Letter : y Current Letter : t Current Letter : o Current Letter : n PASS: The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet for letter in Python : if letter == h : pass print This is pass block print Current Letter :, letter print Good bye! Output: Current Letter : P Current Letter : y Current Letter : t This is pass block Current Letter : h Current Letter : o Current Letter : n Good bye! FRUITFUL FUNCTIONS vs VOID FUNCTIONS: Any function that returns a value is called Fruitful function. A Function that does not return a value is called a void function *Write any example for both Fruitful and void functions
8 RETURN VALUES: The Keyword return is used to return back the value to the called function. def area(radius): b = * radius**2 return b VARIABLE SCOPE: Global Scope: A variable which is defined in the main body of a file is called a global variable. It will be visible throughout the file, and also inside any file which imports that file. Local Scope: A variable which is defined inside a function is local to that function. It is accessible from the point at which it is defined until the end of the function, and exists for as long as the function is executing # This is still a global variable b = 1 def my_function(c): # this is a local variable d = 3 print(c) print(d) FUNCTION COMPOSITION: Calling a function within another function is called as Function Composition. The output of one function is given as input to another function colors=('red','green','blue') >>> fruits=['orange','banana','cherry'] >>> zip(colors,fruits) <zip object at 0x020A00D0> >>>list(zip(colors,fruits)) [('red', 'orange'), ('green', 'banana'), ('blue', 'cherry')]
9 STRINGS A string is a sequence of characters. We can access the characters one at a time with the bracket operator: >>> fruit = 'banana' >>> letter = fruit[1] The second statement selects character number 1 from fruit and assigns it to letter. The expression in brackets is called an index. The index indicates which character in the sequence we want Strings are immutable It is tempting to use the [] operator on the left side of an assignment, with the intention of changing a character in a string. For example: >>> greeting = 'Hello, world!' >>> greeting[0] = 'J' TypeError: 'str' object does not support item assignment The reason for the error is that strings are immutable, which means we can t change an existing string. The best we can do is create a new string that is a variation on the original: >>> greeting = 'Hello, world!' >>> new_greeting = 'J' + greeting[1:] >>> new_greeting 'Jello, world! STRING SLICES: A segment of a string is called a slice. Selecting a slice is similar to selecting a character: String[start_index:end_index] >>> s = 'Monty Python' >>> s[0:5] 'Monty' >>> s[6:12] 'Python If you omit the first index (before the colon), the slice starts at the beginning of the string.if you omit the second index, the slice goes to the end of the string: >>> fruit = 'banana' >>> fruit[:3] If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks: >>> fruit = 'banana' >>> fruit[3:3] [ ]
10 STRING METHODS: S.no Method name Description 1. isalnum() Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise. 2. isalpha() Returns true if string has at least 1 character and all characters are alphabetic and false otherwise. 3. isdigit() Returns true if string contains only digits and false otherwise. 4. islower() Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise. 5. isnumeric() Returns true if a string contains only numeric characters and false otherwise. 6. isspace() Returns true if string contains only whitespace characters and false otherwise. 7. istitle() Returns true if string is properly titlecased and false otherwise. 8. isupper() Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise. 9. replace(old, new [, max]) Replaces all occurrences of old in string with new or at most max occurrences if max given. 10. split() Splits string according to delimiter str (space if not provided) and returns list of substrings; 11. count() Occurrence of a string in another string 12. find() Finding the index of the first occurrence of a string in another string 13. swapcase() Converts lowercase letters in a string to uppercase and viceversa 14. startswith(str, beg=0,end=len(string)) Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise. Note: All the string methods will be returning either true or false as the result 1.isalnum(): Isalnum() method returns true if string has at least 1 character and all characters are alphanumeric and false otherwise. String.isalnum() >>> string="123alpha" >>> string.isalnum()
11 2.isalpha(): isalpha() method returns true if string has at least 1 character and all characters are alphabetic and false otherwise. String.isalpha() >>> string="nikhil" >>> string.isalpha() 3.isdigit(): isdigit() returns true if string contains only digits and false otherwise. String.isdigit() >>> string=" " >>> string.isdigit() 4.islower(): Islower() returns true if string has characters that are in lowercase and false otherwise. String.islower() >>> string="nikhil" >>> string.islower() 5.isnumeric(): isnumeric() method returns true if a string contains only numeric characters and false otherwise. String.isnumeric() >>> string=" " >>> string.isnumeric() 6. isspace(): isspace() returns true if string contains only whitespace characters and false otherwise. String.isspace() >>> string=" " >>> string.isspace()
12 7.istitle() istitle() method returns true if string is properly titlecased (starting letter of each word is capital) and false otherwise String.istitle() >>> string="nikhil Is Learning" >>> string.istitle() 8.isupper() isupper() returns true if string has characters that are in uppercase and false otherwise. String.isupper() >>> string="hello" >>> string.isupper() 9.replace() replace() method replaces all occurrences of old in string with new or at most max occurrences if max given. String.replace() >>> string="nikhil Is Learning" >>> string.replace('nikhil','neha') 'Neha Is Learning' 10.split() split() method splits the string according to delimiter str (space if not provided) String.split() >>> string="nikhil Is Learning" >>> string.split() ['Nikhil', 'Is', 'Learning'] 11.count() count() method counts the occurrence of a string in another string String.count() >>> string='nikhil Is Learning' >>> string.count('i') 3
13 12. find() Find() method is used for finding the index of the first occurrence of a string in another string String.find( string ) >>> string="nikhil Is Learning" >>> string.find('k') swapcase() converts lowercase letters in a string to uppercase and viceversa String.find( string ) >>> string="hello" >>> string.swapcase() 'hello' 14. startswith() Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise. String.startswith( string ) >>> string="nikhil Is Learning" >>> string.startswith('n') 15.endswith() Determines if string or a substring of string (if starting index beg and ending index end are given) ends with substring str; returns true if so and false otherwise. String.endswith( string ) >>> string="nikhil Is Learning" >>> string.startswith('g')
14 STRING MODULE: This module contains a number of functions to process standard Python strings. In recent versions, most functions are available as string methods as well. Example : import string text = Monty Python s Flying Circus print upper, =>, string.upper(text) print lower, =>, string.lower(text) print split, =>, string.split(text) print join, =>, string.join(string.split(text), + ) print replace, =>, string.replace(text, Python, Java ) print find, =>, string.find(text, Python ), string.find(text, Java ) print count, =>, string.c ount(text, n ) ILLUSTRATIVE PROGRAMS: 1. FINDING SQUARE ROOT OF A GIVEN NUMBER while : print("enter x for exit.") num = input("enter a number: ") #input Number if num == 'x': break number = float(num) number_sqrt = number ** 0.5 #compute square root print('square Root of %0.2f is %0.2f' %(number, number_sqrt)) 2. FINDING GCD OF A NUMBER def gcd(a,b): if(b==0): return a return gcd(b,a%b) a=int(input( Enter first number: )) b=int(input( Enter second number: )) GCD=gcd(a,b) print( GCD is: ) print(gcd)
15 Output Case 1: Enter first number:5 Enter second number:15 GCD is: 5 Sum the array of numbers def listsum(numlist): if len(numlist) == 1: return numlist[0] return numlist[0] + listsum(numlist[1:]) print(listsum([1,3,5,7,9])) Output 25 LINEAR SEARCH: def sequentialsearch(alist, item) pos = 0 found = False while pos < len(alist) and not found: if alist[pos] == item: found = pos=pos+1 return found testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0] print(sequentialsearch(testlist, 3)) print(sequentialsearch(testlist, 13)) Output False
16 BINARY SEARCH def binarysearch(alist, item): first = 0 last = len(alist)-1 found = False while first<=last and not found: midpoint = (first + last)//2 if alist[midpoint] == item: found = if item < alist[midpoint]: last = midpoint-1 first = midpoint+1 return found testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,] print(binarysearch(testlist, 3)) print(binarysearch(testlist, 13))
PYTHON MOCK TEST PYTHON MOCK TEST III
http://www.tutorialspoint.com PYTHON MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to Python. You can download these sample mock tests at your local
More informationString Processing CS 1111 Introduction to Programming Fall 2018
String Processing CS 1111 Introduction to Programming Fall 2018 [The Coder s Apprentice, 10] 1 Collections Ordered, Dup allow List Range String Tuple Unordered, No Dup Dict collection[index] Access an
More informationStrings. Chapter 6. Python for Everybody
Strings Chapter 6 Python for Everybody www.py4e.com String Data Type A string is a sequence of characters A string literal uses quotes 'Hello' or "Hello" For strings, + means concatenate When a string
More informationStrings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break
Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break Strings Upsorn Praphamontripong CS 1111 Introduction to Programming Spring 2018 Strings Sequence of characters
More informationWorking with Sequences: Section 8.1 and 8.2. Bonita Sharif
Chapter 8 Working with Sequences: Strings and Lists Section 8.1 and 8.2 Bonita Sharif 1 Sequences A sequence is an object that consists of multiple data items These items are stored consecutively Examples
More informationIntroduction to Python
Introduction to Python خانه ریاضیات اصفهان فرزانه کاظمی زمستان 93 1 Why Python? Python is free. Python easy to lean and use. Reduce time and length of coding. Huge standard library Simple (Python code
More informationCOLLEGE OF ENGINEERING, NASHIK-4
Pune Vidyarthi Griha s COLLEGE OF ENGINEERING, NASHIK-4 DEPARTMENT OF COMPUTER ENGINEERING Important PYTHON Questions 1. What is Python? Python is a high-level, interpreted, interactive and object-oriented
More informationStrings are actually 'objects' Strings
Strings are actually 'objects' Strings What is an object?! An object is a concept that we can encapsulate data along with the functions that might need to access or manipulate that data. What is an object?!
More informationSequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python
Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted
More informationChapter 8: More About Strings. COSC 1436, Summer 2018 Dr. Zhang 7/10/2018
Chapter 8: More About Strings COSC 1436, Summer 2018 Dr. Zhang 7/10/2018 Creating Strings The str Class s1 = str() # Create an empty string s2 = str("welcome") # Create a string Welcome Python provides
More informationIntroductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University
Introductory Linux Course Martin Dahlö UPPMAX Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University August, 2018 Outline Python basics get started with Python Data types Control
More informationDECODE SPECIAL OPERATOR, FORMAT OPERATOR CONTENTS TRIPLE QUOTES. IS a-to-z METHODS REPLACE L E N G T H E X P A N D T A B S ENC0D3
The Game of Strings CONTENTS ACCESS, UPDATE, ESCAPE UNICODE STRINGS MAX MIN TRIPLE QUOTES E X P A N D T A B S ENC0D3 DECODE JUST LSTRIP METHODS IS a-to-z UNIC DE JOIN INDEX SPECIAL OPERATOR, FORMAT OPERATOR
More informationIntroduction to Python for Plone developers
Plone Conference, October 15, 2003 Introduction to Python for Plone developers Jim Roepcke Tyrell Software Corporation What we will learn Python language basics Where you can use Python in Plone Examples
More informationChapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationIntroduction to String Manipulation
Introduction to Computer Programming Introduction to String Manipulation CSCI-UA.0002 What is a String? A String is a data type in the Python programming language A String can be described as a "sequence
More informationModule 3: Strings and Input/Output
Module 3: Strings and Input/Output Topics: Strings and their methods Printing to standard output Reading from standard input Readings: ThinkP 8, 10 1 Strings in Python: combining strings in interesting
More informationCompound Data Types 1
Compound Data Types 1 Chapters 8, 10 Prof. Mauro Gaspari: mauro.gaspari@unibo.it Compound Data Types Strings are compound data types: they are sequences of characters. Int and float are scalar data types:
More informationIntroductory Linux Course. Python I. Pavlin Mitev UPPMAX. Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University
Introductory Linux Course Python I Pavlin Mitev UPPMAX Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University August, 2017 Outline Python introduction Python basics get started with
More informationAdvanced Python. Executive Summary, Session 1
Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.
More information18.1. CS 102 Unit 18. Python. Mark Redekopp
18.1 CS 102 Unit 18 Python Mark Redekopp 18.2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 18.3 Python in Context Two
More informationThe second statement selects character number 1 from and assigns it to.
Chapter 8 Strings 8.1 A string is a sequence A string is a sequence of characters. You can access the characters one at a time with the bracket operator: The second statement selects character number 1
More informationThere are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:
Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited
More informationMidterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals
Midterm 1 Review Important control structures Functions Loops Conditionals Important things to review Binary numbers Boolean operators (and, or, not) String operations: len, ord, +, *, slice, index List
More information\n is used in a string to indicate the newline character. An expression produces data. The simplest expression
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationAccelerating Information Technology Innovation
Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 1 Introduction to Python Agenda What is Python? and Why Python? Basic Syntax Strings User Input Useful
More informationPython Tutorial. Day 1
Python Tutorial Day 1 1 Why Python high level language interpreted and interactive real data structures (structures, objects) object oriented all the way down rich library support 2 The First Program #!/usr/bin/env
More informationPython for Informatics
Python for Informatics Exploring Information Version 0.0.6 Charles Severance Chapter 6 Strings 6.1 A string is a sequence A string is a sequence of characters. You can access the characters one at a time
More informationAccelerating Information Technology Innovation
Accelerating Information Technology Innovation http://aiti.mit.edu/program/philippines-summer-2012/ Philippines Summer 2012 Lecture 1 Introduction to Python June 19, 2012 Agenda About the Course What is
More informationLanguage Reference Manual
ALACS Language Reference Manual Manager: Gabriel Lopez (gal2129) Language Guru: Gabriel Kramer-Garcia (glk2110) System Architect: Candace Johnson (crj2121) Tester: Terence Jacobs (tj2316) Table of Contents
More informationSTATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration
STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the
More informationComposite Types. You will learn how to create new variables that are collections of other entities. Types Of Variables.
Composite Types You will learn how to create new variables that are collections of other entities Types Of Variables Python variables Example composite A string (collection of characters) can be decomposed
More informationConverting a Lowercase Letter Character to Uppercase (Or Vice Versa)
Looping Forward Through the Characters of a C String A lot of C string algorithms require looping forward through all of the characters of the string. We can use a for loop to do that. The first character
More informationChapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.
Chapter 5 Conditional and Iterative Statements Statement Statement are the instructions given to the computer to perform any kind of action. Types of Statement 1. Empty Statement The which does nothing.
More informationWorksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords
Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long
More informationPython I. Some material adapted from Upenn cmpe391 slides and other sources
Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics
More informationHere n is a variable name. The value of that variable is 176.
UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence
More informationCS 115 Lecture 8. Selection: the if statement. Neil Moore
CS 115 Lecture 8 Selection: the if statement Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 24 September 2015 Selection Sometime we want to execute
More informationDecisions. Arizona State University 1
Decisions CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 4 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More informationIPSL python tutorial: some exercises for beginners
1 of 9 10/22/2013 03:55 PM IPSL python tutorial: some exercises for beginners WARNING! WARNING! This is the FULL version of the tutorial (including the solutions) WARNING! Jean-Yves Peterschmitt - LSCE
More informationIntroductory Linux Course. Python I. Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University
Introductory Linux Course Python I Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University nina.fischer@icm.uu.se January 12, 2017 Outline q Python introducjon q Python basics get started
More informationIntroductory Linux Course. Python I. Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University
Introductory Linux Course Python I Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University nina.fischer@icm.uu.se August 26, 2016 Outline q Python introducjon q Python basics get started
More informationPython. Executive Summary
Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic"
More informationPython Programming: Lecture 2 Data Types
Python Programming: Lecture 2 Data Types Lili Dworkin University of Pennsylvania Last Week s Quiz 1..pyc files contain byte code 2. The type of math.sqrt(9)/3 is float 3. The type of isinstance(5.5, float)
More informationGE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING
GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why
More informationSCoLang - Language Reference Manual
SCoLang - Language Reference Manual Table of Contents: 1. Introduction 2. Types a. Basic Data types b. Advanced Data types 3. Lexical Convention a. Identifiers b. Keywords c. Comments d. Operators e. Punctuators
More informationUnit 2. Srinidhi H Asst Professor
Unit 2 Srinidhi H Asst Professor 1 Iterations 2 Python for Loop Statements for iterating_var in sequence: statements(s) 3 Python for While Statements while «expression»: «block» 4 The Collatz 3n + 1 sequence
More informationHandling Strings and Bytes
Chapter 9 Handling Strings and Bytes In this chapter, we present some of the most used methods in strings and bytes objects. Strings are extremely useful to manage most of the output generated from programs,
More informationLists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10
Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Administrative Homework #5 is due today Homework #6 is out and DUE on MONDAY (3/5)
More informationStandard prelude. Appendix A. A.1 Classes
Appendix A Standard prelude In this appendix we present some of the most commonly used definitions from the standard prelude. For clarity, a number of the definitions have been simplified or modified from
More informationLists, loops and decisions
Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence
More informationIntroduction to: Computers & Programming: Strings and Other Sequences
Introduction to: Computers & Programming: Strings and Other Sequences in Python Part I Adam Meyers New York University Outline What is a Data Structure? What is a Sequence? Sequences in Python All About
More informationPREPARING FOR PRELIM 1
PREPARING FOR PRELIM 1 CS 1110: FALL 2012 This handout explains what you have to know for the first prelim. There will be a review session with detailed examples to help you study. To prepare for the prelim,
More informationPrinceton University COS 333: Advanced Programming Techniques A Subset of Python 2.7
Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7 Program Structure # Print "hello world" to stdout. print 'hello, world' # Print "hello world" to stdout. def f(): print
More informationRuby: Introduction, Basics
Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie
More informationIntroduction to Python
Introduction to Python Why is Python? Object-oriented Free (open source) Portable Powerful Mixable Easy to use Easy to learn Running Python Immediate mode Script mode Integrated Development Environment
More informationStrings. Looping. dna = 'ATGTAGC' print(dna) In [1]: ATGTAGC. You can loop over the characters of a string using a for loop, as we saw on Tuesday:
Strings A string is simply a sequence of characters. From a biological perspective, this is quite useful, as a DNA sequence is simply a string composed of only 4 letters, and thus easily manipulated in
More informationWelcome to Python 3. Some history
Python 3 Welcome to Python 3 Some history Python was created in the late 1980s by Guido van Rossum In December 1989 is when it was implemented Python 3 was released in December of 2008 It is not backward
More informationMuntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types
Programming Fundamentals for Engineers 0702113 5. Basic Data Types Muntaser Abulafi Yacoub Sabatin Omar Qaraeen 1 2 C Data Types Variable definition C has a concept of 'data types' which are used to define
More informationPYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s
PYTHON FO R K I D S A P l ay f u l I n t r o d u c t i o n to P r o g r a m m i n g Jason R. Briggs Index Symbols and Numbers + (addition operator), 17 \ (backslash) to separate lines of code, 235 in strings,
More informationUNIVERSITÀ DI PADOVA. < 2014 March >
UNIVERSITÀ DI PADOVA < 2014 March > Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. Easy-to-read: Python code is much more clearly defined and visible
More informationCMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi All of the variables that we have used have held a single item One integer, floating point value, or string often you find that you want
More informationREPETITION CONTROL STRUCTURE LOGO
CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of
More informationPython. Olmo Zavala R. Python Exercises. Center of Atmospheric Sciences, UNAM. August 24, 2016
Exercises Center of Atmospheric Sciences, UNAM August 24, 2016 NAND Make function that computes the NAND. It should receive two booleans and return one more boolean. logical operators A and B, A or B,
More informationx = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0
6 Statements 43 6 Statements The statements of C# do not differ very much from those of other programming languages. In addition to assignments and method calls there are various sorts of selections and
More informationPython. Chapter 3. Strings
Python Chapter 3 Strings 25 Chapter 3 Strings 26 Python Chapter 3 Strings In This Chapter: 1. swap case 2. String Split and Join 3. What's Your Name? 4. Mutations 5. Find a string 6. String Validators
More informationProgramming in Python
3. Sequences: Strings, Tuples, Lists 15.10.2009 Comments and hello.py hello.py # Our code examples are starting to get larger. # I will display "real" programs like this, not as a # dialog with the Python
More informationVariable and Data Type I
Islamic University Of Gaza Faculty of Engineering Computer Engineering Department Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad September 24, 2016 Variable is reserved a location in memory to store
More information2. First Program Stuff
CSE 232 First Midterm, Overview: 1. Getting Started 1. we got started 2. First Program Stuff 1. Compiler vs. Intepreter a. do you know all the steps to create an executable? 2. Variables are declared a.
More informationConditional Expressions and Decision Statements
Conditional Expressions and Decision Statements June 1, 2015 Brian A. Malloy Slide 1 of 23 1. We have introduced 5 operators for addition, subtraction, multiplication, division, and exponentiation: +,
More informationLanguage Reference Manual
TAPE: A File Handling Language Language Reference Manual Tianhua Fang (tf2377) Alexander Sato (as4628) Priscilla Wang (pyw2102) Edwin Chan (cc3919) Programming Languages and Translators COMSW 4115 Fall
More information7. String Methods. Methods. Methods. Data + Functions Together. Designing count as a Function. Three String Methods 1/22/2016
7. String Methods Topics: Methods and Data More on Strings Functions and Methods The String Class Data + Functions Together The square root of nine is three. The tone of this comment is that the square
More informationCase by Case. Chapter 3
Chapter 3 Case by Case In the previous chapter, we used the conditional expression if... then... else to define functions whose results depend on their arguments. For some of them we had to nest the conditional
More informationIteration. Chapter 7. Prof. Mauro Gaspari: Mauro Gaspari - University of Bologna -
Iteration Chapter 7 Prof. Mauro Gaspari: gaspari@cs.unibo.it Multiple assigments bruce = 5 print bruce, bruce = 7 print bruce Assigment and equality With multiple assignment it is especially important
More information"Hello" " This " + "is String " + "concatenation"
Strings About Strings Strings are objects, but there is a special syntax for writing String literals: "Hello" Strings, unlike most other objects, have a defined operation (as opposed to a method): " This
More informationIntro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming
Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals
More informationCPD for GCSE Computing: Practical Sheet 6 February 14
Aims Programming Sheet 6 Arrays in Python Section Aim 1 Arrays A variable with many values Understand the idea of an array as a way to combine many values that are assigned to as single variable. 2 While
More information#4: While Loop Reading: Chapter3
CS 130R: Programming in Python #4: While Loop Reading: Chapter3 Contents Constants While loop Infinite loop Break Continue Constants Similar to variables, but their names are with capital letters and their
More informationSPARK-PL: Introduction
Alexey Solovyev Abstract All basic elements of SPARK-PL are introduced. Table of Contents 1. Introduction to SPARK-PL... 1 2. Alphabet of SPARK-PL... 3 3. Types and variables... 3 4. SPARK-PL basic commands...
More informationGetting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013
CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?
More informationStandard Types. Standard Types. Numbers
4 Standard Types Lesson 4 is one of the longest lessons in this LiveLessons video course, so we recommend you break it up and view different segments at a time rather than watching it all in one sitting.
More informationPython allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:
1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,
More informationThe SPL Programming Language Reference Manual
The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming
More informationExceptions and File I/O
Lab 6 Exceptions and File I/O Lab Objective: In Python, an exception is an error detected during execution. Exceptions are important for regulating program usage and for correctly reporting problems to
More informationIntroduction to Algorithms and Data Structures. Lecture 6 - Stringing Along - Character and String Manipulation
Introduction to Algorithms and Data Structures Lecture 6 - Stringing Along - Character and String Manipulation What are Strings? Character data is stored as a numeric code that represents that particular
More informationtoday cs3157-fall2002-sklar-lect05 1
today homework #1 due on monday sep 23, 6am some miscellaneous topics: logical operators random numbers character handling functions FILE I/O strings arrays pointers cs3157-fall2002-sklar-lect05 1 logical
More informationMULTIPLE CHOICE. Chapter Seven
Chapter Seven MULTIPLE CHOICE 1. Which of these is associated with a specific file and provides a way for the program to work with that file? a. Filename b. Extension c. File object d. File variable 2.
More informationComputing with Strings. Learning Outcomes. Python s String Type 9/23/2012
Computing with Strings CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17 1 Learning Outcomes To understand the string data type and how strings are represented
More informationDuration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT
Duration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT Online Classes are also available Recorded class will be given if you miss any day interview tips and quiz at end of every module
More informationCOMP 364: Classes, Objects, and Names
COMP 364: Classes, Objects, and Names Carlos G. Oliver, Christopher Cameron September 13, 2017 1/26 Outline 1. 202 vs 364 2. Development Environment Recap 3. Basic Data Types 4. Variables 2/26 Your Development
More informationPython Strings. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. September 25, 2012
Python Strings Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée September 25, 2012 Stéphane Vialette (LIGM UPEMLV) Python Strings September 25, 2012 1 / 22 Outline 1 Introduction 2 Using strings
More informationCS2304: Python for Java Programmers. CS2304: Sequences and Collections
CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for
More informationStatements 2. a operator= b a = a operator b
Statements 2 Outline Note: i=i+1 is a valid statement. Don t confuse it with an equation i==i+1 which is always false for normal numbers. The statement i=i+1 is a very common idiom: it just increments
More informationThe C++ Language. Arizona State University 1
The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More informationCOMS W4115 Programming Languages & Translators GIRAPHE. Language Reference Manual
COMS W4115 Programming Languages & Translators GIRAPHE Language Reference Manual Name UNI Dianya Jiang dj2459 Vince Pallone vgp2105 Minh Truong mt3077 Tongyun Wu tw2568 Yoki Yuan yy2738 1 Lexical Elements
More informationLecture 27. Lecture 27: Regular Expressions and Python Identifiers
Lecture 27 Lecture 27: Regular Expressions and Python Identifiers Python Syntax Python syntax makes very few restrictions on the ways that we can name our variables, functions, and classes. Variables names
More informationChapter 10 Characters, Strings, and the string class
Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class Copyright 2003 Scott/Jones Publishing Topics 10.1 Character Testing 10.2 Character Case Conversion
More informationBabu Madhav Institute of Information Technology, UTU 2015
Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?
More informationShell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi
Shell / Python Tutorial CS279 Autumn 2017 Rishi Bedi Shell (== console, == terminal, == command prompt) You might also hear it called bash, which is the most widely used shell program macos Windows 10+
More informationStrings, Lists, and Sequences
Strings, Lists, and Sequences It turns out that strings are really a special kind of sequence, so these operations also apply to sequences! >>> [1,2] + [3,4] [1, 2, 3, 4] >>> [1,2]*3 [1, 2, 1, 2, 1, 2]
More informationMore on Strings Is Twitter Successful?
More on Strings Is Twitter Successful? HW 3 Due this Thursday! HW 3 Bonus question: comment Please come to office hours! Announcement Social Impact of Twitter http://techcrunch.com/2013/01/15/twitters-social-impact-cant-bemeasured-but-its-the-pulse-of-the-planet/
More information