Python Refresher course
By:A.Shobharani
Shobha
Python - Numbers
Number data types store numeric values. They are
immutable data types, which means that changing the value
of a number data type results in a newly allocated object.
Number objects are created when you assign a value to
them. For example:
var1 = 1
var2 = 10
You can also delete the reference to a number object by
using the del statement. The syntax of the del statement is:
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using
the del statement. For example:
del var del var_a, var_b
Python - Numbers
Python supports four different numerical types:
int (signed integers): often called just integers or ints, are positive or
negative whole numbers with no decimal point.
long (long integers ): or longs, are integers of unlimited size, written like
integers and followed by an uppercase or lowercase L.
float (floating point real values) : or floats, represent real numbers and are
written with a decimal point dividing the integer and fractional parts. Floats
may also be in scientific notation, with E or e indicating the power of 10
(2.5e2 = 2.5 x 102 = 250).
complex (complex numbers) : are of the form a + bJ, where a and b are
floats and J (or j) represents the square root of -1 (which is an imaginary
number). a is the real part of the number, and b is the imaginary part.
Complex numbers are not used much in Python programming.
Number Type Conversion:
Type int(x)to convert x to a plain integer.
Type long(x) to convert x to a long integer.
Type float(x) to convert x to a floating-point number.
Type complex(x) to convert x to a complex number with real
part x and imaginary part zero.
Type complex(x, y) to convert x and y to a complex number
with real part x and imaginary part y. x and y are numeric
expressions
Mathematical Functions:
Function Returns ( description )
abs(x) The absolute value of x: the (positive) distance between x and zero.
ceil(x) The ceiling of x: the smallest integer not less than x
cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y
exp(x) The exponential of x: ex
fabs(x) The absolute value of x.
floor(x) The floor of x: the largest integer not greater than x
log(x) The natural logarithm of x, for x> 0
log10(x) The base-10 logarithm of x for x> 0 .
max(x1, x2,...) The largest of its arguments: the value closest to positive infinity
min(x1, x2,...) The smallest of its arguments: the value closest to negative infinity
modf(x) The fractional and integer parts of x in a two-item tuple. Both parts
have the same sign as x. The integer part is returned as a float.
pow(x, y) The value of x**y.
round(x [,n]) x rounded to n digits from the decimal point. Python rounds away from
zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
sqrt(x) The square root of x for x > 0
Random Number Functions:
Function Returns ( description )
choice(seq) A random item from a list, tuple, or string.
randrange ([start,] sto A randomly selected element from range(start,
p [,step])
stop, step)
random() A random float r, such that 0 is less than or equal to
r and r is less than 1
seed([x]) Sets the integer starting value used in generating
random numbers. Call this function before calling
any other random module function. Returns None.
shuffle(lst) Randomizes the items of a list in place. Returns
None.
uniform(x, y) A random float r, such that x is less than or equal to
r and r is less than y
Trigonometric Functions:
Function Description
acos(x) Return the arc cosine of x, in radians.
asin(x) Return the arc sine of x, in radians.
atan(x) Return the arc tangent of x, in radians.
atan2(y, x) Return atan(y / x), in radians.
cos(x) Return the cosine of x radians.
hypot(x, y) Return the Euclidean norm, sqrt(x*x + y*y).
sin(x) Return the sine of x radians.
tan(x) Return the tangent of x radians.
degrees(x) Converts angle x from radians to degrees.
radians(x) Converts angle x from degrees to radians.
Mathematical Constants:
Constant Description
pi The mathematical constant pi.
e The mathematical constant e.
Numbers are
immutable
x 4.5
>>> x = 4.5
>>> y = x y
>>> y += 3
x 4.5
>>> x
4.5 7.5
>>> y y
7.5
shobha 9
Strings
• String is a sequence of characters.
• String may contain alphabets, numbers
and special characters.
• Usually strings are enclosed within a
single quotes and double quotes.
• Strings is immutable in nature.
• Example:
a=„hello world‟
b=“Python”
Problem Solving and Python Programming 10
Accessing Values in Strings:
Python does not support a character type; these are treated as
strings of length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with
the index or indices to obtain your substring:
Example:
var 1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
This will produce following result:
var1[0]: H
var2[1:5]: ytho
Updating Strings:
You can "update" an existing string by (re)assigning a variable to
another string. The new value can be related to its previous value or to
a completely different string altogether.
Example:
var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python'
This will produce following result:
Updated String :- Hello Python
String Literals: Many Kinds
• Can use single or double quotes, and three double
quotes for a multi-line string
>>> 'I am a string'
'I am a string'
>>> "So am I!"
'So am I!'
>>> s = """And me too!
though I am much longer
than the others :)"""
'And me too!\nthough I
am much longer\nthan
the others :)‘
>>> print s
And me too! 28
though I am shobha 1
3
Triple Quotes:
Python's triple quotes comes to the rescue by allowing strings
to span multiple lines, including verbatim NEWLINEs, TABs,
and any other special characters.
The syntax for triple quotes consists of three consecutive
single or double quotes.
para_str = """this is a long string that is made
up of several lines and non-printable characters
such as TAB ( \t ) and they will show up that way
when displayed. NEWLINEs within the string,
whether explicitly given like this within the
brackets [ \n ], or just a NEWLINE within the
variable assignment will also show up. """
print para_str;
Inbuilt String functions
• Python mainly contains 3 inbuilt string
functions.
• They are
– len()
– max()
– min()
• len()- Find out the length of characters in string
• min()- Smallest value in a string based on ASCII values
• max()- Largest value in a string based on ASCII values
Problem Solving and Python Programming 15
What is A SCII values
Problem Solving and Python Programming 16
Example for Inbuilt string
functions
name=input("Enter Your name:")
print("Welcome",name)
print("Length of your name:",len(name))
print("Maximum value of chararacter in your name",
max(name))
print("Minimum value of character in your
name",min(name))
Problem Solving and Python Programming 17
OUTPU
T
Enter Your name:PRABHAKARAN
Welcome PRABHAKARAN
Length of your name: 11
Maximum value of chararacter in your name
R Minimum value of character in your name
A
Problem Solving and Python Programming 18
Strings Concatenation
• The + operator used for string
concatenation.
Example:
a=“Hai”
b=“how are
you” c=a+b
print(c)
Problem Solving and Python Programming 19
Operators on String
• The Concatenate strings with the “*”
operator can create multiple concatenated
copies.
• Example:
>>> print("Python"*10)
PythonPythonPythonPythonPythonPython
PythonPythonPythonPython
Problem Solving and Python Programming 20
String Slicing
• Slicing operation is used to
return/select/slice the particular substring
based on user requirements.
• A segment of string is called slice.
• Syntax: string_variablename [ start:end]
Problem Solving and Python Programming 21
String Slice
example
H e l l o
s=“Hello” 0 1 2 3 4
-5 -4 -3 -2 -1
Problem Solving and Python Programming 22
Strings are immutable
• Strings are immutable character sets.
• Once a string is generated, you cannot
change any character within the string.
Problem Solving and Python Programming 23
String Comparision
• We can compare two strings using comparision
operators such as ==, !=, <,<=,>, >=
• Python compares strings based on
their corresponding ASCII values.
Problem Solving and Python Programming 24
Example of string comparision
str1="green"
str2="black"
print("Is both Equal:",
str1==str2) print("Is str1> str2:",
str1>str2) print("Is str1< str2:", OUTPUT:
str1<str2) Is both Equal: False
Is str1> str2: True
Is str1< str2: False
Problem Solving and Python Programming 25
String formatting operator
• String formatting operator % is unique
to strings.
• Example:
print("My name is %s and i secured %d
marks in python” % ("Arbaz",92))
• Output:
My name is Arbaz and i secured 92 marks
in python
Problem Solving and Python Programming 26
String functions and methods
len() min() max() isalnum() isalpha()
isdigit() islower() isuppe() isspace() isidentifier()
endswith() startswith() find() count() capitalize()
title() lower() upper() swapcase() replace()
center() ljust() rjust() center() isstrip()
rstrip() strip()
Problem Solving and Python Programming 27
i) Converting string functions
captitalize() Only First character capitalized
lower() All character converted to lowercase
upper() All character converted to uppercase
title() First character capitalized in each word
swapcase() Lower case letters are converted to
Uppercase and Uppercase letters
are converted to Lowercase
replace(old,new) Replaces old string with nre string
Problem Solving and Python Programming 28
Program:
str=input("Enter any string:")
print("String Capitalized:",
str.capitalize()) print("String lower
case:", str.lower()) print("String upper
case:", str.upper()) print("String title
case:", str.title()) print("String swap
case:", str.swapcase())
print("String replace case:",str.replace("python","python programming"))
Output:
Enter any string: Welcome to python
String Capitalized: Welcome to python
String lower case: welcome to python
String upper case: WELCOME TO PYTHON
String title case: Welcome To Python
String swap case: wELCOME TO PYTHON
String replace case: Welcome to python
Problem Solving and Python Programming 18
programming
ii)Formatting String functions
center(width) Returns a string centered in a field of given width
ljust(width) Returns a string left justified in a field of given width
rjust(width) Returns a string right justified in a field of given width
format(items) Formats a string
Problem Solving and Python Programming 30
Program:
a=input("Enter any string:")
print("Center alignment:",
a.center(20)) print("Left
alignment:", a.ljust(20))
print("Right alignment:",
a.rjust(20))
Output:
Problem Solving and Python Programming 31
iii) Removing whitespace
characters
Returns a string with
lstrip() leading whitespace
characters removed
Returns a string with
trailing whitespace
rstrip() characters removed
Returns a string with
leading and trailing
strip() whitespace characters
removed
Problem Solving and Python Programming 32
Program
a=input("Enter any string:")
print("Left space trim:",a.lstrip())
print("Right space trim:",a.rstrip())
print("Left and right
trim:",a.strip()) Output:
Problem Solving and Python Programming 33
iv) Testing
String/Character
Returns true if all characters in string are alphanumeric and there is
isalnum()
atleast one character
Returns true if all characters in string are alphabetic
isalpha()
Returns true if string contains only number character
isdigit()
Returns true if all characters in string are lowercase letters
islower()
Returns true if all characters in string are uppercase letters
isupper()
isspace() Returns true if string contains only whitespace characters.
Problem Solving and Python Programming 23
Program
a=input("Enter any string:")
print("Alphanumeric:",a.isalnum()
) print("Alphabetic:",a.isalpha())
print("Digits:",a.isdigit())
print("Lowecase:",a.islower())
Output:
print("Upper:",a.isupper())
Problem Solving and Python Programming 35
v) Searching for substring
Endswith() Returns true if the strings ends with the substring
Returns true if the strings starts with the substring
Startswith()
Returns the lowest index or -1 if substring not found
Find()
Count() Returns the number of occurrences of substring
Problem Solving and Python Programming 36
Program
a=input("Enter any string:")
print("Is string ends with thon:", a.endswith("thon"))
print("Is string starts with good:", a.startswith("good"))
print("Find:", a.find("ython"))
print("Count:", a.count(“o"))
Output:
Enter any string : welcome to python
Is string ends with thon: True
Is string starts with good: False
Find: 12
Count: 3
Problem Solving and Python Programming 37
String Modules
• String module contains a number of functions to
process standard Python strings
• Mostly used string modules:
string.upper()
string.upper()
string.split()
string.join()
string.replace()
string.find()
string.count()
Problem Solving and Python Programming 38
Example
import string
text="Monty Python Flying Circus"
print("Upper:", string.upper(text))
print("Lower:", string.lower(text))
print("Split:", string.split(text))
print("Join:", string.join(string.split(test),"+"))
print("Replace:", string.replace(text,"Python", "Java"))
print("Find:", string.find(text,"Python"))
print("Count", string.count(text,"n"))
Problem Solving and Python Programming 39
Output
Upper: “MONTY PYTHON FLYING CIRCUS”
Lower: “monty python flying circus”
Split: [„Monty‟, „Python‟, „Flying‟, „Circus‟]
Join : Monty+Python+Flying+Circus
Replace: Monty Java Flying Circus
Find: 7
Count: 3
Problem Solving and Python Programming 40
String Special Operators: Assume string variable a holds 'Hello' and variable
b holds 'Python' then:
Operator Description Example
+ Concatenation - Adds values on either a + b will give HelloPython
side of the operator
* Repetition - Creates new strings, a*2 will give -HelloHello
concatenating multiple copies of the
same string
[] Slice - Gives the character from the a[1] will give e
given index
[:] Range Slice - Gives the characters from a[1:4] will give ell
the given range
in Membership - Returns true if a H in a will give 1
character exists in the given string
not in Membership - Returns true if a M not in a will give 1
character does not exist in the given
string
r/R Raw String - Suppress actual meaning print r'\n' prints \n and
of Escape characters. print R'\n' prints \n
% Format - Performs String formatting See at next section
Raw String:
Raw strings don't treat the backslash as a special
character at all. Every character you put into a raw
string stays the way you wrote it:
print 'C:\\nowhere'
This would print following result:
C:\nowhere
Now let's make use of raw string. We would put
expression in r'expression' as follows:
print r'C:\\nowhere'
This would print following result:
C:\\nowhere
Unicode String:
Normal strings in Python are stored internally as 8-bit ASCII,
while Unicode strings are stored as 16-bit Unicode. This
allows for a more varied set of characters, including special
characters from most languages in the world. I'll restrict my
treatment of Unicode strings to the following:
print u'Hello, world!'
This would print following result:
Hello, world!