Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
30 views

Python PPT Lesson 4

Uploaded by

printerkey12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Python PPT Lesson 4

Uploaded by

printerkey12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Lesson 4: Numbers and Strings

• Data are essential building blocks of any computer program. In this lesson, we will
be exploring numerical values, Boolean values, text strings, lists, tuples, and sets.

Objectives
After studying this lesson, you should be able to:
• list the number data types in Python;
• work with text strings; and
• create sets and lists.
Numbers
The most common numerical data types used in programming are integers and floating-point
numbers.

Integers => are made up of whole numbers, their negative counterparts, and zero.
=> are composed of a sequence of digits. Simply entering any digit specifies an
integer value.

Try entering the following lines in the interpreter:

In previous versions of Python, integer sizes were limited by the operating system, whether it
is 32- or 64-bit. In Python 3, integers can be as large as possible. However, there some rules
you have to follow when using integers.
INTEGERS
Rules to follow when using integers:
• Negative integers are specified by starting the sequence with a minus sign.

• You can’t start with a zero (digit) otherwise, it will return a SyntaxError message.
Example:

An exception to this is when you use another base such as Example:


binary (base 2), octal (base 8), or hexadecimal (base 16). You
use 0b or 0B prefix for binary, 0o or 0O for octal, and 0x or 0X
for hexadecimal.
INTEGERS
Rules to follow when using integers:

• You also will not be able to include commas in your specification. If you try to enter
commas in a sequence of digits, you will get a tuple.

Example:

• You can insert underscores within the sequence as digit separators, and they will be
ignored by the interpreter.

Example:
INTEGERS
You can perform mathematical operations on integers.
INTEGERS
Enter the following lines in the interpreter and see their results. The floating-point
division will result in a float value (with a decimal point) if the result is not an exact
integer. Floor (or integer) division basically leaves out the decimal values. Modulo (%)
returns the remainder of a division

See what happens when you try to divide by zero.

You can assign variable names to integer


objects. Once you do, you can perform
integer operations on these variables.
Example:
INTEGERS

Note that Python arithmetic follows PEMDAS precedence rules. However, know that there
are also other operators (bitwise and logical) that can be used in programming and may
affect precedence.

Before entering the following code in the interpreter, try to figure out what the result will be.
FLOATING-POINT
Floating-point => numbers or floats are numerical values with decimal points.
=> To specify a float value, include a decimal point (.) to a
digit or sequence of digits.
=> You don’t even have to include a preceding or succeeding
zero to the decimal point.
FLOATING-POINT
Floating-point => can also take underscores to separate the digits

Example:

Like integers, you can perform mathematical operations on floats and the variables
assigned to them.
Example:
FLOATING-POINT
• When you perform an operation between a float and an integer value, the result will
be a float.
Python code using IDLE Shell:
Example:

Python code: Output:


FLOATING-POINT
• You can also convert the specified values of variables from integers to floats and vice
versa using the float() and int() functions.

Example:
Python code using IDLE Shell:
Python code: Output:
FLOATING-POINT
Let’s try converting a variable’s referenced value from float to integer.

Example:
Python code using IDLE Shell:
Python code: Output:
FLOATING-POINT
Note that these functions do not affect an object’s mutability. The specified values do
not change IDs.
Python code using IDLE Shell:
Example:
Python code: Output:
BOOLEAN
A Boolean value is either True or False. Try these lines in the interpreter:

A Boolean value is used in logical operations to


represent and evaluate the truth or falsehood of
expressions.

❑ To get the boolean values of other data types,


use the bool() function.
o Nonzero numbers are treated as True.
o Zero-valued numbers are treated as False.
STRINGS
Strings are composed of a sequence of Example 1:
characters. They are specified by
enclosing characters in quotation marks.
You can use either single (‘) or double (“)
quotes.

Example 2:
When you want to include quotation
marks as part of your string, you can
use the single quotes within double
quotes and vice versa.
STRINGS
Multiline Strings Example 1
You can also specify multi-line
strings using three quotation
marks. To move to the next
line in the interpreter, press
Shift + Enter.

Let’s see how the multiline string


value is stored:
STRINGS

Escape and Whitespace Characters


Notice how there are a bunch of “\n” in
the string. The backslash ( \ ) is an
escape character. It is used to insert
whitespace characters to the string. “\n”
creates a new line. To display the value
in a more human friendly format, use the
print() function.
STRINGS
Here are some other escape characters that you can use in strings:
• \n - new line
• \r - carriage return
• \t - tab
• \ ‘ - single quote Python code using IDLE Shell:
• \ \ - backslash
Example:
Python code:
Output:
STRINGS
Concatenation and Multiplication
• You can also perform some “operations” with strings. Using + concatenates or joins
string values together. Python does not add a space when concatenating two string
values. So you have to add the space manually.
Example:

