Introduction to Programming

Slides:



Advertisements
Similar presentations
The Print Formatting Statement … named printf. 2 Introduction to printf statements print and println statements don’t allow us to easily format output.
Advertisements

1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
Introduction to Python
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
Introduction to Python
Chapter 9 Formatted Input/Output Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
 Pearson Education, Inc. All rights reserved Formatted Output.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Input, Output, and Processing
6 October 2015Birkbeck College, U. London1 Introduction to Computer Systems Lecturer: Steve Maybank Department of Computer Science and Information Systems.
6 October 2015Birkbeck College, U. London1 Introduction to Computer Systems Lecturer: Steve Maybank Department of Computer Science and Information Systems.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
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.
Formatting Output. Line Endings By now, you’ve noticed that the print( ) function will automatically print out a new line after passing all of the arguments.
22 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
29 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
Introduction to Programming Python Lab 5: Strings and Output 05 February PythonLab5 lecture slides.ppt Ping Brennan
5 February 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
12 February 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
Introduction to Programming
28 Formatted Output.
C Formatted Input/Output
Introduction to Programming
Introduction to Programming
Topics Designing a Program Input, Processing, and Output
Introduction to Programming
Formatting Output.
CPS120: Introduction to Computer Science
TMF1414 Introduction to Programming
Introduction to Programming
Variables, Expressions, and IO
Formatting Output.
Introduction to Programming
OUTPUT STATEMENTS GC 201.
Introduction to Programming
Introduction to Strings
Introduction to Strings
Introduction to Programming
Introduction to Programming
INPUT & OUTPUT scanf & printf.
Introduction to C++ Programming
Introduction to Programming
Introduction to Programming
Introduction to Programming
CS 100: Roadmap to Computing
Introduction to Programming
Margaret Derrington KCL Easter 2014
Wednesday 09/23/13.
Topics Designing a Program Input, Processing, and Output
Introduction to Programming
Introduction to Programming
Topics Designing a Program Input, Processing, and Output
Introduction to Strings
Introduction to Programming
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Introduction to Programming
Introduction to Strings
Introduction to Programming
Introduction to Programming
Introduction to Programming
CS 100: Roadmap to Computing
Introduction to Strings
Getting Started in Python
Presentation transcript:

Introduction to Programming Department of Computer Science and Information Systems Tingting Han (afternoon), Steve Maybank (evening) tingting@dcs.bbk.ac.uk sjmaybank@dcs.bbk.ac.uk Autumn 2018 Week 5: Strings and Output Birkbeck College, U. London

Example 1 of a Function Call first = input("Enter your first name: ") Name of the function: input Argument: the string "Enter your first name: " Returned value: a string entered at the keyboard The returned value becomes the value of first The detailed actions of input are hidden. The calling program has knowledge only of the argument and the returned value. PFE Section 2.2.4

Example 2 of a Function Call mn = min(1, 5, 8, 6.2) Name of the function: min Arguments: the numbers 1, 5, 8, 6.2 Returned value: 1 The returned value becomes the value of mn min is unusual in that it can have any number of arguments PFE Section 2.2.4

Revision: int and float # returns 5.67 float(5.67) float("3E2") # returns 300.0 float("3") # returns 3.0 float("5.2*6.7") # error int("5") # returns the integer 5 int(5.999) int(-5.999) # returns the integer -5 int("5.672") # error Yes, the behaviour of round(,2) is a bit strange for e.g.,   round(21.605,2) #21.61 round(21.615,2) #21.61     (not following the even integer rule) round(356.615,2) # 356.62 I guess it is due to 21.615 is actually something like 21.61499999…, but 356.615 is something like 356.6150000012… But I cannot find any evidence to support my hypothesis. J  Perhaps we can change 21.615 to another number not ending in 5 to avoid unnecessary confusion? PFE Section 2.4.3

Strings A string is a sequence of characters greeting = "Hello" "Hello" is a string with 5 characters # "Hello" is the value of the variable greeting # "Hello" is a string literal PFE Section 2.4

