Introduction
Introduction
v=B7G5B8P8k9s&list=PL98qAXLA6afuh50qD2MdAj3ofYjZR_Phn
https://www.tutorialspoint.com/python/python_basic_syntax.htm
Chapter:1
Introduction, Features, Python building blocks – Identifiers, Keywords, Indention, Variables and
Comments,
Basic data types (Numeric, Boolean, Compound)
Operators: Arithmetic, comparison, relational, assignment, logical, bitwise, membership, identity
operators,
operator precedence
Control flow statements: Conditional statements (if, if…else, nested if)
Looping in Python (while loop, for loop, nested loops)
Loop manipulation using continue, pass, break.
Input/output Functions, Decorators, Iterators and Generators.
Version:Python 2.4.3
Python files have extension .py
Code: ITL404
Developed by Guido van Rossum
Why is it called Python? ... When he began implementing Python, Guido van Rossum was also
reading the published scripts
from “Monty Python's Flying Circus”, a BBC comedy series from the 1970s. Van Rossum
thought he needed a name that was
short, unique, and slightly mysterious, so he decided to call the language Python
----------------------------------------------------------------
*Python is a widely used high-level, general-purpose, interpreted, dynamic programming
language.
*Python is one of the easiest language to learn because of its easy syntax.
* It emphasizes code readability, and its syntax allows programmers to express concepts in
fewer lines of code than possible in languages
such as C++ or Java.
-----------------------------------------------------------------
The Structural Bioinformatics Library (SBL) is a Template C++/Python library for solving
structural biology problems.
The SBL provides programs (executables) for end-users and a rich framework todevelop novel
applications.
---------------------------------------------------------------
Features:
1. Simple and easy to understand
2.Python is freeware
C #.net is owned by microsoft
Java is owned by oracle
It means to use every library we need to pay as they are business making companies
But Python is maintained by a charitable foundation called Python software foundation( PFA)
hence free.
We dont need to pay for the software
4. Platform independent
Can run on windows, Linux OS, Ubuntu without any changes
5. Portable
Program can be transferred from one to other OS
8. Interpreted Language
Code is executed line by line
9. Embedded
It means we can use it in any other web related program to develop any full fledge software
10. Extensive library
Like stdio.h,conio.h in C Python also have more libraries
----------------------------------------------------------------------------------------
System.out.println("Hello World");
}
}
In C language
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("Hello World");
getch();
}
print("Hello World")
Colaboratory, or "Colab" for short, allows you to write and execute Python in your browser, with
The document you are reading is not a static web page, but an interactive environment called a
Colab notebook that
lets you write and execute code.
Colab notebooks allow you to combine executable code and rich text in a single document,
along with images, HTML,
LaTeX and more. When you create your own Colab notebooks, they are stored in your Google
Drive account.
You can easily share your Colab notebooks with co-workers or friends, allowing them to
comment on your notebooks
or even edit them.
-------------------------------------------------------------------------------
Keywords
These are reserved words and you cannot use them as constant or variable or any other
identifier names.
All the Python keywords contain lowercase letters only.
eg: and exec not assert finally or if else etc
-----------------------------------------------------------------------------
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment.
All characters after the # and up to the end of the physical line are part of the comment and the
Python interpreter
ignores them.
You can type a comment on the same line after a statement or expression −
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
Multiline comments
Following triple-quoted string is also ignored by Python interpreter and can be used as a
multiline comments:
'''
This is a multiline
comment.
'''
----------------------------------------------------------------------------------
variables
Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store
integers, decimals or
characters in these variables.
Assigning Values to Variables
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically
when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right
of the = operator
is the value stored in the variable.
example:
a = 100 # An integer assignment
b = 1000.0 # A floating point
name = "John" # A string
---------------------------------------------------------------------------------------
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For
example −
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are
assigned to the same memory location. You can also assign multiple objects to
multiple variables. For example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object
with the value "john" is assigned to the variable c.
--------------------------------------------------------------------------------------
Standard Data Types
The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has various
standard data types that are used to define the operations possible on them and the storage
method for each of them.
Python Numbers
Number data types store numeric values. Number objects are created when you
assign a value to them. For example −
var1 = 1
var2 = 10
You can delete a single object or multiple objects by using the del statement. For
example −
del var
del var_a, var_b
--------------------------------------------------------------------------------------------
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks.
Python allows for either pairs of single or double quotes.
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.
However, Python does not have a character data type, a single character is simply a string with
a length of 1.
example:
str = 'Hello World!'
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at
0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator,
and the asterisk (*) is the repetition operator.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator
example:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
---------------------------------------------------------------------
Python Tuples
A tuple is another sequence data type that is similar to the list.
A tuple consists of a number of values separated by commas. Unlike lists, however,
tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) )
and cannot be updated. Tuples can be thought of as read-only lists
The following code is invalid with tuple, because we attempted to update a tuple,
which is not allowed. Similar case is possible with lists −
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Dictionaries have no concept of order among elements. It is incorrect to say that the elements
are "out of order";
they are simply unordered.
---------------------------------------------------------------------------------
Python Collections (Arrays)
There are four collection data types in the Python programming language:
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are
Tuple, Set,
and Dictionary, all with different qualities and usage.
Example
Create a List:
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that order
will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has
been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
Example
String, int and boolean data types:
type()
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
What is the data type of a list?
Access Items
List items are indexed and you can access them by referring to the index number:
Example
Print the second item of the list:
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
------------------------------------------------------------------------------
Example
This example returns the items from the beginning to, but NOT including, "kiwi":
Example
Change the second item:
Example
Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":
Example
Change the second value by replacing it with two new values:
Example
Insert "watermelon" as the third item:
Example
Using the append() method to append an item:
Example
Insert an item as the second position:
Example
Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
---------------------------------------------------------------------
Remove Specified Item
The remove() method removes the specified item.
Example
Remove "banana":
Example
Remove the second item:
Example
Delete the entire list:
Example
Clear the list content:
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are
List, Set, and
Dictionary, all with different qualities and usage.
Example
Create a Tuple:
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that
order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple
has been created.
Allow Duplicates
Since tuple are indexed, tuples can have items with the same value:
Example
Tuples allow duplicate values:
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
Example
One item tuple, remember the commma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Example
String, int and boolean data types:
Example
A tuple with strings, integers and boolean values:
type()
From Python's perspective, tuples are defined as objects with the data type 'tuple':
<class 'tuple'>
Example
What is the data type of a tuple?
Example
Print the second item in the tuple:
Negative Indexing
Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the tuple:
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Return the third, fourth, and fifth item:
Note: The search will start at index 2 (included) and end at index 5 (not included).
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT included, "kiwi":
Example
This example returns the items from "cherry" and to the end:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
Example
Check if "apple" is present in the tuple:
But there is a workaround. You can convert the tuple into a list, change the list, and convert the
list back into a tuple.
Example
Convert the tuple into a list to be able to change it:
print(x)
Add Items
Once a tuple is created, you cannot add items to it.
Example
You cannot add items to a tuple:
Just like the workaround for changing a tuple, you can convert it into a list, add your item(s), and
convert it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
Tuples are unchangeable, so you cannot remove items from it, but you can use the same
workaround as we used for changing and adding tuple items:
Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
Example
The del keyword can delete the tuple completely:
Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called "packing" a tuple:
Example
Packing a tuple:
Example
Unpacking a tuple:
print(green)
print(yellow)
print(red)
Note: The number of variables must match the number of values in the tuple, if not, you must
use an asterix to
collect the remaining values as a list.
Using Asterix*
If the number of variables is less than the number of values, you can add an * to the variable
name and the values will be assigned to the variable as a list:
Example
Assign the rest of the values as a list called "red":
print(green)
print(yellow)
print(red)
If the asterix is added to another variable name than the last, Python will assign values to the
variable until the number of values left matches the number of variables left.
Example
Add a list of values the "tropic" variable:
print(green)
print(tropic)
print(red)
----------------------------------------------------------------------------------
Python Sets
myset = {"apple", "banana", "cherry"}
Set
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List,
Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is both unordered and unindexed.
Example
Create a Set:
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by
index or key.
Unchangeable
Sets are unchangeable, meaning that we cannot change the items after the set has been
created.
Once a set is created, you cannot change its items, but you can add new items.
Example
Duplicate values will be ignored:
print(thisset)
Example
Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Example
String, int and boolean data types:
Example
A set with strings, integers and boolean values:
type()
From Python's perspective, sets are defined as objects with the data type 'set':
<class 'set'>
Example
What is the data type of a set?
Access Items
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a specified value is present in a
set, by using the in keyword.
Example
Loop through the set, and print the values:
for x in thisset:
print(x)
Example
Check if "banana" is present in the set:
print("banana" in thisset)
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
Once a set is created, you cannot change its items, but you can add new items.
Example
Add an item to a set, using the add() method:
thisset.add("orange")
print(thisset)
Add Sets
To add items from another set into the current set, use the update() method.
Example
Add elements from tropical and thisset into newset:
thisset.update(tropical)
print(thisset)
thisset.update(mylist)
print(thisset)
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
Example
Remove "banana" by using the remove() method:
thisset.remove("banana")
print(thisset)
Note: If the item to remove does not exist, remove() will raise an error.
Example
Remove "banana" by using the discard() method:
thisset.discard("banana")
print(thisset)
You can also use the pop() method to remove an item, but this method will remove the last item.
Remember that sets are unordered, so you will not know what item that gets removed.
Example
Remove the last item by using the pop() method:
print(x)
print(thisset)
Note: Sets are unordered, so when using the pop() method, you do not know which item that
gets removed.
Example
The clear() method empties the set:
thisset.clear()
print(thisset)
Example
The del keyword will delete the set completely:
del thisset
print(thisset)
-------------------------------------------------------------------------------
Python Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and does not allow duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are
unordered.
Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are
unordered.
When we say that tuples are ordered, it means that the items have a defined order, and that
order will not change.
Unordered means that the items does not have a defined order, you cannot refer to an item by
using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Dictionary Length
To determine how many items a dictionary has, use the len() function:
Example
Print the number of items in the dictionary:
print(len(thisdict))
Example
String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
type()
From Python's perspective, dictionaries are defined as objects with the data type 'dict':
<class 'dict'>
Example
Print the data type of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
Get the value of the "model" key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
There is also a method called get() that will give you the same result:
Example
Get the value of the "model" key:
"year": 1964
}
x = thisdict["model"]
print(x)
x = thisdict.get("model")
print(x)
Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
Get a list of the keys:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.keys()
print(x)
The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary
will be reflected in the keys list.
Example
Add a new item to the original dictionary, and see that the value list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
car["color"] = "white"
print(car)
Example
Add a new item to the original dictionary, and see that the keys list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
car["year"] = 2020
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Update Dictionary
The update() method will update the dictionary with the items from the given argument.
Example
Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Update Dictionary
The update() method will update the dictionary with the items from a given argument. If the item
does not exist, the item will be added.
Example
Add a color item to the dictionary by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is
removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Example
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
Example
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a
reference to dict1, and changes made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Another way to make a copy is to use the built-in function dict().
Example
Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
Example
Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}