Python Fundamentals XI

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

What is Python?

EIS

• Python is a powerful high-level, object-oriented


programming language created by Guido van
Rossum and first released in 1991.
• Python's name is derived from the television series Monty
Python's Flying Circus.
• This language is now one of the most popular languages in
existence. Since 2003, Python has consistently ranked in
the top ten most popular programming languages as
measured by the TIOBE Programming Community Index.
Why Python?
EIS
• Its syntax is very clean, with an emphasis on readability and uses
standard English keywords. A basic understanding of any of the programming
languages is a plus. Moreover, an experienced developer in any programming
language can pick up Python very quickly.
• Python is a cross-platform programming language, meaning, it runs on multiple
platforms like Windows, Mac OS X, Linux, Unix and has even been ported to the
Java and .NET virtual machines.
• Python interpreters are available for many operating systems, allowing Python
code to run on a wide variety of systems. Most Python implementations
(including CPython) include a read–eval–print loop(REPL), meaning they can
function as a command line interpreter, for which the user enters statements
sequentially and receives the results immediately.
• Python is indeed an exciting and powerful language. It has the right
combination of performance and features that make writing programs
in Python both fun and easy
Python Features EIS

• Beginner's Language
• Simple and Easy to Learn
• Interpreted Language
• Cross-platform language
• Free and Open Source
• Object-Oriented language
• Extensive Libraries
• Integrated
• Databases Connectivity
First Steps With Python EIS
Starting Python Interpreter
After installation, the python interpreter lives in the installed
directory. On Windows machines, the Python installation is usually
placed in C:\PythonXX, though you can change this when you're
running the installer. To add this directory to your path, you can type
the following command into the command prompt in a DOS box:

You can start Python from Unix, DOS, or any other system that
provides you a command-line interpreter or shell window. Typing
"python" in the command line will invoke the interpreter in
immediate mode. We can directly type in Python expressions and
press enter to get the output.
The classic first program is "Hello, World!" Let’s adhere to tradition. EIS
Type in the following and press Enter:

Congratulations!! You have written your first program in Python.


Python Scripting mode EIS
Scripting mode is used to execute Python program written in a
file such as Notepad or any other text editor. Such a file is
called a script. Scripts can be saved to disk for future use.
Python scripts have the extension .py, meaning that the
filename ends with .py. For example: "myFirstProg.py".

Open a text editor (Notepad) and type in the following


program exactly as written:
print ("Hello World!")
Save this file as "myFirstProg.py".
To execute this file in script mode we simply write
EIS
"python myFirstProg.py" at the command prompt.
You should see the line Hello World! as output.

The print() is a function that tells the system to perform an action.


We know it is a function because it uses parentheses. print() tells
Python interpreter to display or output whatever we put in the
parentheses. By default, this will output to the current terminal
window .
Congratulations! You have written the "Hello, World!" program in
Keywords in Python EIS
Keywords are the reserved words in Python. These are
reserved words and we cannot use a keyword as variable
name, function name or any other identifier. Keywords in
Python are case sensitive. Python is a dynamic language and
number of keywords can vary slightly in course of time.
EIS
Python Data Types and Variables
Variables are used to store information to be referenced and manipulated in a
computer language. They also provide a way of labelling data with a detailed
naming, so our programs can be understood more clearly by the reader and
ourselves.

Python Variables
Every variable in Python is considered as an object. Variables in Python follow
the standard nomenclature of an alphanumeric name beginning in a letter or
underscore. Based on the data type of a variable, the interpreter allocates
memory and decides what can be stored in the reserved memory. You do not
need to declare variables before using them, or declare their type. Variable
names are case sensitive. Most variables in Python are local in scope to their
own function or class. Global variables, however, can be declared with the global
Assigning Values to Variables EIS
When you assign a variable, you use the = symbol. The name
of the variable goes on the left and the value you want to store
in the variable goes on the right.
Example:

total = 100 # An integer assignment