Alternative Notation 'Hello' is the same string as "Hello" print('He said "Hello" today') # The double quotes " are characters in the string Result: He said "Hello" today print("He said 'Hello' today") # The single quotes ' are characters in the string Result: He said 'Hello' today print("He said \"Hello\" and 'Goodbye' today") Result: He said "Hello" and 'Goodbye' today PFE Section 2.4.1

Length of a String The length of string is the number of characters in the string. The function len takes a string as an argument and returns the length of the string length1 = len("World") # the variable length1 is assigned the value 5 length2 = len("") # "" is the empty string # the variable length2 is assigned the value 0 PFE Section 2.4.1

Concatenation The + operator concatenates strings firstName = "Harry" lastName = "Morgan" name = firstName+lastName # name has the value "HarryMorgan" How to have "Harry Morgan" as the value of name? name = firstName+" "+lastName It is not possible to mix strings and numbers test = "Harry"+5 # error test = "Harry"+"5" PFE Section 2.4.2

Concatenation and Repetition The * operator can be used to repeat strings dashes = "-" * 10 # dashes has the value "----------" dashes = 10 * "-" # also possible What are the results? separator1 = "_" * 5 + "&" * 10 + "#" * 5 Result: '_____&&&&&&&&&&#####' separator2 = 3 * "@" + 2 * "w" * 5 + "9" * 4 Result: '@@@wwwwwwwwww9999' separator3 = 10.0 * '&' Result: error raceback (most recent call last): File "<pyshell#17>", line 1, in <module> separator = 10 * "@" + "s" * 3.0 TypeError: can't multiply sequence by non-int of type 'float' PFE Section 2.4.2

Convert Numbers to Strings Recall int and float convert strings to numbers The function str converts numbers to strings string1 = str(45) # string1 has the value "45" string2 = str(3E2) # string2 has the value "300.0" string3 = str(6+5) # string3 has the value "11" string4 = str("45") # string4 has the value "45" test = "Harry"+5 # error How to fix this? test = "Harry"+"5" test = "Harry"+str(5) # Which way is preferred? Why? string5 = str(pi) #string5 has the value "3.141592653589793" The second way is preferred. If we have two variables: name = “Harry” age = 5 test = name + age # error, mixing string with number To fix this, there is only the second way that is working. test = name + “age” # this doesn’t work as test would have the value of ”Harryage” test = name + str(age) # this works well PFE Section 2.4.3

String Indexing The characters on a string are indexed left to right, starting from 0 Individual characters can be extracted from a string name = "Harry" first = name[0] # first has the value "H" last = name[4] or last = name[-1] # last has the value "y" other = name[5] # error H a  r y 1 2 3 4 PFE Section 2.4.4

String Operations Statement Result Comment string="Py" string = string+"thon" string is set to "Python" When applied to strings, + denotes concatenation  print("Please" + " enter your name: ") Prints Please enter your name: Use concatenation to break up strings that don’t fit onto one line team = str(49)+"ers" team is set to "49ers" Because 49 is an integer it must be converted to a string greeting = "H & S" n = len(greeting) n is set to 5 Each space counts as one character string = "Sally" ch = string[1] ch is set to "a" Note that the initial position has index 0 last = string[len(string)-1] last is set to the string containing the last character in string The last character has position len(string)-1 PFE Section 2.4.4

Escape Sequences \", \n, \\ string = "He said \"Hello\"" # Each \" is treated as a single character – the double quote. len(string)? # The value of string has 15 characters print("*\n**\n***") # Each \n produces a new line. The result is * ** *** len("*\n**\n***")? # 8 print("\\") # prints \ PFE Section 2.4.5

A Motivation Example price1 = 23.789 price2 = 0.039 price3 = 199.8 desired output print(price1) print(price2) print(price3) print(price4) print(price5) actual output PFE Section 2.5.3

String Format Operator % formatString % value  this is a string! "%.2f" % price # create a string containing the value of price # correct to two decimal places. f is for float. # The rightmost % is the string format operator. price = 10.809 string = "%.2f" % price # value of string is "10.81" price = 10.809 #price is at most of two decimal places. PFE Section 2.5.3