You can also multiply strings. What it does is:

Example:
STRINGS
Offset and Slice
• You can also get a specific character within a string based on its position in the
sequence using offset. Offset is represented by a bracket symbol ( [] ).
• Keep in mind that the index starts at 0, so if you want to get the third character, you
use 2 as offset.

Python code:
Output:
STRINGS
Offset and Slice

Python code using IDLE Shell:


STRINGS
• Slice
You can also get a particular segment using slice. Like offset, you can define a
slice using brackets ( [] ) and colon ( : ).
[:] - gets the entire sequence from start [: end] - gets all the characters until
to end before the chosen endpoint
Example: Example:

[start :] - gets all the characters from the [start : end] - gets characters from the
start point of the slice until the end of start until before the endpoint
the sequence Example:
Example:
STRINGS
• Slice
You can also get a particular segment using slice. Like offset, you can define a slice
using brackets ( [] ) and colon ( : ).

[start: end: step] - gets characters from start until before the endpoint, skipping
every number of characters set by the step

Example:
STRINGS
• Slice
Example:
Python code:

Output:
STRINGS
• Slice
Example:
Python code using IDLE Shell:
STRINGS
▪ Length
Python also has other built-in functions that can be used to manipulate and
gather information from string values. For example, you can get the length of a
string using the len() function.
len() function counts the number of characters and returns the result as an integer value.

Examples:

Note that the len() function can also be used with other data types such as tuples, list,
sets, arrays, and dictionaries.
STRINGS
▪ STRIP
You can “clean up” a string from excess whitespace characters using the strip()
method. Methods are like functions that are associated with the object.

The strip() method is a procedure for strings.


Example:
o strip() - Strips whitespace characters on both sides
o lstrip() - Strips whitespace characters on the left
o rstrip() - Strips whitespace characters on the right
STRINGS
▪ STRIP
Note that this does not modify the original
value associated with the variable name.

Try checking the variable and see that


the associate value remains the same:

You can also indicate a sequence of characters as


an argument. Python will locate these characters
at the selected ends and remove them from the
string
STRINGS
• Split and Join
• If you do not indicate a separator, Python will try to use whitespaces to separate
the string into a list.

Let’s try this example with different whitespace characters and see how the
split() method will turn the string value into a list.

Example:
STRINGS
• Split and Join
You can also bring together list items to form a string value using the join() method.

For example, we will join the items in the grocery list using a comma (,) .

Python code:

Output:

Python code using IDLE Shell:


STRINGS
• REPLACE
The replace() method is another handy string method. The method can take on
three arguments:
• the string you want to be replaced,
• the string you want to replace it with, and
• (optional) the number of times the replacement would occur.
Example:

If you do not set the optional parameter, it will replace all instances it can find.
STRINGS
• REPLACE
Please note that like the previous methods, replace() method does not alter the
original value.

Example:
STRINGS
• CASE
We can also change the case of the characters in the string using the following
methods:
Example:
• capitalize() - Capitalizes the first word of the string
• title() - Capitalizes the first letter of each word
• upper() - Capitalizes all the letters in the string
• lower() - Converts the letters to lowercase
• swapcase() - Changes the case from upper to
lowercase and vice versa

Note that these methods do not change the original


string’s value.
THE input() FUNCTION
In Python, we use the input() function to take input from the user. Whatever you enter as
input, the input function converts it into a string. If you enter an integer value still input()
function converts it into a string.

• The input() function allows us to show a prompt and have the user provide or
type some information that goes in a Python variable.

• The parameter to input() is a prompt string that prints out, prompting the user
what they are supposed to type. Adding a space at the end of the prompt string
looks best.

SYNTAX: input(prompt)

Example: input(‘What is your name? ‘)


THE input() FUNCTION
• User Input in Python
In this example, we are taking input from the user and input user data as a string in Python
with a prompt and printing it.
Example:
Python code: Output:
THE input() FUNCTION
By default input() function helps in taking user input as a string.
If any user wants to take input as integer , we just need to convert it using the int() function

• Convert User Input to a Number by adding the int() function


Example:
Python code: Output:
THE input() FUNCTION
By default input() function helps in taking user input as a string.
If any user wants to take input as float, we just need to convert it using the float() function.

• Take float input in Python


Example:
Python code:

Output:
THE input() FUNCTION
• Using string, int and float for the user’s input
Python code: Output:
END OF SLIDES

You might also like