Python Fundamentals XI
Python Fundamentals XI
Python Fundamentals XI
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:
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:
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.
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.
# 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
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)
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.
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.