pi = 3.141 # A floating point
firstName = "Bill" # A string
Python Native Datatypes EIS
A Data type provides a set of values from which an expression may
take its values. The type defines the operations that can be done on the
data, the meaning of the data, and the way values of that type can be
stored.
Python supports the following data types:
1.Numbers
2.String
3.List
4.Tuple
5.Dictionary
Numbers EIS
Python supports four distinct numeric types: integers, long, float and complex
numbers. In addition, Booleans are a subtype of plain integers. Integers or int
are positive or negative whole numbers with no decimal point. Long integers
have unlimited precision and floats represent real numbers and are written with
a decimal point dividing the integer and fractional parts. Complex numbers have
a real and imaginary part, a + bc, where a is the real part and b is the imaginary
part. Example: (Code) Example: (output)
#integer example
x=9999 Type of x is < class 'int' >
print("type of x is ", type(x))
#float example
y=3.141
print("The type of y is ", type(y)) The type of y is < class 'float' >
#complex example
z=99+5j
print("The type of z is ", type(z)) The type of z is < class 'complex' >
String EIS
A String is an array of characters. They are formed by a list of characters, which is
really an "array of characters". They are less useful when storing information for
the computer to use. An important characteristic of each string is its length,
which is the number of characters in it. There are numerous algorithms for
processing strings, including for searching, sorting, comparing and transforming.
In Python, string is a sequence of Unicode character.
Unicode was introduced to include every character in all languages and bring
uniformity in encoding. We can create them simply by enclosing characters in
quotes. Python treats single quotes the same as double quotes.

Python strings are "immutable" which means they cannot be changed after they
are created.
Characters in a string can be accessed using the standard [ ] syntax and zero-
based indexing.
EIS
Example
Input (Code): Output:
str = "Hello World"
print (str[0]) H
print (str[6:11]) World
print (str + " !!") Hello World !!
print (len(str)) 11
EIS
List
Python List is one of the most frequently used and very versatile
datatype. Lists work similarly to strings: use the len() function and
square brackets [ ] to access data, with the first element at index 0.

weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] Output:


print (weekdays[0]) Monday
print (weekdays[4]) Friday
Tuple EIS
A tuple is a container which holds a series of comma-separated values
between parentheses. A tuple is similar to a list. Since, tuples are quite
similar to lists, both of them are used in similar situations as well.

The only the difference is that list is enclosed between square bracket
[ ], tuple between parenthesis ( ) and List have mutable
objects whereas Tuple have immutable objects.

my_Tuple_1 = (1,2,"Hello",3.14,"world") Output:


print(my_Tuple_1)
print(my_Tuple_1[3]) (1, 2, 'Hello', 3.14, 'world')
my_Tuple_2 = (5,"six") 3.14
print(my_Tuple_1 + my_Tuple_2) (1, 2, 'Hello', 3.14, 'world', 5, 'six')
Dictionary EIS
Python Dictionaries allow you store and retrieve related information in a way that
means something both to humans and computers.
• Dictionaries are non-ordered and contain "keys" and "values".
• Each key is unique and the values can be just about anything, but usually they are
string, int, or float, or a list of these things.
• Like LIST, Dictionaries can easily be changed, can be shrunk and grown at run time.
• Dictionaries don't support the sequence operation of the sequence data types like
strings, tuples and lists.
• Dictionaries belong to the built-in mapping type.
my_Dictionay = {'ID': 1110, 'Name':'John', 'Age': 12}
Output:
print (my_Dictionay['ID'])
1110
print (my_Dictionay['Age'])
12
#insert
my_Dictionay['Total Marks'] = 600
{'Total Marks': 600, 'Age': 12, 'ID': 1110, 'Name': 'John'}
print (my_Dictionay)
Python - Shallow and Deep Copy:
EIS
When creating copies of arrays or objects one can make a deep
copy or a shallow copy.
Shallow copying is creating a new object and then copying the non
static fields from the current object to the new object.
• If the field is a value type, a bit by bit copy of the field is performed.
• If the field is a reference type, the reference is copied but the referred
object is not, therefore the original object and its clone refer to the
same object.
While Deep copying is creating a new object and then copying the
non-static fields of the current object to the new object.
• If a field is a value type, a bit by bit copy of the field is performed.
• If a field is a reference type, a new copy of the referred object is
performed.
import copy
EIS
color1 = ['Red', 'Blue']
color2 = ['White','Black']
color3 = [color1 , color2]

