Chapter 1: Python Basics
Introduction
• Programs consist of statements to be run one after the other. A
statement describes some action to be carried out.
Input/output
• Basic output
• The print() function displays output to the user. Output is the information
or result produced by a program.
• The sep and end options can be used to customize the output
• Multiple values, separated by commas, can be printed in the
same statement. By default, each value is separated by a space
character in the output.
• The sep option can be used to change this behavior.
• By default, the print() function adds a newline character at the
end of the output
• The end option can be used to continue printing on the same line.
Input/output
Input/output
Input/output
Basic input
• Computer programs often receive input from the user.
• Input is what a user enters into a program.
• An input statement, variable = input("prompt"), has three parts:
• A variable refers to a value stored in memory.
• The input() function reads one line of input from the user. A function is a
named, reusable block of code that performs a task when called. The
input is stored in the computer's memory and can be accessed later using
the variable.
• A prompt is a short message that indicates the program is waiting for
input.
Input/output
Data Types
• When we create a data item we can either assign it to a variable, or
insert it into a collection.
• Variables allow programs to refer to values using names rather than
memory locations.
• When we assign in Python, what really happens is that we bind an
object reference to refer to the object in memory that holds the data.
• The names we give to our object references are called identifiers or
just plain names.
• A valid Python identifier is a nonempty sequence of characters of any
length that consists of a “start character” and zero or more
“continuation characters”.
Data Types
• The start character can be anything that Unicode considers to be a letter,
including the ASCII letters (“a”, “b”, …, “z”, “A”, “B”, …, “Z”), the underscore
(“_”), as well as the letters from most non-English languages.
• Each continuation character can be any character that is permitted as a start
character, or pretty well any nonwhite space character, including any
character that Unicode considers to be a digit, such as (“0”, “1”, …, “9”), or
the Catalan character “·”.
• Example: TAXRATE, Taxrate, TaxRate, taxRate, and taxrate are five different
identifiers.
Data Types
• The second rule is that no identifier can have the same name as
one of Python’s keywords
Data Types
• Names that begin and end with two underscores (such as __lt__)
should not be used. Python defines various special methods and
variables that use such names
Integral Types
• Python provides two built-in integral types, int and bool.
• Both integers and Booleans are immutable
• When used in Boolean expressions, 0 and False are False, and any other
integer and True are True.
• When used in numerical expressions True evaluates to 1 and False to 0.
x=5
print(id(x)) # e.g. 140711053364144
x=x+1
print(x) # 6
print(id(x)) # e.g. 140711053364176 → different from previous
Integral Types
• The size of an integer is limited only by the machine’s memory
• C and java has limitation (32 bits)
• Integer literals are written using base 10 (decimal) by default
Integral Types
• All the binary numeric operators (+, -, /, //, %, and **) have
augmented assignment versions (+=, -=, /=, //=, %=, and **=)
where x op= y is logically equivalent to x = x op y in the normal
case when reading x’s value has no side effects.
• All the binary bitwise operators (|, ^, &, <<, and >>) have
augmented assignment versions (|=, ^=, &=, <<=, and >>=) where
i op= j is logically equivalent to i = i op j in the normal case when
reading i’s value has no side effects.
Integral Types
Integral Types
• Boolean:
• There are two built-in Boolean objects: True and False
# Case 1: No arguments
print("bool() →", bool()) # Returns False
# Case 2: Passing a bool
a = True
print("bool(True) →", bool(a)) # Returns True (copy of the bool)
# Case 3: Passing other types
print("bool(0) →", bool(0)) # False (0 is considered False)
print("bool(1) →", bool(1)) # True
print("bool('') →", bool('')) # False (empty string is False)
print("bool('hello') →", bool('hello')) # True
print("bool([]) →", bool([])) # False (empty list)
print("bool([1, 2, 3]) →", bool([1, 2, 3])) # True (non-empty list)
Floating-Point Types
• Python provides three kinds of floating-point values: the built-in
float and complex types,and the [Link] type from the
standard library
• All three are immutable.
• Type float holds double-precision floating-point numbers whose
range depends on the C
• Numbers of type float are written with a decimal point, or using
exponential notation
• for example, 0.0, 4., 5.7, -2.5, -2e9, 8.9e-4.
Floating-Point Types
• The float data type can be called as a function
• with no arguments it returns 0.0
• with a float argument it returns a copy of the argument
• and with any other argument it attempts to convert the given object to a
float.
• Floating-point numbers can be converted to integers using the
• int()
• round()
• [Link]() or [Link]()
• The float.is_integer() method returns True if a floating-point
number’s fractional part is 0
Floating-Point Types
print("float() →", float()) # No arguments → 0.0
print("float(3.14) →", float(3.14)) # With float → returns same
print("float('2.718') →", float('2.718’)) # String → converted to float
x = 5.75
print("int(x) →", int(x)) # Truncates decimal
print("round(x) →", round(x)) # Rounds to nearest int
print("[Link](x) →", [Link](x)) # Down
print("[Link](x) →", [Link](x)) #Up
Floating-Point Types
print("float(3.0).is_integer() →", float(3.0).is_integer()) # True
print("float(3.14).is_integer() →", float(3.14).is_integer())# False
Floating-Point Types
• The complex data type is an immutable type that holds a pair of
floats, one representing the real part and the other the imaginary
part of a complex number.
• Literal complex numbers are written with the real and imaginary
parts joined by a + or - sign, and with the imaginary part followed
by a j.
• Here are some examples: 3.5+2j, 0.5j, 4+0j, -1-3.7j.
• Notice that if the real part is 0, we can omit it entirely.
Floating-Point Types
• The decimal module provides immutable Decimal numbers that
are as accurate as we specify.
• Calculations involving Decimals are slower than those involving
floats
Strings
• Strings are represented by the immutable str data type which
holds a sequence of Unicode characters.
• string objects—with no arguments it returns an empty string, with
a nonstring argument it returns the string form of the argument,
and with a string argument it returns a copy of the string.
• Strings are generally defined using single or double quotes
• In addition, we can use a triple quoted string
Strings
• If we want to use quotes inside a normal quoted string we can do
so without formality if they are different from the delimiting
quotes; otherwise, we must escape them:
Strings
• The solution is to use raw strings. These are quoted or triple quoted strings
whose first quote is preceded by the letter r. Inside such strings all characters
are taken to be literals, so no escaping is necessary.
• If we want to write a long string literal spread over two or more lines but
without using a triple quoted string there are a couple of approaches we can
take:
Slicing and Striding Strings
• Individual characters in a string, can be extracted using the item
access operator ([])
• Index positions into a string begin at 0 and go up to the length of
the string minus 1. But it is also possible to use negative index
positions—these count from the last character back toward the
first.
Slicing and Striding Strings
• The slice operator has three syntaxes:
• seq[start]
• seq[start:end]
• seq[start:end:step]
• The seq can be any sequence, such as a list, string, or tuple. The
start, end, and step values must all be integers (or variables
holding integers)
• The second syntax extracts a slice from and including the start-th
item, up to and excluding the end-th item.
Slicing and Striding Strings
Slicing and Striding Strings
String: Case Conversion
Method Description
[Link]() Converts all characters to uppercase
[Link]() Converts all characters to lowercase
[Link]() Capitalizes the first character
[Link]() Capitalizes the first character of each word
[Link]() Swaps case (upper to lower and vice versa)
String: Searching and Finding
Method Description
[Link](sub) Returns the index of first occurrence of sub, or -1
[Link](sub) Returns the index of last occurrence of sub, or -1
[Link](sub) Like find(), but raises ValueError if not found
[Link](sub) Counts how many times sub occurs
String: Check String Properties
Method Description
[Link]() True if all characters are letters
[Link]() True if all characters are digits
[Link]() True if all characters are alphanumeric
[Link]() True if all characters are whitespace
[Link]() / [Link]() True if all characters are lower/upper
[Link](sub) True if string starts with sub
[Link](sub) True if string ends with sub
String: Modifying and Formatting
Method Description
[Link](old, new) Replaces all occurrences of old with new
[Link]() Removes leading and trailing whitespace
[Link]() / [Link]() Removes whitespace from left/right
[Link](sep) Splits the string into a list (default: whitespace)
[Link](iterable) Joins elements of iterable using s as separator
[Link](width) Pads the string with zeros on the left
[Link](width) Centers the string in a field of given width
s = "abc123"
Strings: Examples print([Link]())
s = "banana" s = "abc 123"
index = [Link]("a") print([Link]())
print(index)
s = "abc@123"
s = "banana" print([Link]())
print([Link]("z"))
s = "hello world"
print([Link]("o")) s = " hello world "
s = "hello world" print([Link]())
print([Link]("z")) # Output: "hello world"
Strings: Examples
s = "##Hello##"
print([Link]("#"))
s = " hello world "
print([Link]())
# Output: "hello world"
items = ["apple", "banana", "cherry"]
result = ", ".join(items)
print(result)
Strings: Examples
s = "Python is fun"
words = [Link]()
r_words = ' '.join(words[::-1])
print(r_words)
Collection Data types
• A sequence type is one that supports the membership operator
(in), the size function (len()), slices ([]), and is iterable.
Collection Data Types: Tuples
• A tuple is an ordered sequence of zero or more object references.
• Tuples support the same slicing and striding syntax as strings
• Like strings, tuples are immutable, so we cannot replace or
delete any of their items.
• The tuple data type can be called as a function, tuple()—
• with no arguments it returns an empty tuple
• with a tuple argument it returns a copy of the argument
• and with any other argument it attempts to convert the given object to a
tuple.
Collection Data Types: Tuples
• An empty tuple is created using empty parentheses, (), and a tuple of
one or more items can be created by using commas.
• Tuples provide just two methods,
• [Link](x), which returns the number of times object x occurs in tuple t
• [Link](x), which returns the index position of the leftmost occurrence of object
x in tuple t—or raises a Value Error exception if there is no x in the tuple.
Collection Data Types: Tuples
• Animals= “dog”, “cat”, “tiger”, “lion”
• Animals[1:]
• Animals[-3:]
• >> Animals[:2], “elephant”, Animals[2:]
• >>Animals[:2] + (“elephant”,)+ Animals[2:]
Collection Data Types: Tuples
data = ("a", "b", "c", ("d", "e", "f"), "g", "h")
result = data[3][1:] + (data[1],) + data[-2:-5:-1]
print(result)
Collection Data Types: Tuples
Collection Data types: Named Tuples
• A named tuple behaves just like a plain tuple, and has the same
performance characteristics.
• What it adds is the ability to refer to items in the tuple by name as well
as by index position
• The collections module provides the namedtuple() function. This
function is used to create custom tuple data types. For example:
• The first argument to [Link]() is the name of the custom tuple
data type that we want to be created.
• The second argument is a string of space separated names, one for each item
that our custom tuples will take.
Collection Data types: Named Tuples
Sales[0][-1]
Collection Data Types: Lists
• A list is an ordered sequence of zero or more object references.
• Lists support the same slicing and striding syntax as strings and
tuples.
• Unlike strings and tuples, lists are mutable, so we can replace
and delete any of their items.
• It is also possible to insert, replace, and delete slices of lists.
Collection Data Types: Lists
• The list data type can be called as a function, list()—
• with no arguments it returns an empty list,
• with a list argument it returns a shallow copy of the argument,
• and with any other argument it attempts to convert the given object to a
list. It does not accept more than one argument.
Collection Data Types:
• A list comprehension is an expression and a loop with an
optional condition enclosed in brackets where the loop is used to
generate items for the list, and where the condition can filter out
unwanted items
Collection Data Types: Dictionaries
• A dict is an unordered collection of zero or more key–value pairs
whose keys are object references that refer to hash table objects,
and whose values are object references referring to objects of any
type
• Dictionaries are mutable, so we can easily add or remove items,
but since they are unordered they have no notion of index position
and so cannot be sliced or strided.
• Dictionaries can also be created using braces—empty braces, {},
• Nonempty braces must contain one or more comma separated
items, each of which consists of a key, a literal colon, and a value
Collection Data Types: Dictionaries
Collection Data Types: Dictionaries
• Because dictionaries have both keys and values, we might want to
iterate over a dictionary by (key, value) items, by values, or by
keys.
Control Structures and Functions
• Python provides conditional branching with if statements and
looping with while and for …in statements.
• Python also has a conditional expression—this is a kind of if
statement that is Python’s answer to the ternary operator (?:)
Control Structures and Functions
Control Structures and Functions
Control Structures and Functions (While loop)
• The else clause is optional. As long as the boolean_expression is
True, the while block’s suite is executed.
• If the boolean_expression is or becomes False, the loop
terminates, and if the optional else clause is present, its suite is
executed.
• else clause’s suite is always executed if the loop terminates
normally (break, return and exception)
Control Structures and Functions (While loop)
Control Structures and Functions (For loop)
• The expression is normally either a single variable or a sequence
of variables, usually in the form of a tuple. If a tuple or list is used
for the expression, each item is unpacked into the expression’s
items
Control Structures and Functions (For loop)
Exception Handling
• Catching and Raising Exceptions
• Exceptions are caught using try …except blocks, whose general
syntax is:
Exception Handling
• There must be at least one except block, but both the else and
the finally blocks are optional.
• The else block’s suite is executed when the try block’s suite has
finished normally—but it is not executed if an exception occurs.
• If there is a finally block, it is always executed at the end.
Exception Handling
• Each except clause’s exception group can be a single exception or
a parenthesized tuple of exceptions.
• For each group, the as variable part is optional; if used, the
variable contains the exception that occurred, and can be
accessed in the exception block’s suite.
• If an exception occurs in the try block’s suite, each except clause
is tried in turn.
• If the exception matches an exception group, the corresponding
suite is executed.
Exception Handling
Exception Handling
Exception Handling
Example Programs
Example Programs
Example Programs
Custom Functions
• Functions are a means by which we can package up and
parameterize functionality.
• Four kinds of functions can be created in Python:
• Global functions
• Local functions
• Lambda functions
• Methods
Custom Functions
• Global functions are accessible to any code in the same module
(i.e., the same .py file) in which the object is created.
• Local functions (also called nested functions) are functions that
are defined inside other functions. These functions are visible only
to the function where they are defined; they are especially useful
for creating small helper functions that have no use elsewhere.
• Lambda functions are expressions, so they can be created at
their point of use; however, they are much more limited than
normal functions.
Custom Functions
• Methods are functions that are associated with a particular data
type and can be used only in conjunction with the data type
• The general syntax for creating a (global or local) function is:
Custom Functions
Custom Functions
• This idiom of using default none must be used for dict and list
Custom Functions
• We can also use the sequence unpacking operator in a function’s
parameter list. This is useful when we want to create functions
that can take a variable number of positional arguments.
Custom Functions
• The function can be called with just positional arguments, for
example,
• sum_of_powers(1, 3, 5),
• or with both positional and keyword arguments,
• sum_of_powers(1, 3, 5, power=2).
Custom Functions
Lambda Functions
• Lambda functions are functions created using the following syntax:
lambda parameters: expression
• The parameters are optional, and if supplied they are normally just
comma separated variable names, that is, positional arguments
• Although the complete argument syntax supported by def statements
can be used.
• The expression cannot contain branches or loops cannot have a return
(or yield) statement
• The result of a lambda expression is an anonymous function. When a
lambda function is called it returns the result of computing the
expression as its result.
Lambda Functions