[go: up one dir, main page]

0% found this document useful (0 votes)
36 views20 pages

Slide 3

This document provides an introduction to Python strings and input/output functions. It discusses string literals, escape codes, string methods like lower(), upper(), title(), format(), split(), and the input() function for user input. It also covers converting string input to numeric types using int() and formatting output using print() and the format() method. Examples are provided for common string and input/output tasks in Python.

Uploaded by

jesubayoemmanuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views20 pages

Slide 3

This document provides an introduction to Python strings and input/output functions. It discusses string literals, escape codes, string methods like lower(), upper(), title(), format(), split(), and the input() function for user input. It also covers converting string input to numeric types using int() and formatting output using print() and the format() method. Examples are provided for common string and input/output tasks in Python.

Uploaded by

jesubayoemmanuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

GETTING STARTED WITH PYTHON

MICHEAL OGUNDERO
EMAIL – OGUNDEROAYODEJI@GMAIL.COM
QUESTIONS FROM LAST CLASS

1. What are comments for?


2. How is a multiline comment written?
3. List two rules for naming an identifier.
4. What is the symbol for ‘not equal to’ and ‘equal to’ in Python?
5. Suggest a suitable variable name to store the following:
○ The brands of laptops available in a store.
○ Books that you like.
○ Number of students in a class.
○ Total sales in a store.
STRINGS II

Triple Quoted String Literals


• Strings delimited by one quote character, like ’, are required to lie within a single Python line. It is
sometimes convenient to have a multi-line string, which can be delimited with triple quotes,

sillyTest = '''Say, "I'm in!"


This is line 3'''
print(sillyTest)
• The line structure is preserved in a multi-line string. As you can see, this also allows you to embed both
single and double quote characters!
STRINGS II

Escape Codes
• Now try to output sillyTest again
sillyTest
• The answer looks strange! It indicates an alternate way to encode the string internally in Python using
escape codes.
• Escape codes are embedded inside string literals and start with a backslash character \.
• They are used to embed characters that are either unprintable or have a special syntactic meaning to
Python that you want to suppress.
Below is some of the escommon escape codes
Escape Meaning
code
\\ Backslash
\n Newline
\’ Single quote character
\” Double quote character

print('a\nb\n\nc')
EXERCISE

Create a Python script that uses escape characters to format and print the following text:

My favorite programming languages:


1. Python
2. Java
3. C++
STRING METHODS

A method is a function that “belongs to” an object. String Methods are functions that belong to the string
object.
Methods are specific to the data type for a particular variable. So there are some built-in methods that
are available for all strings, different methods that are available for all integers, etc.
They are called using dot notation.
For example, lower() is a string method that can be used like this, on a string called "sample string":
sample_string.lower().

sample_string = 'Sample string'


print(sample_string.lower())
print(sample_string.upper())
print(sample_string.title())
STRING METHODS

Below is an image that shows some methods that are possible with any string.

person = input('Enter your name: ')


print('Hello ', person, '!')

Each of these methods accepts the string itself as the first argument of the method. However, they also
could receive additional arguments, that are passed inside the parentheses.

my string = 'Sebastian thrun'


my_string.islower() # True
my_string.count('a') # 2
my_string.find('a') # 3
STRING METHODS: format()

This method is very useful with print statements. It is used to format the output of a string.
For example, lower() is a string method that can be used like this, on a string called "sample string":
sample_string.lower().

print("Mohammed has {} balloons".format(27))


# Mohammed has 27 balloons

animal = "dog"
action = "bite"
print("Does your {} {}?".format(animal, action))
# Does your dog bite?

maria_string = "Maria loves {} and {}"


print(maria_string.format("math", "statistics"))
# Maria loves math and statistics

Notice how in each example, the number of pairs of curly braces {} you use inside the string is the same
as the number of replacements you want to make using the values inside format()
STRING METHODS: split()

This method returns a data container called a list that contains the words from the input string.
The split method has two additional arguments (sep and maxsplit).
The sep argument stands for "separator". It can be used to identify how the string should be split up (e.g.,
whitespace characters like space, tab, return, newline; specific punctuation (e.g., comma, dashes)). If the sep
argument is not provided, the default separator is whitespace.
True to its name, the maxsplit argument provides the maximum number of splits. The argument gives
maxsplit + 1 number of elements in the new list, with the remaining string being returned as the last
element in the list.

new_str = "The cow jumped over the moon."


new_str.split() # ['The', 'cow', 'jumped', 'over', 'the',
'moon.']

new_str.split(' ', 3)
# ['The', 'cow', 'jumped', 'over the moon.']

new_str.split('.')
# ['The cow jumped over the moon', '']
EXERCISE

Below, we have a string variable that contains the first verse of a poem. Remember, \n is a special
sequence of characters that causes a line break (a new line).

verse = "If you can keep your head when all about you\n Are losing theirs and blaming it on you,\nIf you
can trust yourself when all men doubt you,\n But make allowance for their doubting too;\nIf you can wait
and not be tired by waiting,\n Or being lied about, don’t deal in lies,\nOr being hated, don’t give way to
hating,\n And yet don’t look too good, nor talk too wise:"
Answer the following questions about verse using python code and properly formatting your output:

1. What is the length of the string variable verse?


2. What is the index of the first occurrence of the word 'and' in verse?
3. What is the index of the last occurrence of the word 'you' in verse?
4. What is the count of occurrences of the word 'you' in the verse?
5. Replace all appearances of ‘you’ with ‘me’.
6. Split the verse on every newline.
7. Seperate the verse by commas.
INPUT AND OUTPUT

The Input Function


• Programs are only going to be reused if they can act on a variety of data.
• One way to get data is directly from the user.

person = input('Enter your name: ')


print('Hello ', person, '!')

• That is what the built-in function input does:


i. First it prints the string you give as a parameter(in this case ’Enter your name: ’ ),
ii. and then it waits for a line to be typed in, and returns the string of characters you typed.
• The parameter inside the parentheses after input is important.
• It is a prompt, prompting you that keyboard input is expected at that point, and hopefully indicating
what is being requested.
• Without the prompt, the user would not know what was happening, and the computer would just sit
there waiting!
INPUT AND OUTPUT

The Input Function

applicant = input("Enter the applicant's name: ")


interviewer = input("Enter the interviewer's name: ")
time = input("Enter the appointment time: ")
print(interviewer, "will interview", applicant, "at", time)

• The statements are executed in the order they appear in the text of the program: sequentially. This is
the simplest way for the execution of the program to flow.You will see instructions later that alter that
natural flow.
INPUT AND OUTPUT

Print with Keyword Parameter sep


• One way to put punctuation but no space after the person in hello_you.py is to use the plus operator,
+. Another approach is to change the default separator between fields in the print function.

'''Hello to you! Illustrates sep with empty string in print. '''


person = input('Enter your name: ‘)
print('Hello ', person, '!', sep='')
INPUT AND OUTPUT

Numbers and Strings of Digits


• Consider the following problem: Prompt the user for two numbers, and then print out a sentence
stating the sum. For instance if the user entered 2 and 3, you would print ‘The sum of 2 and 3 is 5.’
'''Error in addition from input.'''
x = input("Enter a number: ")
y = input("Enter a second number: ")
print('The sum of ', x, ' and ', y, ' is ', x+y, '.', sep='')
Can someone explain this?

Needing to convert string input to numbers is a common situation, both with keyboard input and later in
web pages.
xString = input("Enter a number: ")
x = int(xString)
yString = input("Enter a second number: ")
y = int(yString)
print('The sum of ', x, ' and ', y, ' is ', x+y, '.', sep='')
INPUT AND OUTPUT

Numbers and Strings of Digits


• Immediate conversion
'''Two numeric inputs, with immediate conversion'’’
x = int(input("Enter a number: "))
y = int(input("Enter a second number: "))
print('The sum of ', x, ' and ', y, ' is ', x+y, '.', sep=‘ ')

Naming a variable that ‘sum’

'''Two numeric inputs, explicit sum'’’


x = int(input("Enter an integer: "))
y = int(input("Enter another integer: "))
sum = x+y
print('The sum of ', x, ' and ', y, ' is ', sum, '.', sep=‘ ')
Exercise

Write a program that asks for three numbers, and lists all three, and their sum.
INPUT AND OUTPUT

String Format Operation


• There is a particular operation on strings called format, that makes substitutions into places enclosed in
braces

'''Hello to you! Illustrates format with {} in print. '''


person = input('Enter your name: ‘)
greeting = 'Hello, { }!'.format(person)
print(greeting)

• the object is the string ’Hello { }!’. The method is named format. There is one further parameter,
person.

person = input('Enter your name: ')


print('Hello {}!'.format(person))
INPUT AND OUTPUT

String Format Operation


• There are multiple places to substitute, and the format approach can be extended to multiple
substitutions
• Each place in the format string where there is ’{}’, the format operation will substitute the value of the
next parameter in the format parameter list

'''Compare print with concatenation and with format string.'''


applicant = input("Enter the applicant's name: ")
interviewer = input("Enter the interviewer's name: ")
time = input("Enter the appointment time: ")
print(interviewer + ' will interview ' + applicant + ' at ' + time +'.')
print(interviewer, ' will interview ', applicant, ' at ', time, '.', sep=’’)
print(‘{ } will interview { } at { }.'.format(interviewer, applicant, time))
INPUT AND OUTPUT

String Format Operation


• Since braces have special meaning in a format string, there must be a special rule if you want braces to
actually be included in the final formatted string. The rule is to double the braces: ’{{’ and ’}}’.

'''Illustrate braces in a formatted string.'''


a=5
b=9
setStr = 'The set is {{{ }, { }}}.'.format(a, b) print(setStr) c

• Optional elaboration with explicitly numbered entries Imagine the format parameters numbered in
order, starting from 0. In this case 0, 1, and 2. The number of the parameter position may be included
inside the braces

print('{0} will interview {1} at {2}.'.format(interviewer, applicant, time))


EXERCISE

1. Declare a string and count the number of occurrences of a specific character.


2. Create a program that prompts the user to enter a word and prints the length of the word.
3. Create a program that takes a user's name and age as input and prints a message using string
formatting.
4. Ask the user to enter two numbers. Perform addition, subtraction, multiplication, and division, and
print the results.

You might also like