# normal copy
Output:
color4 = color3
print (id(color3) == id(color4)) # True - color3 is the same object as color4 True
print (id(color3[0]) == id(color4[0])) # True - color4[0] is the same object as color3[0] True

# shallow copy
color4 = copy.copy(color3)
print (id(color3) == id(color4)) # False - color4 is now a new object False
print (id(color3[0]) == id(color4[0])) # True - The new variable refers to the original variable. True

# deep copy
color4 = copy.deepcopy(color3)
print (id(color3) == id(color4)) # False - color4 is now a new object False
print (id(color3[0]) == id(color4[0])) # False - color4[0] is now a new object False
Python - Type Conversion: EIS

Python has FIVE standard Data Types.

Sometimes it is necessary to convert values from one type to another.


Python defines type conversion functions to directly convert one data
type to another which is useful in day to day and competitive program
development.
Python String to Integer: EIS
The method int() is the Python standard built-in function to convert a
string into an integer value. You call it with a string containing a number
as the argument, and it returns the number converted to an actual
integer:
str =100 Output:
x = int(str)
y = x+ 200
print(y) 300

x= "100" Output:
y="-50"
z = int(x)+int(y)
print(z) 50
Python String to float Python Float to string
EIS
x= "10.5"
Output: x = 100.00 Output:
y="4.5"
z = float(x)+float(y) y = str(x)
15 print(y) ‘100. 0’
print(z)
Print (y + str(5)) ‘100.05’
Python Floats to Integers
x = 10.5 Output:
y = 4.5
z = int(x) + int(y) 14
print(z)

Python Integers to Floats


x = 100 Output:
y = 200
z = float(x) + float(y) 300.0
print(z)
Formatting Styles
Conversion Meaning EIS
d Signed integer decimal.
i Signed integer decimal.
o Unsigned octal.
u Unsigned decimal.
x Unsigned hexadecimal (lowercase).
X Unsigned hexadecimal (uppercase).
e Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
f Floating point decimal format.
F Floating point decimal format.
g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.
G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.
c Single character (accepts integer or single character string).
r String (converts any python object using repr()).
s String (converts any python object using str()).
% No argument is converted, results in a "%" character in the result.
# various formatting styles using print and format statement
from datetime import date
print('{:015}'.format(123)) # Value 123 with leading Zeros
EIS
print('hey, {:15}'.format('hello world'),"ok") # hey, hello world ok
print('{:*^30}'.format('ABC')) # *************ABC**************
print('{0}, {1}, {2}, {3}'.format(10, 12, 30, 90)) # 10, 12, 30, 90
print('{}, {}, {}'.format(11, 2223, 34)) # 11,2223, 34
print('{x}, {y}, {z}'.format(x=18, y=26, z=34)) # 18, 26, 34
print('{[1]}'.format(['first', 'second', 'third'])) # second
print('{[subject]}'.format({'subject': 'Informatics Practices'})) # Informatics Practices
# Numerical Representation
print('{:x}'.format(15)) # Lower Hexadecimal code
print('{:o}'.format(8)) # Lower Octal value
print('{:X}'.format(15)) # Uppercase Hexadecimal code
print('{:#x}'.format(100)) # Hexadecimal including 0x
print('{:b}'.format(65)) # Binary digits
print('{:c}'.format(65)) # Character
print('{:d}'.format(100)) # Decimal format
print('{:,}'.format(1234567)) # Thousand Seperator
print('{:e}'.format(0.0000000001)) # Scientific Notation (lower)
print('{:E}'.format(0.0000000001)) # Scientific Notation (Upper)
print('{:f}'.format(100/3.0)) # Fixed point
print('{:f}'.format(3/14.0)) # Fixed output
print('{:g}'.format(3/14.0)) # General Format
print('{:%}'.format(0.66)) # percentage format
print('{:.2}'.format(0.214286)) # Precision
print('{!r}'.format('string is lovely'))
print('{!s}'.format(1.53438987))
today = date.today()
print("today's date is ",today)
Converting to Tuples and Lists:
EIS
• A list is a mutable ordered sequence of elements that is contained
within square brackets [ ].
• A tuple is an immutable ordered sequence of elements contained
within parentheses ( ).

