CHAPTER 3: String And Numeric Data In Python

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

1 Programming Languages and Paradigms Lisp Programming.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Introduction to Python
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏
Introduction to C Programming
Guide to Programming with Python Chapter Two Basic data types, Variables, and Simple I/O: The Useless Trivia Program.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
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.
Computing with Numbers Zelle - Chapter 3 Charles Severance - Textbook: Python Programming: An Introduction to Computer Science, John.
Numeric Types, Expressions, and Output ROBERT REAVES.
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Input, Output, and Processing
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Built-in Data Structures in Python An Introduction.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Variables, Expressions and Statements
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Chapter 5 Strings CSC1310 Fall Strings Stringordered storesrepresents String is an ordered collection of characters that stores and represents text-based.
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏ Sec 9-7 Web Design.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Data Manipulation Variables, Data Types & Math. Aug Variables A variable is a name (identifier) that points to a value. They are useful to store.
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.
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.
Mr. Crone.  Use print() to print to the terminal window  print() is equivalent to println() in Java Example) print(“Hello1”) print(“Hello2”) # Prints:
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Few More Math Operators
String and Lists Dr. José M. Reyes Álamo.
Fundamentals of Programming I Overview of Programming
Topics Designing a Program Input, Processing, and Output
Catapult Python Programming Wednesday Morning session
CSc 120 Introduction to Computer Programing II Adapted from slides by
Chapter 8 Text Files We have, up to now, been storing data only in the variables and data structures of programs. However, such data is not available.
Chapter 2 - Introduction to C Programming
CS 100: Roadmap to Computing
Variables and Primative Types
Presented By S.Yamuna AP/IT
Variables, Expressions, and IO
Chapter 2 - Introduction to C Programming
Introduction to Programming
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Few More Math Operators
Data types Numeric types Sequence types float int bool list str
String and Lists Dr. José M. Reyes Álamo.
Coding Concepts (Data- Types)
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Chapter 3 Mathematical Functions, Strings, and Objects
Fundamentals of Python: First Programs
Variables, Data Types & Math
CS190/295 Programming in Python for Life Sciences: Lecture 3
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Introduction to Computer Science
Terminal-Based Programs
月夜憶舍弟 戍鼓斷人行,邊秋一雁聲。 露從今夜白,月是故鄉明。 有弟皆分散,無家問死生。 寄書長不達,況乃未休兵。 杜甫
Python Review
Unit 3: Variables in Java
Introduction to Programming
月夜憶舍弟 戍鼓斷人行,邊秋一雁聲。 露從今夜白,月是故鄉明。 有弟皆分散,無家問死生。 寄書長不達,況乃未休兵。 杜甫
Class code for pythonroom.com cchsp2cs
More Basics of Python Common types of data we will work with
Presentation transcript:

CHAPTER 3: String And Numeric Data In Python COMPUTER PROGRAMMING SKILLS 1439-1440

Outline String Constants Special Characters String Operations Types of Numeric Data Hexadecimal, Octal and Binary Numeric Operators and functions Order of Numeric Operators Exercises

String Constants Strings are a collection of characters which are stored together to represent arbitrary text inside a python program. You can create a string constant inside a python program by surrounding text with either single quotes (’), double quotes ("), or a collection of three of either types of quotes (’’’ or """). In the first two cases, the opening and closing quotes must appear on the same line in your program; when you use triple quotes, your text can span as many lines as you like. The empty string '' is the string equivalent of the number 0. It is a string with nothing in it.

String Constants s = 'Hello' t = "Hello" m = """This is a long string that is spread across two lines.""" b=''

Special Characters The backslash, \, is used to get certain special characters, called escape characters, into your string. There are a variety of escape characters, and here are the most useful ones: \n the newline character. It is used to advance to the next line. \t This is used to insert an escape character. print('Hi\nthere!') print('Hi\t there!') Hi there! Hi there!

Special Characters \' for inserting apostrophes into strings. Say you have the following string: s = 'I can't go' This will produce an error because the apostrophe will actually end the string. You can use \' to get around this: s = 'I can\'t go' Another option is to use double quotes for the string: s =" I can't go" \" analogous to \' \\ This is used to get the backslash itself. For example: filename = 'c:\\programs\\file.py' filename = 'c:\\programs\\file.py' print(filename) c:\programs\file.py

String Operations (length, concatenation) To get the length of a string (how many characters it has), use the built-in function len. For example, len('Hello') is 5. The operators + and * can be used on strings. The + operator combines two strings. This operation is called concatenation. The * repeats a string a certain number of times. print('AB'+'cd’) print('A'+'7'+'B’) print('Hi'*4) ABcd A7B HiHiHiHi

String Operations (Indexing) We will often want to pick out individual characters from a string. Python uses square brackets to do this. The table below gives some examples of indexing the string s='Python'. The first character of s is s[0], not s[1]. Remember that in programming, counting usually starts at 0, not 1. Negative indices count backwards from the end of the string. When we try to do s[12]. There are only six characters in the string and Python will raise the following error message: IndexError: string index out of range

String Operations (Slices) A slice is used to pick out part of a string. It behaves like a combination of indexing and the range function. Below we have some examples with the string s='abcdefghij'. index: 0 1 2 3 4 5 6 7 8 9 letters: a b c d e f g h i j