Vocabulary "%m.nf" is the format string %m.nf is the format specifier m is the field width % (outside the format string) is the string format operator Apply the format string on a floating number Compare the following three format specifiers %m.nf %m.f %.nf PFE Section 2.5.3

Examples value = 56.68 "%0.3f" % value # the result is the string "56.680" "%8.3f" % value # the result is the string " 56.680" # Note that " 56.680" has two spaces on the left, to ensure # that the length of the string is 8, not 6 "%4.3f" % value # Note that "56.680" has length 6, not 4 PFE Section 2.5.3

A Motivation Example price1 = 23.789 price2 = 0.039 price3 = 199.8 desired output print(price1) print(price2) print(price3) print(price4) print(price5) actual output PFE Section 2.5.3

A Motivation Example price1 = 23.789 price2 = 0.039 price3 = 199.8 formatPrice = "%6.2f" print(formatPrice % price1) print(formatPrice % price2) print(formatPrice % price3) print(formatPrice % price4) print(formatPrice % price5) PFE Section 2.5.3

A Motivation Example price1 = 23.789 price2 = 0.039 price3 = 199.8 formatPrice = "%8.2f" print(formatPrice % price1) print(formatPrice % price2) print(formatPrice % price3) print(formatPrice % price4) print(formatPrice % price5) PFE Section 2.5.3

Integers and Strings For integers use %d or %nd, for example price = 105 string1 = "%5d" % price # result " 105" string2 = "%2d" % price # result "105" For strings use %s or %ns, for example string3 = "%7s" % "Hello" # result " Hello" PFE Section 2.5.3

More Examples Format String Sample output ~ is a space Comments "%d"  24 Use d with an integer  "%5d"  ~~~24 Spaces are added so that the field width is 5 "%05d"  00024 If you add 0 before the field width, zeroes are added instead of spaces.  "Quantity:%5d"  Quantity:~~~24 Characters inside a format string but outside the format specifier appear in the output.  “%.f"  1.21997 Use f with a floating point number  "%.2f"  1.22 Prints two digits after the decimal point  "%7.2f"  ~~~1.22 Spaces are added so that the field width is 7  "%s"  Hello Use s with a string  “%9s"  ~~~~Hello Strings are right-justified by default  "%-9s"  Hello~~~~ Use a negative field width to left-justify  "%d %.2f"  24~1.22 You can format multiple values at once  "%d%%"  24% To add a percentage sign to the output, use %% PFE Section 2.5.3

Multiple Format Specifiers Syntax for the string format operator formatString % (value_1, value_2, .., value_n) The format string must contain n format specifiers, one for each value. If there is only one value then the brackets can be omitted, formatString % value Example quantity = 100 total = 509.371 print("Quantity: %d Total: %10.2f" % (quantity, total)) # prints "Quantity: 100 Total: 509.37" PFE Section 2.5.3

Example title = "Quantity" print("%10s %8d" % (title, 24)) # “~~Quantity~~~~~~24“ print ("%-10s %8d" % (title, 24)) # "Quantity~~~~~~~~24“ Note that ~ represents a space. 10 widths 8 widths 10 widths 8 widths PFE Section 2.5.3

A Motivation Example price1 = 23.789 item1 = "Teddy" price2 = 0.039 item2 = "GingerBreadMan" item3 = "Mickey" item4 = "Pony" item5 = "Sam" print(item1, price1) print(item2, price2) print(item3, price3) print(item4, price4) print(item5, price5) PFE Section 2.5.3

A Motivation Example formatItemPrice = "%14s %8.2f" #or alternatively, #formatItem = "%14s" #formatPrice = "%8.2f" #formatItemPrice = formatItem+" "+formatPrice print(formatItemPrice % (item1, price1)) print(formatItemPrice % (item2, price2)) print(formatItemPrice % (item3, price3)) print(formatItemPrice % (item4, price4)) print(formatItemPrice % (item5, price5)) item1 = "Teddy" item2 = "GingerBreadMan" item3 = "Mickey" item4 = "Pony" item5 = "Sam" Or print(str(formatItem+" "+formatPrice) % (item1, price1)) PFE Section 2.5.3