You can use the methods list() and tuple() to convert the values passed
to them into the list and tuple data type respectively.
Python List to Tuple Python Tuple to List
lst = [1,2,3,4,5] Output: tpl = (1,2,3,4,5) Output:
print(lst) print(tpl)
tpl = tuple(lst) [1, 2, 3, 4, 5] lst = list(tpl) (1, 2, 3, 4, 5)
print(tpl) (1, 2, 3, 4, 5) print(lst) [1, 2, 3, 4, 5]
ValueError: EIS
While converting from string to int you may get ValueError exception.
This exception occurs if the string you want to convert does not represent any numbers.
Traceback (most recent call last):
str = "halo" File “stest.py", line 3, in < module >
x = int(str) x = int(str)
print(x) ValueError: invalid literal for int() with base 10: 'halo'
You can see, the above code raised a ValueError exception if there is any digit that is
not belong to decimal number system.
str = "halo“
x = int(str)
except ValueError: Output:
print("Could not convert !!!") Could not convert !!!

If you are ever unsure of the type of the particular object, you can use the type() function:
Output:
print(type('Hello World!')) < class 'str' >
print(type(365)) < class 'int' >
print(type(3.14)) < class 'float' >
Python Mathematical Functions: EIS
Functions can do anything, but their primary use pattern is taking
parameters and returning values.

The math module provides some basic mathematical functions for


working with floating-point numbers. Using Math module in python,
we can access to different mathematical functions already defined by
the C standard. These functions perform various arithmetic
operations like calculating the floor, ceiling, or absolute value of a
number using the floor(x), ceil(x), and fabs(x) functions respectively.
Here is the list of all the functions and attributes defined in math module with a brief
explanation of what they do. => (in Next Slide)
List of Functions in Python (Math Module)
Function Description Function Description EIS
ceil(x) Returns the smallest integer greater than or equal to x. pow(x, y) Returns x raised to the power y
copysign(x, y) Returns x with the sign of y sqrt(x) Returns the square root of x
fabs(x) Returns the absolute value of x acos(x) Returns the arc cosine of x
factorial(x) Returns the factorial of x asin(x) Returns the arc sine of x
floor(x) Returns the largest integer less than or equal to x atan(x) Returns the arc tangent of x
fmod(x, y) Returns the remainder when x is divided by y atan2(y, x) Returns atan(y / x)
frexp(x) Returns the mantissa and exponent of x as the pair (m, e) cos(x) Returns the cosine of x
Returns an accurate floating point sum of values in the hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)
fsum(iterable)
iterable sin(x) Returns the sine of x
Returns True if x is neither an infinity nor a NaN (Not a tan(x) Returns the tangent of x
isfinite(x)
Number) degrees(x) Converts angle x from radians to degrees
isinf(x) Returns True if x is a positive or negative infinity radians(x) Converts angle x from degrees to radians
isnan(x) Returns True if x is a NaN acosh(x) Returns the inverse hyperbolic cosine of x
ldexp(x, i) Returns x * (2**i) asinh(x) Returns the inverse hyperbolic sine of x
modf(x) Returns the fractional and integer parts of x atanh(x) Returns the inverse hyperbolic tangent of x
trunc(x) Returns the truncated integer value of x cosh(x) Returns the hyperbolic cosine of x
exp(x) Returns e**x sinh(x) Returns the hyperbolic cosine of x
expm1(x) Returns e**x - 1 tanh(x) Returns the hyperbolic tangent of x
log(x[, base]) Returns the logarithm of x to the base (defaults to e) erf(x) Returns the error function at x
log1p(x) Returns the natural logarithm of 1+x erfc(x) Returns the complementary error function at x
log2(x) Returns the base-2 logarithm of x gamma(x) Returns the Gamma function at x
log10(x) Returns the base-10 logarithm of x lgamma(x) Returns the natural logarithm of the absolute value of the Gamma
Mathematical constant, the ratio of circumference of a circle to it's
pi
diameter (3.14159...)
e mathematical constant e (2.71828...)
String Manipulation in Python:
EIS
Strings are sequences of characters.
There are numerous algorithms for processing strings, including for searching,
sorting, comparing and transforming.
Python strings are "immutable" which means they cannot be changed after they
are created.
To create a string, put the sequence of characters inside either single quotes,
double quotes, or triple quotes and then assign it to a variable.
str = 'Hellow World!' Access characters in a string:
str = "Hellow World!"
str = """Sunday In order to access characters from String, use the square brackets []
Monday for slicing along with the index or indices to obtain your characters.
Tuesday""" • Python String index starts from 0.
print(str [0:-6]) # output is Hellow• Python allows negative indexing for its sequences.
print(str [7:-1]) # output is World The index of -1 refers to the last item, -2 to the second last item and so on.
String Concatenation: EIS
Joining of two or more strings into a single one is called concatenation.
Python uses "+" operator for joining one or more strings.
str1 = 'Hellow ' Output:
str2 = ' World!'
print(str1 + str2) Hellow World!