String Operations (Changing individual characters of a string) Suppose we have a string called s and we want to change the character at index 4 of s to 'X'. It is tempting to try s[4]='X', but that unfortunately will not work. Python strings are immutable, which means we can’t modify any part of them. If we want to change a character of s, we have to instead build a new string from s and reassign it to s. Here is code that will change the character at index 4 to 'X’: s = s[:4] + 'X' + s[5:] The idea of this is we take all the characters up to index 4, then X, and then all of the characters after index 4.

String Operations (String Methods) Strings come with a ton of methods, functions that return information about the string or return a new string that is a modified version of the original. Here are some of the most useful ones:

String Operations (String Methods) One very important note about lower, upper, and replace is that they do not change the original string. If you want to change a string, s, to all lowercase, it is not enough to just use s.lower(). You need to do the following: s = s.lower() If you try to find the index of something that is not in a string, Python will raise an error. For instance, if s='abc' and you try s.index('z'), you will get an error.

Types of Numeric Data Integers and decimal numbers are represented differently on computers. Integers are whole numbers, which means they have no fractional parts, and they can be positive, negative, or zero. To compute the area of a circle given the circle’s radius, we use the value π, or approximately 3.14159. Python supports such noninteger numbers, and they are called floating-point numbers. The Python name for the floating-point type is float. x = 5 y=5.24 print(type(x)) print(type(y)) <class 'int'> <class 'float'>

Hexadecimal, Octal and Binary Hexadecimal, octal, and binary Python has built-in functions hex, oct, and bin for converting integers to hexadecimal, octal, and binary. The int function converts those bases to base 10. Hexadecimal values are prefaced with 0x, octal values are prefaced with 0o and binary values are prefaced with 0b. print(hex(250)) print(oct(250)) print(bin(250)) print(int(0xfa)) 0xfa 0o372 0b11111010 250

Hexadecimal, Octal and Binary The int function has an optional second argument that allows you to specify the base you are converting from. print(int('101101', 2)) # convert from base 2 print(int('617052', 8)) # convert from base 8 print(int('12A04', 16)) # convert from base 16 45 204330 76292

Numeric Operators and functions (operators) Here is a list of the common operators in Python:

Numeric Operators and functions (operators) The integer division operator, //, is basically, for positive numbers. It behaves like ordinary division except that it throws away the decimal part of the result. For instance, while 8/5 is 1.6, we have 8//5 equal to 1. The modulo operator, %, returns the remainder from a division. For instance, the result of 18%7 is 4 because 4 is the remainder when 18 is divided by 7. Thus to check if a number, n, is even, see if n%2 is equal to 0. To check if n is divisible by 3, see if n%3 is 0.

Numeric Operators and functions (functions) Python has a module called math that contains familiar math functions, including sin, cos, tan, exp, log, log10, factorial, sqrt, floor, and ceil. There are also the inverse trig functions, hyperbolic functions, and the constants pi and e. from math import sin, pi print('Pi is roughly', pi) print('sin(0) =', sin(0)) Pi is roughly 3.141592653589793 sin(0) = 0.0

Numeric Operators and functions (functions) There are two built in math functions, abs (absolute value) and round that are available without importing the math module. The round function takes two arguments: the first is the number to be rounded and the second is the number of decimal places to round to. The second argument can be negative. print(abs(-4.3)) print(round(3.336, 2)) print(round(345.2, -1)) 4.3 3.34 350.0

Numeric Operators and functions (functions) The built-in int function creates an actual integer object from a string that looks like an integer, and the str function creates a string object from the digits that make up an integer. the result of the expression 5 + 10 is very different from '5' + '10'. The plus operator splices two strings together in a process known as concatenation. Mixing the two types directly is not allowed: print ('5'+10) #You have to write: print (int('5')+10) or print ('5'+'10') Traceback (most recent call last): File "/home/main.py", line 1, in <module> print ('5'+10) TypeError: Can't convert 'int' object to str implicitly

Numeric Operators and functions (functions) Python comes with a module, called random, that allows us to use random numbers in our programs. To load this function, we use the following statement: from random import randint Using randint is simple: randint(a,b) will return a random integer between a and b including both a and b. from random import randint x = randint(1,10) print('A random number between 1 and 10: ', x) A random number between 1 and 10: 7

Order of Numeric Operators 1 ( ) 2 ** 3 / // % 4 + -

Exercises Write a program that asks the user to enter a string. The program should then print the following: The total number of characters in the string The string repeated 10 times The first character of the string (remember that string indices start at 0) The first three characters of the string The last three characters of the string The string backwards The second character of the string if the string is long enough The string with its first and last characters removed

Exercises Write a program that generates a random number, x, between 1 and 50, a random number y between 2 and 5, and computes x y . Write a program that generates a random number between 1 and 10 and prints your name that many times. Write a program that asks the user to enter two numbers, x and y, and computes |x-y|/(x+y) . Write a program that asks the user for a number and prints out the factorial of that number. Write a program that asks the user for a number of seconds and prints out how many minutes and seconds that is. For instance, 200 seconds is 3 minutes and 20 seconds. [Hint: Use the // operator to get minutes and the % operator to get seconds.]