A Motivation Example formatItemPrice = "%-14s %8.2f" #or alternatively, #formatItem = "%-14s" #formatPrice = "%8.2f" #formatItemPrice = formatItem+" "+formatPrice print(formatItemPrice % (item1, price1)) print(formatItemPrice % (item2, price2)) print(formatItemPrice % (item3, price3)) print(formatItemPrice % (item4, price4)) print(formatItemPrice % (item5, price5)) item1 = "Teddy" item2 = "GingerBreadMan" item3 = "Mickey" item4 = "Pony" item5 = "Sam" Or print(str(formatItem+" "+formatPrice) % (item1, price1)) PFE Section 2.5.3

A Motivation Example formatItemPrice = "%-14s: %8.2f" #or alternatively, #formatItem = "%-14s" #formatPrice = "%8.2f" #formatItemPrice = formatItem+“: "+formatPrice print(formatItemPrice % (item1, price1)) print(formatItemPrice % (item2, price2)) print(formatItemPrice % (item3, price3)) print(formatItemPrice % (item4, price4)) print(formatItemPrice % (item5, price5)) item1 = "Teddy" item2 = "GingerBreadMan" item3 = "Mickey" item4 = "Pony" item5 = "Sam" Or print(str(formatItem+“: "+formatPrice) % (item1, price1)) PFE Section 2.5.3

Format Specifier Summary formatString % value ~ represents a space e.g., print(“%.f” % 35.678), print(“%d” % -5), or print(“%s” % “hello”) formatString value (float) 35.678 (int) -5 (string) “hello” float (round) “%.f” “36” “-5” error “%.2f” “35.68” “-5.00” “%6.1f” “~~35.7” “~~-5.0” “%07.2f” “0035.68” “-005.00” int (trunc) “%d” “35” “%5d” “~~~35” “~~~-5” “%-5d” “35~~~” “-5~~~” string “%s” “35.678” “hello” “%7s” ~35.678” “~~~~~-5” “~~hello” “%3s” “~-5”

PFE Review questions, Ch 2 Programming Exercise 1 R2.15. Write pseudocode for a program that computes the first and last digit of a number. For example, if the input is 23456 the program should print 2 and 6. Use % and log(x, 10). PFE Review questions, Ch 2

PFE Review questions, Ch 2 Programming Exercise 1 R2.15. Write pseudocode for a program that computes the first and last digit of a number. For example, if the input is 23456 the program should print 2 and 6. Use % and log(x, 10). number = int(input("Please enter a number:")) digits = int(log(number, 10)) #digits is the (number of digits of the number – 1) firstDigit = int(number//10**digits) lastDigit = number%10 # if number is an integer PFE Review questions, Ch 2

PFE Review questions, Ch 2 Programming Exercise 1 R2.15. Write pseudocode for a program that computes the first and last digit of a number. For example, if the input is 23456 the program should print 2 and 6. Use % and log(x, 10). numberStr = input(Please enter a number:) firstDigit=int(numberStr[0]) lastDigit= int(numberStr[-1]) The program is valid for positive numbers only. It can be a floating point number. PFE Review questions, Ch 2

PFE Review questions, Ch 2 Programming Exercise 2 R2.21.How do you get the first character of a string? The last character? The middle character (if the length is odd)? The middle two characters (if the length is even)? Harry: middle r Potter: middle tt PFE Review questions, Ch 2

PFE Review questions, Ch 2 Programming Exercise 2 R2.21.How do you get the first character of a string? The last character? The middle character (if the length is odd)? The middle two characters (if the length is even)? inputStr = input("Please input a string:) firstChar = inputStr[0] lastChar = inputStr[-1] midChar = inputStr[(len(inputStr)-1)/2]# if length is odd midChar1 = inputStr[len(inputStr)/2-1] # if length is even midChar2 = inputStr[len(inputStr)/2] PFE Review questions, Ch 2