Reverse a String:
In Python Strings are sliceable. Slicing a string gives you a new string from one
point in the string, backwards or forwards, to another point, by given
increments. They take slice notation or a slice object in a subscript:
string[subscript]
The subscript creates a slice by including a colon within the braces
string[begin : end : step]
It works by doing [begin: end: step] - by leaving begin and end off and specifying
a step of -1, it reverses a string. str = 'Python String' Output:
print(str[::-1]) gnirtS nohtyP
String Methods:
Python has several built-in methods associated with the string data type. These methods let us easily modify EIS
and manipulate strings. Built-in methods are those that are defined in the Python programming language and
are readily available for us to use. Here are some of the most common string methods.
Method Description Method Description
capitalize() Converts the first character to upper case join() Joins the elements of an iterable to the end of the string
casefold() Converts string into lower case ljust() Returns a left justified version of the string
center() Returns a centered string lower() Converts a string into lower case
count() Returns the number of times a specified value occurs in a string lstrip() Returns a left trim version of the string
encode() Returns an encoded version of the string maketrans() Returns a translation table to be used in translations
endswith() Returns true if the string ends with the specified value partition() Returns a tuple where the string is parted into three parts
expandtabs() Sets the tab size of the string replace() Returns a string where a specified value is replaced with a specified value
find() Searches the string for a specified value and returns the position of
rfind() Searches the string for a specified value and returns the last position of where it
where it was found
format()
was found
Formats specified values in a string
format_map() Formats specified values in a string
rindex() Searches the string for a specified value and returns the last position of where it
was found
index() Searches the string for a specified value and returns the position of
rjust() Returns a right justified version of the string
where it was found
isalnum()
rpartition() Returns a tuple where the string is parted into three parts
Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet rsplit() Splits the string at the specified separator, and returns a list
isdecimal() Returns True if all characters in the string are decimals rstrip() Returns a right trim version of the string
isdigit() Returns True if all characters in the string are digits split() Splits the string at the specified separator, and returns a list
isidentifier() Returns True if the string is an identifier splitlines() Splits the string at line breaks and returns a list
islower() Returns True if all characters in the string are lower case startswith() Returns true if the string starts with the specified value
isnumeric() Returns True if all characters in the string are numeric strip() Returns a trimmed version of the string
isprintable() Returns True if all characters in the string are printable swapcase() Swaps cases, lower case becomes upper case and vice versa
isspace() Returns True if all characters in the string are whitespaces title() Converts the first character of each word to upper case
istitle() Returns True if the string follows the rules of a title translate() Returns a translated string
isupper() Returns True if all characters in the string are upper case upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning

Note: All string methods returns new values. They do not change the original string.

You might also like