python
- Details
- Last Updated: Saturday, 02 October 2021 04:49
- Published: Friday, 12 October 2018 04:41
- Hits: 1138
Python:
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. Similar to perl.
Python provides interfaces to all major commercial databases. Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems. It can be easily integrated with C, C++, Java, etc.
Python has so much support from community, that almost everything can be done by using python's vast library or modules. You can build a website, write a program for raspberry pi, build games with gui, etc. Infact, it's one language that you can learn and get by doing everything without learning any more languages. I've avoided python in the past because of it's huge confusion over python2 vs python3, but now this issue looks settled.
Python 3 is latest version, python 2 is going to be EOL in 2020. So, switch to python 3 for all coding. There are significant differences b/w python2 and python3, so don't waste your time learning python2. However, we may still want to install both python2 and python3, as many pgms are still written in python2. So, not having python2 will cause those pgms to error out. When we install python 2, it is installed as both python (python is just a soft link to python2) and python2, while python 3 is installed as python3. Since python is just a soft link to python2, we can change it at any time to point to either python2 or python3. This helps reduce confusion, as pgms written in python 2 may suddenly start failing if python3 is installed as python. So, we keep soft links for all python, python2 and python3. We can change the soft link of "python" to point to "python3" if needed. However, it's advisable to leave python soft link pointing to python2, and have a separate link for python3.
python3 itself has several versions as python3.4, python3.6, etc. Latest stable version is python3.8 as of 2020.
NOTE: On any linux distro, after installing latest version of python3, change the soft link of python3 to point to python3.8 or whatever is the latest version. That way, your latest python version would be available for your programs, by just typing python3.
cmd: cd /usr/bin; rm python3; ln -s python3.8 python3; => now calling python3 calls python3.8
All the discussion below is for python3, unless explicitly specified. I'll point out the differences where applicable. Be careful when searching for python on internet, as many of them are for python2, and may not work for python3.
Official doc is on python.org site: https://docs.python.org/
geeksforgeeks also has very elaborate and fantastic tutorial here: https://www.geeksforgeeks.org/python-programming-language/
Python installation:
On any Linux distro, to install python3, there are 2 ways: one thru package mgmt, while other by manually downloading and installing.
1. Pckage mgmt:
CentOS: For CentOS, we install using yum. Below are the ways to install python2 and python3.
A1. rpm pkg for python2: sudo yum install python => by default, it installs puthon2. It specifically installs python 2.7 in /usr/bin/python2.7. A soft link is created to python2 in /usr/bin dir (/usr/bin/python2 -> python2.7). Another soft link "python" is made to python2 (/usr/bin/python -> python2). and python2 are soft links to python2.7 already installed
A2. rpm pkg for python 3.4: sudo yum install python34 => installs python 3.4 in /usr/bin/python3.4. A soft link is created to python3 in /usr/bin dir (/usr/bin/python3 -> python3.4) python and python2 are soft links to python2.7 already installed
A3. rpm pkg for python 3.6: sudo yum install python36 => installs python 3.6 in /usr/bin/python3.6. A soft link is created to python3 in /usr/bin dir (/usr/bin/python3 -> python3.6). python and python2 are soft links to python2.7 already installed
A4: rpm pkg for python 3.7: sudo yum install python37 => Although latest version of python is python3.7, yum repo still doesn't have it, and gives an error that "no such package found". Run "yum info python37" to find out if python 3.7 available or not.
NOTE: one very important thing to note is that "yum" is written in python2. So if you change soft link of python to change to python3 (after installing python3), then yum will not work and will throw this error:
File "/usr/bin/yum", line 30
except KeyboardInterrupt, e:
SyntaxError: invalid syntax
To fix this, do one of 2 things:
1. change python version being called in yum to python2: In /usr/bin/yum file, change first line from "#!/usr/bin/python" to "#!/usr/bin/python2". This will force python2 soft link to be used, instead of using python link.
2. change softlink in python to python2. This will cause yum to still use python2 as softlink python is pointing to python2. However, this may cause other pgms to fail, which may rely on pyton3, and need python ink to point to python3. To fix this, any pgm that needs to have python3, change first line in that pgm to point to python3 instead of python
First choice is preferred, as python3 is the step forward, so keeping soft link python pointing to python3 is going to work for most pgms.
Linux Mint: On LinuxMint, we install using apt. Latest python is 3.8 as of June 2021.
A1. sudo apt install python3.8 => This installs python version 3.8. Look in /usr/bin/ dir to make sure you see python3.8 over there.
2. manual: not tried yet. It's not recommended way, as it requires lot more efforst, and there's no reason to do it (as all linux distro allow you to install via pkg mgmt)
Python syntax:
1. comment: Python comment is anything after a # at start of line or end of line. Multiline comments are not supported, but can be mimicked by putting any comment within triple quotes, i.e " " " .... multi line comment " " "
ex: a=2 #comment
2. case sensitive: Python is case sensitive. So, var and Var are different.
3. End of line: Each stmt ends with newline \n. So, no ; needed (this is in contrast to other languages which use ; etc to indicate end of line). However for multi stmt in single line, we need ; In cases where we need line to continue, we use line continuation char \. Recall that \ hides metacharacter immediately following it and treats it as literal, so newline metacharacter is hidden from shell interpretor. What the interpretor sees is just a space.
ex:
total = item_one + \
item_two + \
item_three
4. Blocks of code: no braces provided, instead all statements within the block must be indented the same amount. This is unique feature of python, and also very confusing as all other languages use brackets or keywords to mark begin or end of block, but never rely on spaces or indentation. This indentation needs to be a tab or 4 spaces to signify a block. 2 tabs or 8 spaces signifies another block nested within the outer parent block. Similarly 3 tabs signifies yet another nested block within outer 2 blocks and so on. We can have 1 space also to indent a block, but for readability, we keep it s 4 spaces or 1 tab (most editors automatically convert tab into 4 spaces, so it's the same thing) . All of the code with same number of spaces at start of line is considered part of one block. NOTE: we can't have 0 spaces to identify a block, as that will error out. We do need some indentation.
ex:
if True: => header line begin stmt with keyword (if, else, while, etc), terminate with : and are followed by suite
print "True" => this group of stmt in single code block called suite. This is indented by a tab or 4 spaces, so it's part of if block
print "I'm here" => This is part of if block too, as it's same indentation.
else:
print "False" => this is part of else bock, as it's indented by a tab
print "end" => this is not part of if-else block as it's not indented at all.
NOTE: these are 2 of the most distinct departure from other languages.
I. One is the absence of end of line character (i.e no semicon etc, just a newline marks end of cmd in a line). We can always add a semicolon at end of line and python will work just fine, but correct way is to not put a semicolon.
II. Second is the use of tabs or spaces to identify blocks of code. Usually high level languages don't rely on spaces for correct functionality, but python is all about spaces. Most other languages use curly braces { ... } to define scope of loops, functions, etc.
5. reserved keywords: Like any other pgm lang, python has reserved keywords, which can't be used as var names or for any other purpose. ex:
1. if else,
2. and, not, or
3. for, while, break, continue
4. print, exec, try, return, assert, class. print function is most used function and is explained later under "Functions" section.
6. quotes: single quotes and double quotes have same meaning, and so are interchangeable in python. We use one or the other when it's absolutely needed, i.e use double-quotes if your string contains a single-quote
Running python:
We can run python interactively or run a python pgm via a cmd line
python --version => returns version num. If it's 2.x it's older, if 3.x it's newer. We can also run "python -V" to get version num.
1. interactively:
typing python brings up python shell. Prompt is >>>. We can type any python cmd in it. Type "Ctrl + D" to exit shell.
>>> print("Hello")
prints Hello on screen
2. via cmd line:
file: test.py => here are are specifying python3 as interpretor instead of python (since python is usually set as a soft link to python2)
#!/usr/bin/python3 print ("Hello, Python!") #this is a comment: # single line comment |
> type ./test.py to run above file. (do chmod 755 test.py to make it a executable file).
> python3 test.py => This also runs the above python file. We could do "python test.py" too. This will work as long as syntax in test.py is python2 syntax.
Data Types and variables:
I. Variables:
As in any programming language, we need to define variables which store data, which may be of multiple data types supported by the language. var do not need explicit declaration of data type. This declaration happens automatically when you assign a value to a variable using = sign (i.e var2=1.1 => assigns float num 1.1 to var2)
variable names or Identifiers: starts with letter (a-z) or _. Variables are not declared beforehand to be of a particular type (as in C), but this is a common practice in most shell programming. The type is figured out by python during assignment.
II. Data types: Python is strongly typed language, meaning we would need to convert one data type to other to use it, else it will give error.
A. primitive data types: In python, we have 4 primitive data types:
1. numbers: numbers may of 4 types:
A. int (signed integers) ex: var1=10
B. long (long int, can also be oct or hex) ex: var2=-579678L; var3=0xDEADBEEF
C. float (fp real) ex: var4=15.2; var5=32.3e18
D. complex (complex num) ex: 3.14j, 4.5-3j
2. Strings: cont set of char in "...." or '....'. In both of these quotes, values are not substituted but printed as it is. There are special formatting available that allow substitution within single or double quotes that is explained later. This is differences from scripting languages and other languages which treat single and double quotes differently. There is also a triple quote in python that allows string to span multiple lines (so newline tab etc are treated as part of string).
ex: var1 = "my name"
ex: address = ''' my house is at => due to triple quotes, everything on this line and below is part of string including new llines. print(address) will print all 3 lines as is.
1207 goog ln,
los angeles "'
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.
ex: str='My world'; print(str[0]) => prints M; print(str[2:5]) => prints worl; print(str+"TEST") => prints My worldTEST
There are 2 types of string in python. traditional str type (which is 1 byte or 8bit char), and newer unicode type (which are 2 byte or 16 bit char and can be upto 4 bytes for UTF-8). On any string type, we can put a char "u" infront of the string to indicate that it's unicode type. u or U refers to UTF-8 style where each string can be variable length from 1 byte to 4 bytes. (UTF-8 is used widely now, since 1 byte could only store ASCII char and can't handle millions of other char out there. UTF-8 is compatible with 1 byte ASCII code)
There are many other prefixes besides "u" to indicate how the string is going to be interpreted. "r" means raw string type (so that anything inside the string is going to be treated as literal and not interpreted. ex: r"me\n" => this is not going to treat \n as new line but instead as 2 literals \ and n.
str=u'Me .op' => this string is now unicode type (since u preceedes the string). So, each character is stored as 16 bits instead of 8 bits. u'text' is just a shortcode for calling unicode('text')
formatted strings: In version 3.6 of python, formatted string literals were introduced. So far, no substitutions happened for any characters inside strings, but with formatted string (or f-string), we can provide replacement fields by enclosing them within { ... }. Any python expr is allowed within these curly braces.
ex: name = "Fred"
a = f"He said his name is {name}." => This substitutes name with variable "name"., since we have f in front of string.
a = "He said his name is {name}."=> no substitution occurs
NOTE: char: There is no char var type in python. char are rep with string with length of one.
There are many string methods available to operate on strings. Look in python link for such methods.
ex: str.upper() returns a copy of string, with all letters uppercased. "My name".upper() returns string "MY NAME"
3. boolean: 2 values: True and False.
B. Compound data types:
4. List: most versatile. similar to arrays in C, except that items belonging to list can be of diff data types. NOTE: there are no array data type in Python. List are superset of arrays, so we use list in it's place. list have syntax same as that of array. On internet, lot of articles talk about array in python. In reality they are not talking about array, but list.
list contains items separated by commas and enclosed within [].
1D Lists:
ex: mylist = [] => this defines an empty list (since [] used, it implies a list). However, the size of list is not defined here, i.e if the list has 10 entries or 100 entries isn't mentioned, so it's not possible for compiler to reserve memory for this list at this point in time.
ex: list1 = ['A',1,"john", 23]; print(list1[1:3]) => prints [1, "john"] => Here, we specify entries of the list. So, here compiler/interpretor reserves memeory for list depending on how many entires are in the list, and the size of each entry. NOTE: the range specified includes item with index=1,2 but NOT index=3, as range is up to index-1. Also, commas preserved when we print the list
ex: list1[3]=102 => this updates value 23 with new value 102, not possible with tuple since it's read only
ex: for x in [1, 2, 3]: print x, => prints 1 2 3
Assigning values to list: We saw one way to assign initial values to list. Let's see if we can assign initial values to a list in other way.
my_list[0]=4;=> Here my_list is defined for the 1st time with 0th entry having value 4. Previously, we assigned list values as my_list=[4] which worked. This will give a Name Error: "NameError: name 'my_list' is not defined". This is because we are accessing indices of list, and python doesn't know what indices it has. So, let's define an empty list.
my_list = []; my_list[0]=4; my_list[1]=2; => This will give an Error: "IndexError: list assignment index out of range". This is because python doesn't know the size of the list. If we assigned values to this list as my_list = [4,2] => then python knows the size of list as 2, and assigns value as my_list[0]=4 and my_list[1]=2. Then we can access value as my_list[0].
One way to resolve above issue is to define the list with size specified. ex: my_list = [0]*4; => This defines a list with 4 elements [0,0,0,0]. Now we can do my_list[0]=4. However, here list elements must all be of same type, else *4 won't work.
2D lists:
2D lists are en extensions of 1D list, i.e each element of a 2D list is in itself a 1D list.
ex: my_arr = [ [300, 200,100, 900], [600, 500, 400, 700] ]; => This is a 2D list, where each list element is 1D list.
Accessing list elements: We access it the same way as in 1D list, except that we provide the index of 1D list also.
print(my_arr[1][0:2]) => prints [600, 500]. This is called slicing of array/list/tuple. format is [start_index:stop_index-1:increment of index]. See in numpy module section for more details. so, my_arr[0][3:1:-1] = [900, 100]
ex: print(my_arr[:]) => This prints entire 2D array since blank start means start from 1st index and blank end means stop at last index. Since no dimensions specified, it includes all dimension, so o/p is: [ [300, 200,100], [600, 500, 400] ]. This applies to any dimension array. arr[:] will all elements of the array. For some reason, slicing across multiple indices don't work, i.e my_arr[1:3][0:5] returns empty array.
We define a 2D list same way as 1D list. i.e list_2d = []. However, we can't do something like list_2D[0][0]=5, without having this list already specified for same reasons as 1D list above) with values as: list_2D=[[67,34],[35,67]]. Now we can do: list_2D[0][0]=5.
We can initialize 2D list as: my_list = [[0]*2]*3; => This will create 2D list of 2x3 with all values as 0, i.e [[0,0,0],[0,0,0]]
list operators: There are multiple operators for manipulating lists. Some of them are: cmp(list1, list2); len(list3); list.sort(list4);
Arrays: Lists behave almost same as arrays, but are not efficient. Lists are more generic than array (in that they allow multiple data types, while array allow same data type only), but they also get less efficient for storing/retrieving, computing, etc. Most scientific computations can be easily carried out with arrays, since they usually work on only one kind of data (i.e int, float, etc). Python doesn't enforce typing (i.e one particular type of data as int, etc), so they never created an array data type in Python. For most basic uses, lists serves our purpose, and we don't care about speed. However, if performance becomes critical because of large amount of data to work with, then Arrays are needed.
We said previously that python doesn't have arrays. However, python supports modules which allow us to use arrays. 2 ways to create arrays in Python
A. array module: Python has module "array" that can be imported to get arrays. We specify the type of data elements, and all elements of array have to be of that data type. There are many functions available to operate on array. This method is not recommended method for creating arrays, use 2nd method using numpy module.
ex: import array as arr => We don't need to install any module for this. More details about array module can be found on internet
my_array = arr.array('i', [2, 4, 6]); print(my_array) => prints array('i', [2, 3, 5]) => NOTE: everything in array including data type is printed. Again, commas preserved while printing array (same way as in lists)
B. numpy module: There is NumPy module that can be used to create arrays. It's not included by default with Python distribution, so will need to be installed (see in NumPy section). This is the recommended method for creating arrays.
5. tuples: similar to list, specified using (). however they cannot be updated (i.e read only). We can apply slicing across tuples also. Used very rarely in simple codes.
ex: tuple1 = ('ab', 2.7)
6. sets: sets are similar to sets in maths where we can take union, intersection, etc. Sets defined using curly braces { .. }. They contain any number of objects, and of different types. Sets are unordered: the original order, as specified in the definition, is not necessarily preserved. Additionally, duplicate values are only represented in the set once. set elements must be immutable. For example, a tuple may be included in a set, as it's immutable. However lists and dictionaries are mutable, so they can’t be set elements. Other way to create set is using the set() function.
ex: x = {'foo', 'bar', 'baz', 'foo', 'qux', 12, (1,2), None}
print(x) => {none, 'foo', 12, (1,2), 'bar', 'baz', 'qux'}
=> NOTE: duplicate entries are removed, and order of elements is not preserved
Many operators as union, intersection, difference, |, &, ^, etc are allowed on sets. sets are also very rarely used in simple programs.
7 dictionary: They are like hashes in perl. They are also known as associative arrays. They consist of key-value pair. key/values can be any data type.
Dictionaries are enclosed by { } and values can be assigned and individual elements are accessed using [ ... ]. since both sets and dictionary use { }, we distinguish b/w the two via presence of ":". Since { } is used to rep empty dictionary, we can't use {} to rep empty set (since then python interpretor has no way of knowing if the object is a set or a dictionary). In that case,, we use set() func with no args to create empty set. We use ":" to assign key:value pair for each element
1D dictionary: Just like 1D list, we have 1D dictionary:
ex:
tinydict = {'name': 'john','code':6734, 'dept': 'sales'} => Assigns key value pair as follows: name->john, code->6734, etc. print(tinydict.keys()) prints ['dept', 'code', 'name'] while tinydict.values() prints ['sales', 6734, 'john']
tinydict['name'] prints "john", tinydict['code'] prints "6734" and so on
Assigning values to list: There are 2 ways to assign dict key/value pair.
A. We can assign dict key/value pair as we did in 1D list, and as shown in ex above.
ex: tinydict = {"name": "john",5:9}
B. We can also assign dict values in array form as shown below. This is different than in 1D list, where we weren't allowed to do dict[0]=5 and so on.
dict = {} => initialize dict. This is needed for dictionary, as w/o this there is no way to know for python compiler/interpretor to find out if dict[0]=1 is list assignment or dictionary assignment.
dict[0]=5 => Now we are allowed assignment like these. NOTE: 0 is a key her, and not index number. It just happens to be a integer key here, as 0 is not enclosed in quotes. The value is also integer as it's not enclosed in quotes.
dict['one'] = "This is one" => print (dict['one']) prints "This is one". Here both key and value are strings.
dict[2] = "This is two"
2D dictionary: Just like 2D list, we can have higher dim dict as 2D, 3D, etc. However for 2D dict, we can't do something like dict_2D['a']['b']='xyz". Th reason might be that 2nd index it needs to know the range. So, we have to first define 1D dict, and then use that 1D dict as elements of 2D dict.
ex: dict1D['age']=35; dict1D['salary']=300;
dict2D['ramesh']=dict1D => Now dict2D['ramesh']['age']=35, dict2D['ramesh']['salary']=300 and so on. dict2D['mohan']={'age':50,'salary':500}. So 2D dict are just an array of 1D dict.
So, 2D dict are little cumbersome to write as you will first need to form 1D dict and then use that as elements of 2D. It would have been nice to just directly assign elements to 2D dict.
Operators:
Just like in other lang, we have various operators to operate on variables. Mostly operators are used for number data type (int, float, etc), but some of them can be used on other data types too. How the operator behaves depends on the data type of it's operands.
1. arithmetic: +, -, *, /, etc. ex: a+b. + and * are used in strings to concatenate or repeat strings.
2. comparison: ==, !=, >, >=, etc ex: (a<b)
3. assignment: =, +=, -=, etc ex: c=a+b;
4. bit wise : &, |, ^, ~, <<, >>, etc ex: a=16, b=2, a&b
5. logical: not, or, and
Control statements:
1. if elif else: This is same as if stmt in other languages. elif is substitute for "else if". Both elif and else are optional. An if
… elif
… elif
… sequence is a substitute for the switch
or case
statements found in other languages.
ex:Below if .. elif .. else stmt needs appr tab spaces for each block of code. NOTE: if, elif and else are at start of line with no tab.
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
else:
print('More')
ex: if ( var == 100 ) : print ("val is 100") #for single line suite, it can be on same line
2. for: for stmt differ from that in C. There is no start, end or iteration index. Python’s for
statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
ex: below iterates over the list and prints each word and length
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
ex: to iterate over a seq of numbers just as we do in for loop in C pgm, we can use range() function. syntax of range is (start,stop,step), where stop is required parameter, while star/step are optional. sop value is not included in range (i.e range is upto stop-1). range(10)
generates 10 values, from 0 to 9 (doesn't include 10). range(5,9) generates 4 values = 5,6,7,8. range(0,10,3) indicates step value of 3, so it generates 4 values = 0, 3, 6, 9. So, by using range() function, we can achieve what we do using for loops in C pgm.
for i in range(5):
print(i) => prints 0,1,2,3,4
ex: To iterate over the indices of a sequence, you can combine range()
and len()
as follows:
for i in range(len(words)):
print(i, words[i])) => This prints index 0,1,2 and prints the 3 words
3. while: The while
statement is used for repeated execution as long as an expression is true.
ex: infinite loop below since expr is set to "True"
while True:
print("infinite loop")
4. break, continue, else: break, continue and else claues can be used in loops as "for" and "while", "break" breaks out of the innermost enclosing for
or while
loop, while "continue" continue thru next iteration of loop. Else clause can be used for loops as "for" and "while". a loop’s else
clause runs when no break
occurs. Look for more details in the python website link above.
Functions: Function syntax is similar to those of other lang. All functions require parenthesis and optional args inside it.
1. Builtin: Python provides many builtin functions as print(), int(), abs(), open(), sorted(), etc.
A. print( ) : print function is one of the most used functions to o/p something on screen. It wasn't a function in python2 (it was just a statement), so no ( ) were required with print, but it's a function in python3, so it needs ( ). i.e: print("Hello, Python!"); However () works in python 2 also. So, it's preferred to use print as a func with parenthesis ( .... )
Python2: print "The answer is", 2*2, "My name=", name, "var=", 2*var1
Python3: print("The answer is", 2*2, "My name=", name, "var=",2*var1) => this will work in python2 also as parenthesis work in python2. Anything within quotes is printed as literal string, anything outside quotes is computed if it can be computed based on data types, or the value is just printed if it's a var. A newline is appended by default, but if we put a comma at the end of args 9i.e just before closing parenthesis), it suppresses newline.
We can use strings, list, var, etc to be printed using print. With List and tuples, full list will be printed, w/o requiring us to iterate over each element of the list.
ex: formatted string and other string type can be used inside print
name = "Fred"; print(f"He said his name is {name}." ) => This substitutes name with variable "name"., since we have f in front of string.
% operator for strings: String objects have one unique built-in operation: the %
operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values
(where format is a string), %
conversion specifications (as d, s, f, etc) in format are replaced with zero or more elements of values. The effect is similar to using the sprintf()
in the C language.
ex: name="afg"; age=2;
my_format = "his name is %s, his age is %2d"; my_values = (name, age) => NOTE: my_values need parenthesis since they are tuples (not curly braces or square brackets)
print(my_format % my_values) => Here %s and %2d in format string are replaced with values in var "name" and "age".NOTE: the whole thing here can be treated as a string, that is put inside print function. Whatever is the o/p of this formatting operator is passed to print func as an argument.
o/p is => his name is afg, his age is 2
ex: print( ' %(language)s has %(number)03d quote types.' % {'language': "Python", "number": 2}) => outputs "Python has 002 quote types". Here "s" after %(language) is a conversion spec saying convert 'language' object into a string using function str(). similarly 03d spec asks it to convert "number" into signed integer with 3 digits. Here values are not tuples, but hash, so curly braces used. NOTE: there is no comma after single or double quotes of string, as it's "format % value" that is being used inside print function, and not the typical "string followed by variable" syntax
ex: We can use % operator on string inside print func, along with other regular args, as strings, var, etc to be printed. The whole format string is just another string arg to print func.
var2=23; var3 = "my stuff"
print('The value of pi is approximately %5.3f.' % math.pi, var2, "good", var3) => Here math.pi is formatted with total of 5 digits and 3 digits of precision (%. %5.3f means width=5, precision=2).
o/p is => The value of pi is approximately 3.142 23 good my stuff
format method: above are older ways of formatting print o/p. Now, we use format method to format strings.
ex: print
(
'{0} and {1}'
.
format
(
'Geeks'
,
'Portal'
))=> {0} is replaced by string in 0 position which is 'Geeks' and {1} is replaced by string in position 1 which is 'Portal', so o/p is => Geeks and Portal. NOTE: there is no comma here after single or double quotes but a dot, since we are using the method on print argument, so it's not typical print variable.
B. input( ): input function is other widely used function to get input from user. There are diff b/w how this func behaved in python2 vs python3.
Python 2:
python2: str = raw_input("Enter your input: "); => raw_input() reads 1 line from std i/p and returns it as string w/o the newline
python2: str = input("Enter your cmd: "); => same as above except that valid python expr can be provided, and it will return result. result is still stored as string.
Enter your cmd: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40] => str stores this list
Python 3:
python3: raw_input() function from python2 has been deprecated and instead replaced by input() func.So, no python expr can be provided.
python3: input() function from python2 is depracted, and instead stmt eval(input()) must be used to get same behaviour as input() func of python2. We don't use this stmt much, instead input() func above is used.
With all these input functions above, the result is stored as string, so in order to do numeric computation, we have to do data conversion using func below. Also, no expr are allowed, i.e expr will be treated as strings, and won't be computed.
ex: here 2 numbers are provided as i/p, but have to be converted to int in order to add them
num1=input("1st number")
num2=input("2nd number")
sum=int(num1)+int(num2)
print("Sum is", sum); #Here if i/p is 1 and 2, then o/p is 3. If we just did "sum=num1+num2", then it would concatenate the 2 strings and print "12"
C1. type(): type is an inbuilt func to find data type of any var or object (in case of OOP discussed later):
ex: age=50; print(type(age)) => prints type as "int".
ex: type_var = type(tinydict) => assigns "dict" string to type_var (as tinydict defined above is of type "dict")
C2. data conversion: data can be converted from one type to other by casting. Some of the casting functions are:
ex: int(x), str(x), list(y), hex(x), dict(d)
ex: python3: var_int = int(input("Enter any number: ")); var1=var_int+1; => here, var_int stores integer (i.e any number entered is a string, but then int() func converts it to int, so that we can do airthmetic computation on it.
C3. isinstance(): The isinstance()
function returns True
if the specified object is of the specified type, otherwise False
.
ex: if (isinstance("Hello", str) ): print("true") => This checks if "Hello" is of type string. It returns True since anything within ".." is a string
ex: my_num=4.7; var1=isinstance(my_num, (str,list,dict,tuple)); print(var1) => this prints "False", since my_num is of type "int", while allowed types that this func is checking for are str,list,dict and tuple.
D. Maths:
ex: abs(x); log(x); max(x1,x2,...); pow(x,y);
ex: random()
ex: cos(x); radians(x);
ex: constants: pi, e
E. File functions: Python has file functions for reading/writing files just as in other lang.
file read/write ex shown below:
fo = open("foo.txt", "w+") => opens file for both rd/wrt, ptr at start of file. w=wrt_only, r=rd_only, (a=append_mode, ptr at end of file)
fo.write( "Python is a great language.\nYeah its great!!\n");
str = fo.read(10); => reads 10 bytes from file, if no arg provided, then reads whole file until EOF
print "Read String is : ", str
fo.close
exception: when script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error. exception must be handled, else pgm terminates.
ex:
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!") => trying to wrt to rd only file, raises an exception of IOError
except IOError: => std exception raised when an I/O operation fails
print "Error: can\'t find file or read data" => This gets printed when IOError exception happens in try block
except ... => some other exception code can be put here for a diff exception raised. There are about 30-40 different exception errors that we can specify
except: => "except" stmt w/o any Exception code means raise this exception for any exception error
else:
print "Written content in the file successfully" => If no exception, then run this block
Assert: An assertion is a sanity-check. An expression inside assert stmt is tested, and if the result comes up false, an exception is raised. Assertions were added in Python 1.5. They are usually placed inside function definition to check for valid inputs or to check for valid outputs. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback. Assertions are very useful in exposing bugs, and should always be used extensively.
assert (Temperature >= 0),"Colder than absolute zero!" => This checks for Temperature variable to be +ve. If -ve, then the stmt following assert is printed "Colder ..." and pgm terminates.
assert(isinstance(b, float) or isinstance(b, int)) => Here on failure of assertion (i.e b is neither float nor int), no stmt is printed, but pgm terminates with traceback. If there are many assertions in pgm, it may be tedious to figure out which assertion failed, so it's good practice to have "text" following assert keyword.
2. User defined: Besides the built in functions provided by python, we may define our own function also. There are 2 kinds of function defined in python:
A. Normal function: These are regular function definition (as is common in other pgm lang)
defining a func:
def functionname( parameters ): => i/p param or args
"function_docstring" => optional: explains what this func does
function_suite
return [expression] => If no expr provided, it returns none
ex:
def printme( str ):
"This prints a passed string into this function"
print str
return;
printme("I'm first call to user defined function!") => calls printme func
NOTE: All parameters (arguments) in Python are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.
If var defined within func, then they are local to func, and are diff from same var declared outside the func.
total = 0; # This is global variable.
def sum( arg1, arg2=10 ): //default val of arg2 is 10
total = arg1 + arg2; # Here total is local variable.
return total; //here 30 is stored in total and returned.
# Now you can call sum function
total1 = sum( arg1=10, arg2=20 ); //here total1 is 30. We use arg1 to specify that 10 is for arg1, so on. This allows to place args out of order
print total; => here total is printed as 0, as it's global var
Passing func as an arg: We can also pass a func as an arg to another func
ex:
def
shout(text):
return
text.upper()
def
greet(func1): => Arg of greet function is func1
greeting
=
func1(
"hi"
) => func1 is called with arg specified
print
(greeting)
greet(shout) => This calls greet func with arg "shout", which is itself a func. shout gets called with arg "hi", so o/p returned is HI.
B. anonymous function: These are functions w/o a name, and are faster way of implementing simple one line functions. "lambda"
keyword is used to create anonymous functions. This function can have any number of arguments but only one expression, which is evaluated and returned. It's also called as lambda func and can also have another function as an argument.
ex: square
=
lambda
x1:x1
*
x1 => Here, we define square as lambda func with one arg "x1". It computes square.Here lambda func is assigned a var "square", which points to the lambda func
print(square(5)) => This calls the var pointing to func "square" with arg =5. It returns 25.
ex:
cube
=
lambda
func1:func1
*
*
3 => here func1 is an arg to lambda func.
print(cube(square(2)) => here cube func is called with arg "square(2)". Now, square func is called with arg 2, which returns 4. This 4 is now cubed to get final answer
More Topics: More advanced topic are in next section.