knowledge hub

by notelanka developer team

Information_Communication_Technology_S

sinhala medium and english medium hear.

Physics pdf

sinhala medium and english medium hear.

chemistry sinhala notes

sinhala medium and english medium hear.



what is the life? How is the world created ?

--

As some religion says God was created or according to evaluation or by nature. Yes i think all in this happening as nature wants. we believe that trees, leaves, animals, humans have evolved formally according to nature and the world is born. So we are living in this human, beast world, god, ghost or alien world in this universe. after our death are we born in other world or do we have a soul again. What is the meaning of life. We who are born dying as we believe most, we who don't even belong to us, we who can't control us, who call each other the beautiful happiness of life, run away looking for me?.. Don't think these are questions for anyone in this world at any moment of their life. There are people who seek answer for them then, today and forever. They give each interpretation of them. But can we accept them? It's just their mere thought. I am also the one who write this. You accept or reject them according to the size of your wisdom and life. But the only vision that you and me accept from your heart is Buddhism. Is Buddhism not a faith but a vision? that's way. That's why Amulika should be accepted not bye a Shaddra but by a kind of Shuddra. Is that the reasonable vision that you are going to follow and accept according to the Dhamma. We were born to find a root in the world. How to dei,how to be born dead.. I feel like these scientifically or secretly arguing, trying to provide is an endless act.. It should be the suffering of life. But thinking that we are enjoying life, we follow physical things knowing that the rest of them are useless. Why don't we go to find a worldly comfort in our life..

Can it really be done. Can we forget our parents,children,job responsibilities and stay. Most people think that life is other that the world's comfort.. It is that they leave everything and let it happen according to their karma. It's not a realization of the rest of life. Just a very delicate trick you use to cover your laziness. All we need to do is know the immortality, silence in all these physical things.. Can we know that our children, jobs , parents, lose everything and we don't belong to us and none of them last forever and on the day the world is lost they all will be lost parents,lovers,children are all like this.. They may be ours in this soul in another soul. Even they can't control we can't own them everyday that they are ours. According to nature it all fades away. Imagine when this world is destroyed ,there will be no one in the world with us who we hold and hold. Then way are we craving for everything today and greedy to let go.. On other side, you will say everything else but for us can't give up. Yes we can't. Lose the bond of love for our parents and children. Live a good life without collecting money, power, knowledge. All that needs to be done. It should only be added to the noble dhamma which is the other Yawabodha..Then we won't remember their crazy relationship or their lazy abandonment. So can we live by following this most fair world nature and realizing that all things are restless, do duties for all, treat everyone fairly, and remember that what others do is following us according to the Dhamma.. Yes then we already found the way to success. All that has to be done is to walk the same path no longer. Talking the past,living in the present, realizing that the future is cool,step towards your right goal.

knowledge hub

New update tody

operating systems sinhala/english


Operating system classification.




පරිගණකයේ ඉතිහාසය


ict පරිගණක දෘඩාංග වර්ගීකරණය


ict peper


logic gate note downloade


html note downloade


2019 a.l accounting part 2


2019 ict part2


2019 a.l ict part1


A.l BS note set ,part 1-5


A.l BS note set, part 6-10


A.l BS note set, part 11-17


networing diagrams pdf


SQL all comands


My Blog

-

Total Pageviews

Popular posts

 

Results For ict sinhala notes.

වෙබ් අඩවි නිර්මානය (ICT)


*වෙබ් පිටු නිර්මාණය සදහා HTML භාවිතා කිරී




Link shared by Admin

දත්ත හා තොරතුරු ICT


*දත්ත හා තොරතුරු නිර්මාණය ,බෙදාහැරීම සහ කලමණාකරනය




Link shared by note lanka

ගොනු පද්ධති (File System)


*#FileSystem #ICTSinhalalesson #Mathsapi




Link shared by note lanka

තොරතුරු වල වියුක්ත ආතිය


*#DataInfomation #ICTSinhalalesson #Mathsapi




Link shared by note lanka

දත්ත සැකසුම් ජීවන චක්‍රය.(Data processing life cycle)


*Tags :- a/l ict notes, sinhala medium, free download, pdf




Link shared by note lanka

ගැටලු විසදීමේ ක්‍රියාවලිය (Problem Solving Process)


*Tags :- a/l ict notes, sinhala medium, free download, pdf #Alevelict




Link shared by note lanka

10.4.ෙවබ් පිටුවක් වැඩිදියුණු කිරීම සඳහා


*Tags :- a/l ict notes, sinhala medium, free download, pdf #Alevelict




Link shared by note lanka

Python - පයිතන් ක්‍රමලේඛ භාශාව


* Tags :- a/l ict notes, sinhala medium, free download, pdf




Link shared by note lanka

දත්ත සන්නිවේදනය හා පරිගනක ජාල


* Tags :- a/l ict notes, sinhala medium, free download, pdf




Link shared by note lanka

පරිගණකයෙහි දත්ත නිරූපණය


*tags alevel ict free download.pdf #mathsapi




Link shared by Admin

දත්ත සමුදාය පද්ධතීන් සැලසුම් කිරීම


*tags alevel ict free download.pdf #mathsapi




Link shared by note lanka

තොරතුරු හා සන්නිවේදන තාක්ෂණයේ නව නැඹ�


*tags alevel ict free download.pdf #mathsapi




Link shared by Admin

12 පාඩම - E commerce


*tags alevel ict free download.pdf #mathsapi




Link shared by note lanka

තාර්කික ද්වාර හා බූලීය වීජ ගණිතය


*tags alevel ict free download.pdf #mathsapi




Link shared by note lanka

දත්ත සන්නිවේදනය හා පරිගණක ජාල තාක්ෂණ�


*tags alevel ict free download.pdf #mathsapi




Link shared by note lanka

no image

 Operating system classification.

Operating systems can be categorized according to the number of users and the number of actions performed.

1. Single user signal task

Systems designed to allow only one operator to connect and perform only one program. MA dos, PC dos

2. Single user multi task

Systems that allow a user to use multiple programs at once. For example, listening to a song while editing an article, downloading a video

3. Multi user multi task

Perpetual operating systems that allow multiple users to perform multiple tasks simultaneously. These operating systems require high-capacity, efficient mainframe computers or supercomputers. Unix, windows server

4. Multi threading

In this case, several parts of a computer program are executed simultaneously. These operating systems allow you to make the most of the processor capabilities.

5. Real time

Refunds will be made immediately after input without any delay. This operating system is included in equipment used in mechanical and scientific work.

Examples - ATMs, air ticket booking systems,

characteristics

දත්ත The entered data is processed and output without any delay.

There are times when the user does not have an interface and there are smaller interfaces.

Responds in less time.

Cost is high.

Has more memory capacity and efficiency.

      6. Time sharing systems

A lot of users or applications work by allocating processor time. An example of this is when a number of people connect to the main computer through a network system.

characteristics

Immediate response time

Processor lazy time is short.

Using operating systems to control all processes in a computer
Download sinhala medium full pdf


It is essential to pay attention to the operating system, which is a key item in the software classification of the software needed to recover a computer.

Introduction to operating systems

This is the most important software needed to run a computer. An operating system controls and maintains all the processes on the computer, providing an interface to maintain the connection between the user and the hardware.





As soon as a computer is turned on, the BIOS program controls the overall performance of the computer by staying in the main memory until the operating system shuts down.

Booting the computer

Booting is the process by which a computer is powered on until it becomes usable by the user.

පසු After powering the computer, it restarts and confirms the power supply.

 Then the Bootstrap loader program in ROM is activated and the BIOS program is executed.

This checks if the computer's input and output devices are working properly. If it does not work properly, it will make a beep. This is called power on self test (POST test).

Bo The boot sector then redirects to the CMOS memory and identifies the location where the operating system should be located (often the operating system is on the hard disk and may be in other storage when formatted, such as a CD).

Master The master boot record at that location contains a set of 512 byte instructions and executes it.

It copies the operating system to the main memory and then gives control of the computer to the operating system and the user.

Evolution of operating systems.

Operating systems evolved and evolved under several conditions, from the operating system currently used in computers.

Lack of an operating system.

Original computers did not use an operating system. The tasks to be performed here are executed by the computer programmer himself by inserting them into the main memory.

characteristics

o Utilization of the processor utilization (making maximum use of the processor capability).

o Processor time wasted during input and output operations, ie the processor does not work.

o Linear layout i.e. one task after another.

o Programs are accessed directly from the computer


Simple Simple batch system

In the past, this operating system was introduced to automate some of the tasks performed by the user himself. In this case, the programs to be executed were written on a magnetic tape and given to the computer one at a time, and the output of the activated program was written on a printer or other magnetic tape and the other program was inserted into memory.




characteristics

o Implementing only one program at a time.

o No special interface to connect to a user.

o Processor laziness during input and output operations.

o Increased ability to respond.

o There is no direct access to the program.

o Use of programs written on a magnetic tape.


Mult Multi programmed batch system

This was introduced on third-generation computers to avoid wasting processor time. Here the main memory is divided into sections to send several programs to one memory at a time. (Dividend)

When one program has an input or output function, the processor executes the other program that is stored in memory.

Sharing Time sharing operating system

This allows the processor time to be directed to multiple programs at the same time, making the most of the processor utility. Here the context switch is used to store several programs in memory and execute each program at the same time. This did not waste processor time. Most of the computers we use today use this time sharing method.

Some of the key functions of an operating system.

 Resource management.

Provide an interface.

Operational management.

Protect the computer.

Providing an interface. (Interface)

This allows the user to use the computer while managing software and hardware. The interface has several modes.

1. Command line interface

Here the required data and instructions on an inductor on the computer screen should be encoded according to the correct operating rules. There should be an experienced person with special knowledge to use these interfaces. Code must be remembered. These interfaces are used in operating systems such as MS doc, unix, and linux.

python  Iterables and Iterators


  Iterator vs Iterable vs Generator

An iterable is an object that can return an iterator. Any object with state that has an __iter__ method and returns an iterator is an iterable. It may also be an object without state that implements a __getitem__ method. - The method can take indices (starting from zero) and raise an IndexError when the indices are no longer valid.
Python's str class is an example of a __getitem__ iterable.
An Iterator is an object that produces the next value in a sequence when you call next(*object*) on some object. Moreover, any object with a __next__ method is an iterator. An iterator raises StopIteration after exhausting the iterator and cannot be re-used at this point.
Iterable classes:

Iterable classes define an __iter__ and a __next__ method. Example of an iterable class:
class MyIterable:
    def __iter__(self):

         return self
    def __next__(self):
         #code
#Classic iterable object in older versions of python, __getitem__ is still supported... class MySequence:
    def __getitem__(self, index):
         if (condition):             raise IndexError         return (item)
 #Can produce a plain `iterator` instance by using iter(MySequence())
Trying to instantiate the abstract class from the collections module to better see this.
Example:
Python 2.x Version ≥ 2.3 import collections >>> collections.Iterator() >>> TypeError: Cant instantiate abstract class Iterator with abstract methods next Python 3.x Version ≥ 3.0 >>> TypeError: Cant instantiate abstract class Iterator with abstract methods __next__
Handle Python 3 compatibility for iterable classes in Python 2 by doing the following:
Python 2.x Version ≥ 2.3 class MyIterable(object): #or collections.Iterator, which I'd recommend....
     ....
python  Get the parent directory


 os.path.abspath(os.path.join(PATH_TO_GET_THE_PARENT, os.pardir))

 If the given path exists

to check if the given path exists

path = '/home/john/temp' os.path.exists(path) #this returns false if path doesn't exist or if the path is a broken symbolic link

 check if the given path is a directory, file, symbolic link, mount point etc

to check if the given path is a directory

dirname = '/home/john/python' os.path.isdir(dirname)

to check if the given path is a file

filename = dirname + 'main.py' os.path.isfile(filename)

to check if the given path is symbolic link

symlink = dirname + 'some_sym_link' os.path.islink(symlink)

to check if the given path is a mount point

mount_path = '/home' os.path.ismount(mount_path) 

 Absolute Path from Relative Path

Use os.path.abspath:

>>> os.getcwd() '/Users/csaftoiu/tmp'

 >>> os.path.abspath('foo') '/Users/csaftoiu/tmp/foo'

 >>> os.path.abspath('../foo') '/Users/csaftoiu/foo' 

>>> os.path.abspath('/foo') '/foo'

python  os.path


 os.path

This module implements some useful functions on pathnames. The path parameters can be passed as either strings, or bytes. Applications are encouraged to represent file names as (Unicode) character strings

Join Paths

To join two or more path components together, firstly import os module of python and then use following:

import os os.path.join('a', 'b', 'c')

The advantage of using os.path is that it allows code to remain compatible over all operating systems, as this uses the separator appropriate for the platform it's running on.

For example, the result of this command on Windows will be:

>>> os.path.join('a', 'b', 'c') 'a\b\c'

In an Unix OS:

>>> os.path.join('a', 'b', 'c') 'a/b/c' 

 Path Component Manipulation

To split one component off of the path:

>>> p = os.path.join(os.getcwd(), 'foo.txt')

 >>> p '/Users/csaftoiu/tmp/foo.txt'

 >>> os.path.dirname(p) '/Users/csaftoiu/tmp' 

>>> os.path.basename(p) 'foo.txt' 

>>> os.path.split(os.getcwd()) ('/Users/csaftoiu/tmp', 'foo.txt')

 >>> os.path.splitext(os.path.basename(p)) ('foo', '.txt') 

python  Read a file between a range of lines


 So let's suppose you want to iterate only between some specific lines of a file

You can make use of itertools for that

import itertools

with open('myfile.txt', 'r') as f:

    for line in itertools.islice(f, 12, 30):

        # do something here

This will read through the lines 13 to 20 as in python indexing starts from 0. So line number 1 is indexed as 0

As can also read some extra lines by making use of the next() keyword here.

And when you are using the file object as an iterable, please don't use the readline() statement here as the two techniques of traversing a file are not to be mixed together 

 Copy a directory tree

import shutil source='//192.168.1.2/Daily Reports' destination='D:\\Reports\\Today' shutil.copytree(source, destination)  
The destination directory must not exist already. 

 Copying contents of one file to a dierent file
with open(input_file, 'r') as in_file, open(output_file, 'w') as out_file:
    for line in in_file:
        out_file.write(line)
Using the shutil module:

import shutil shutil.copyfile(src, dst)

python  Checking if a file is empty


 >>> import os >>> os.stat(path_to_file).st_size == 0

or

>>> import os    >>> os.path.getsize(path_to_file) > 0

However, both will throw an exception if the file does not exist. To avoid having to catch such an error, do this:

import os def is_empty_file(fpath):      return os.path.isfile(fpath) and os.path.getsize(fpath) > 0

which will return a bool value.

python  Random File Access Using mmap


 Using the mmap module allows the user to randomly access locations in a file by mapping the file into memory. This is an alternative to using normal file operations.

import mmap

with open('filename.ext', 'r') as fd:    # 0: map the whole file    mm = mmap.mmap(fd.fileno(), 0)

    # print characters at indices 5 through 10    print mm[5:10]

    # print the line starting from mm's current position    print mm.readline()

    # write a character to the 5th index    mm[5] = 'a'

    # return mm's position to the beginning of the file    mm.seek(0)

    # close the mmap object    mm.close()

 Replacing text in a file

import fileinput
replacements = {'Search1': 'Replace1',                'Search2': 'Replace2'}
for line in fileinput.input('filename.txt', inplace=True):
    for search_for in replacements:
        replace_with = replacements[search_for]        line = line.replac
python Check whether a file or path exists


Employ the EAFP coding style and try to open it.

import errno

try:

    with open(path) as f:

        # File exists except IOError as e:

    # Raise the exception if it is not ENOENT (No such file or directory)    

if e.errno != errno.ENOENT:

        raise    # No such file or directory

This will also avoid race-conditions if another process deleted the file between the check and when it is used. This race condition could happen in the following cases:

Using the os module:

import os os.path.isfile('/path/to/some/file.txt')

Python 3.x Version ≥ 3.4

Using pathlib:

import pathlib path = pathlib.Path('/path/to/some/file.txt') if path.is_file():

    ...

To check whether a given path exists or not, you can follow the above EAFP procedure, or explicitly check the path:

import os path = "/home/myFiles/directory1"

if os.path.exists(path):    ## Do stuff 

no image

 The simplest way to iterate over a file line-by-line:

with open('myfile.txt', 'r') as fp:    for line in fp:        print(line)

readline() allows for more granular control over line-by-line iteration. The example below is equivalent to the one above:

with open('myfile.txt', 'r') as fp:    while True:        cur_line = fp.readline()

  # If the result is an empty string        if cur_line == '':            # We have reached the end of the file            break        print(cur_line)

Using the for loop iterator and readline() together is considered bad practice.

More commonly, the readlines() method is used to store an iterable collection of the file's lines:

with open("myfile.txt", "r") as fp:    lines = fp.readlines() for i in range(len(lines)):    print("Line " + str(i) + ": " + line)

This would print the following:

Line 0: hello

Line 1: world

Section 30.3: Iterate files (recursively)

To iterate all files, including in sub directories, use os.walk:

import os for root, folders, files in os.walk(root_dir):    for filename in files:        print root, filename

root_dir can be "." to start from current directory, or any other path to start from.

Python 3.x Version ≥ 3.5

If you also wish to get information about the file, you may use the more efficient method os.scandir like so:

for entry in os.scandir(path):   if not entry.name.startswith('.') and entry.is_file():       print(entry.name) 

 Getting the full contents of a file

The preferred method of file i/o is to use the with keyword. This will ensure the file handle is closed once the reading or writing has been completed.

with open('myfile.txt') as in_file:    content = in_file.read()

print(content)

or, to handle closing the file manually, you can forgo with and simply call close yourself:

in_file = open('myfile.txt', 'r') content = in_file.read() print(content)

in_file.close()

Keep in mind that without using a with statement, you might accidentally keep the file open in case an unexpected exception arises like so:

in_file = open('myfile.txt', 'r') raise Exception("oops") in_file.close()  # This will never be called 


no image

 Parameter Details filename the path to your file or, if the file is in the working directory, the filename of your file access_mode a string value that determines how the file is opened buffering an integer value used for optional line buffering

When it comes to storing, reading, or communicating data, working with the files of an operating system is both necessary and easy with Python. Unlike other languages where file input and output requires complex reading and writing objects, Python simplifies the process only needing commands to open, read/write and close the file. This topic explains how Python can interface with files on the operating system.

 File modes

 There are different modes you can open a file with, specified by the mode parameter. These include:

'r' - reading mode. The default. It allows you only to read the file, not to modify it. When using this mode the file must exist.

'w' - writing mode. It will create a new file if it does not exist, otherwise will erase the file and allow you to write to it.

'a' - append mode. It will write data to the end of the file. It does not erase the file, and the file must exist for this mode.

'rb' - reading mode in binary. This is similar to r except that the reading is forced in binary mode. This is also a default choice.

'r+' - reading mode plus writing mode at the same time. This allows you to read and write into files at the same time without having to use r and w.

'rb+' - reading and writing mode in binary. The same as r+ except the data is in binary

'wb' - writing mode in binary. The same as w except the data is in binary.

'w+' - writing and reading mode. The exact same as r+ but if the file does not exist, a new one is made. Otherwise, the file is overwritten.

'wb+' - writing and reading mode in binary mode. The same as w+ but the data is in binary.

'ab' - appending in binary mode. Similar to a except that the data is in binary.

'a+' - appending and reading mode. Similar to w+ as it will create a new file if the file does not exist. Otherwise, the file pointer is at the end of the file if it exists.

'ab+' - appending and reading mode in binary. The same as a+ except that the data is in binary.

 with open(filename, 'r') as f:     f.read() with open(filename, 'w') as f:     f.write(filedata) with open(filename, 'a') as f:     f.write('\\n' + newdata)

                       r r+ w w+ a a+ 

Read              ✔ ✔ ✘ ✔ ✘ ✔

Write             ✘ ✔ ✔ ✔ ✔ ✔ 

Creates file   ✘ ✘ ✔ ✔ ✔ ✔ 

Erases file    ✘ ✘ ✔ ✔ ✘ ✘

Python 3 added a new mode for exclusive creation so that you will not accidentally truncate or overwrite and existing file.

'x' - open for exclusive creation, will raise FileExistsError if the file already exists 'xb' - open for exclusive creation writing mode in binary. The same as x except the data is in binary. 'x+' - reading and writing mode. Similar to w+ as it will create a new file if the file does not exist. Otherwise, will raise FileExistsError. 'xb+' - writing and reading mode. The exact same as 

x+ but the data is binary x x+ 

Read                             ✘ ✔

 Write                          ✔ ✔

 Creates file                ✔ ✔ 

Erases file                  ✘ ✘ 

Initial position Start Start

Allow one to write your file open code in a more pythonic manner:

Python 3.x Version ≥ 3.3 try:    with open("fname", "r") as fout:        # Work with your open file except FileExistsError:    # Your error handling goes here

In Python 2 you would have done something like

Python 2.x Version ≥ 2.0 import os.path if os.path.isfile(fname):    with open("fname", "w") as fout:        # Work with your open file else:    # Your error handling goes here

 Initial position Start Start Start Start End End


no image

 Python 2.x Version ≥ 2.3

In Python 2.x, to continue a line with print, end the print statement with a comma. It will automatically add a space.

print "Hello,", print "World!" # Hello, World! Python 3.x Version ≥ 3.0

In Python 3.x, the print function has an optional end parameter that is what it prints at the end of the given string. By default it's a newline character, so equivalent to this:

print("Hello, ", end="\n") print("World!") # Hello, # World!

But you could pass in other strings

print("Hello, ", end="") print("World!") # Hello, World!

print("Hello, ", end="<br>") print("World!") # Hello, <br>World!

print("Hello, ", end="BREAK") print("World!") # Hello, BREAKWorld!

If you want more control over the output, you can use sys.stdout.write:

import sys

sys.stdout.write("Hello, ") sys.stdout.write("World!") # Hello, World!

no image

Python programs can read from unix pipelines. Here is a simple example how to read from stdin:

import sys

for line in sys.stdin:    print(line)

Be aware that sys.stdin is a stream. It means that the for-loop will only terminate when the stream has ended.

You can now pipe the output of another program into your python program as follows:

$ cat myfile | python myprogram.py

In this example cat myfile can be any unix command that outputs to stdout.

Alternatively, using the fileinput module can come in handy:

import fileinput for line in fileinput.input():    process(line)


Using input() and raw_input()  

Python 2.x Version ≥ 2.3

raw_input will wait for the user to enter text and then return the result as a string.

foo = raw_input("Put a message here that asks the user for input")

In the above example foo will store whatever input the user provides.

Python 3.x Version ≥ 3.0

 return float(raw_input(msg)) 

       except ValueError:

            if err_msg is not None:

                print(err_msg)

def input_number(msg, err_msg=None):

    while True:

        try:

            return float(input(msg)) 

       except ValueError:

            if err_msg is not None:

                print(err_msg)

And to use it:

user_number = input_number("input a number:

 ", "that's not a number!")

Or, if you do not want an "error message":

user_number = input_number("input a number: ") 

input will wait for the user to enter text and then return the result as a string.

foo = input("Put a message here that asks the user for input")

In the above example foo will store whatever input the user provides.

Section 29.5: Function to prompt user for a number

def input_number(msg, err_msg=None):

    while True:

        try:


no image

 Input can also be read from files. Files can be opened using the built-in function open. Using a with <command> as <name> syntax (called a 'Context Manager') makes using open and getting a handle for the file super easy:

with open('somefile.txt', 'r') as fileobj:    # write code here using fileobj

This ensures that when code execution leaves the block the file is automatically closed.

Files can be opened in different modes. In the above example the file is opened as read-only. To open an existing file for reading only use r. If you want to read that file as bytes use rb. To append data to an existing file use a. Use w to create a file or overwrite any existing files of the same name. You can use r+ to open a file for both reading and writing. The first argument of open() is the filename, the second is the mode. If mode is left blank, it will default to r.

# let's create an example file: with open('shoppinglist.txt', 'w') as fileobj:    fileobj.write('tomato\npasta\ngarlic')

with open('shoppinglist.txt', 'r') as fileobj:    # this method makes a list where each line    # of the file is an element in the list    lines = fileobj.readlines()

print(lines) # ['tomato\n', 'pasta\n', 'garlic']

with open('shoppinglist.txt', 'r') as fileobj:

 # here we read the whole content into one string:    content = fileobj.read()    # get a list of lines, just like int the previous example:    lines = content.split('\n')

print(lines) # ['tomato', 'pasta', 'garlic']

If the size of the file is tiny, it is safe to read the whole file contents into memory. If the file is very large it is often better to read line-by-line or by chunks, and process the input in the same loop. To do that:

with open('shoppinglist.txt', 'r') as fileobj:    # this method reads line by line:    lines = []    for line in fileobj:        lines.append(line.strip())

When reading files, be aware of the operating system-specific line-break characters. Although for line in fileobj automatically strips them off, it is always safe to call strip() on the lines read, as it is shown above.

Opened files (fileobj in the above examples) always point to a specific location in the file. When they are first opened the file handle points to the very beginning of the file, which is the position 0. The file handle can display its current position with tell:

fileobj = open('shoppinglist.txt', 'r') pos = fileobj.tell() print('We are at %u.' % pos) # We are at 0.

Upon reading all the content, the file handler's position will be pointed at the end of the file:

content = fileobj.read() end = fileobj.tell() print('This file was %u characters long.' % end) # This file was 22 characters long. fileobj.close()

The file handler position can be set to whatever is needed:

fileobj = open('shoppinglist.txt', 'r') fileobj.seek(7) pos = fileobj.tell() print('We are at character #%u.' % pos)

You can also read any length from the file content during a given call. To do this pass an argument for read(). When read() is called with no argument it will read until the end of the file. If you pass an argument it will read that number of bytes or characters, depending on the mode (rb and r respectively):

# reads the next 4 characters # starting at the current position next4 = fileobj.read(4) # what we got? print(next4) # 'cucu' # where we are now? pos = fileobj.tell() print('We are at %u.' % pos) # We are at 11, as we was at 7, and read 4 chars.

fileobj.close()

To demonstrate the difference between characters and bytes:

with open('shoppinglist.txt', 'r') as fileobj:    print(type(fileobj.read())) # <class 'str'>

with open('shoppinglist.txt', 'rb') as fileobj:    print(type(fileobj.read())) # <class 'bytes'> 

no image

  Using the print function

Python 3.x Version ≥ 3.0

In Python 3, print functionality is in the form of a function

Input from a File

Input can also be read from files. Files can be opened using the built-in function open. Using a with <command> as <name> syntax (called a 'Context Manager') makes using open and getting a handle for the file super easy:

with open('somefile.txt', 'r') as fileobj:    # write code here using fileobj

This ensures that when code execution leaves the block the file is automatically closed.

Files can be opened in different modes. In the above example the file is opened as read-only. To open an existing file for reading only use r. If you want to read that file as bytes use rb. To append data to an existing file use a. Use w to create a file or overwrite any existing files of the same name. You can use r+ to open a file for both reading and writing. The first argument of open() is the filename, the second is the mode. If mode is left blank, it will default to r.

# let's create an example file: with open('shoppinglist.txt', 'w') as fileobj:    fileobj.write('tomato\npasta\ngarlic')

with open('shoppinglist.txt', 'r') as fileobj:    # this method makes a list where each line    # of the file is an element in the list    lines = fileobj.readlines()

print(lines) # ['tomato\n', 'pasta\n', 'garlic']

with open('shoppinglist.txt', 'r') as fileobj:

 Tuple Are Element-wise Hashable and Equatable

hash( (1, 2) )  # ok hash( ([], {"hello"})  # not ok, since lists and sets are not hashabe

Thus a tuple can be put inside a set or as a key in a dict only if each of its elements can.

{ (1, 2) } #  ok 

{ ([], {"hello"}) ) # not ok 



python  Built-in Tuple Functions

 Tuples support the following build-in functions

Comparison

If elements are of the same type, python performs the comparison and returns the result. If elements are different types, it checks whether they are numbers.

If numbers, perform comparison. If either element is a number, then the other element is returned. Otherwise, types are sorted alphabetically .

If we reached the end of one of the lists, the longer list is "larger." If both list are same it returns 0.

tuple1 = ('a', 'b', 'c', 'd', 'e') tuple2 = ('1','2','3')


python  Packing and Unpacking Tuples

 Tuples in Python are values separated by commas. Enclosing parentheses for inputting tuples are optional, so the two assignments

a = 1, 2, 3   # a is the tuple (1, 2, 3)

and

a = (1, 2, 3) # a is the tuple (1, 2, 3)

are equivalent. The assignment a = 1, 2, 3 is also called packing because it packs values together in a tuple.

Note that a one-value tuple is also a tuple. To tell Python that a variable is a tuple and not a single value you can use a trailing comma



 pyhton Tuples are immutable

 One of the main differences between lists and tuples in Python is that tuples are immutable, that is, one cannot add or modify items once the tuple is initialized. For example:


You can use the += operator to "append" to a tuple - this works by creating a new tuple with the new element you "appended" and assign it to its current variable; the old tuple is not changed, but replaced!
This avoids converting to and from a list, but this is slow and is a bad practice, especially if you're going to append multiple times. 
python  Tuple

 A tuple is an immutable list of values. Tuples are one of Python's simplest and most common collection types, and can be created with the comma operator (value = 1, 2, 3). 



python Filter

 Parameter Details function callable that determines the condition or None then use the identity function for filtering (positionalonly) iterable iterable that will be filtered (positional-only) Section 26.1: Basic use of filter

To filter discards elements of a sequence based on some criteria:


 Filter as short-circuit check
filter (python 3.x) and ifilter (python 2.x) return a generator so they can be very handy when creating a shortcircuit test like or or and:




Complementary function: filterfalse, ifilterfalse





Linked lists in python

  Linked lists

A linked list is a collection of nodes, each made up of a reference and a value. Nodes are strung together into a sequence using their references. Linked lists can be used to implement more complex data structures like lists, stacks, queues, and associative arrays. 

 Single linked list example

This example implements a linked list with many of the same methods as that of the built-in list object.



class Node:   

 def __init__(self, val):      

  self.data = val 

       self.next = None

    def getData(self): 

       return self.data

    def getNext(self):   

     return self.next

    def setData(self, val):    

    self.data = val

    def setNext(self, val): 

       self.next = val

class LinkedList:    def __init__(self):  

      self.head = None

    def isEmpty(self): 

       """Check if the list is empty"""        return self.head is None

    def add(self, item): 

       """Add the item to the list"""        new_node = Node(item)        new_node.setNext(self.head)        self.head = new_node

    def size(self):

        """Return the length/size of the list"""        count = 0        current = self.head        while current is not None:            count += 1            current = current.getNext()        return count

    def search(self, item):   

     """Search for item in list. If found, return True. If not found, return False"""        current = self.head        found = False        while current is not None and not found: 

 

          if current.getData() is item: 

               found = True            else:                current = current.getNext()

 return found

    def remove(self, item):        """Remove item from list. If item is not found in list, raise ValueError"""        current = self.head        previous = None        found = False        while current is not None and not found:  

          if current.getData() is item:                found = True            else:                previous = current                current = current.getNext()        if found:            if previous is None:                self.head = current.getNext()           

 else:  

              previous.setNext(current.getNext())      

  else:   

         raise ValueError            print 'Value not found.'

    def insert(self, position, item): 

       """        Insert item at position specified. If position specified is        out of bounds, raise IndexError        """        if position > self.size() - 1:  

          raise IndexError            print "Index out of bounds."        current = self.head        previous = None        pos = 0        if position is 0: 


           self.add(item)        else:  

          new_node = Node(item)            while pos < position:                pos += 1                previous = current                current = current.getNext()            previous.setNext(new_node)            new_node.setNext(current)

    def index(self, item): 

       """        Return the index where item is found.        If item is not found, return None.        """        current = self.head        pos = 0        found = False        while current is not None and not found: 

           if current.getData() is item:                found = True            else: 

               current = current.getNext()                pos += 1        if found:            pass        else:

            pos = None

 return pos

    def pop(self, position = None):        """        If no argument is provided, return and remove the item at the head.        If position is provided, return and remove the item at that position.        If index is out of bounds, raise IndexError        """        if position > self.size():            print 'Index out of bounds'            raise IndexError                   current = self.head        if position is None:            ret = current.getData()            self.head = current.getNext()        else:            pos = 0            previous = None            while pos < position:                previous = current                current = current.getNext()                pos += 1                ret = current.getData()            previous.setNext(current.getNext())        print ret        return ret

    def append(self, item):        """Append item to the end of the list"""        current = self.head        previous = None        pos = 0        length = self.size()        while pos < length:            previous = current            current = current.getNext()            pos += 1        new_node = Node(item)        if previous is None:            new_node.setNext(current)            self.head = new_node        else:            previous.setNext(new_node)

    def printList(self):        """Print the list"""        current = self.head        while current is not None:            print current.getData()            current = current.getNext()

Usage functions much like that of the built-in list.

ll = LinkedList() ll.add('l') ll.add('H') ll.insert(1,'e') ll.append('l') ll.append('o') ll.printList()

no image

Built in Modules and Functions 

A module is a file containing Python definitions and statements. Function is a piece of code which execute some logic.

>>> pow(2,3)    #8

To check the built in function in python we can use dir(). If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attribute of the given object, and of attributes reachable from it.

>>> dir(__builtins__) [    'ArithmeticError',    'AssertionError',    'AttributeError',    'BaseException',    'BufferError',    'BytesWarning',    'DeprecationWarning',    'EOFError',    'Ellipsis',    'EnvironmentError',    'Exception',    'False',    'FloatingPointError',    'FutureWarning',    'GeneratorExit',    'IOError',    'ImportError',    'ImportWarning',    'IndentationError',    'IndexError',    'KeyError',    'KeyboardInterrupt',    'LookupError',    'MemoryError',    'NameError',    'None',    'NotImplemented',    'NotImplementedError',    'OSError',    'OverflowError',    'PendingDeprecationWarning',    'ReferenceError',    'RuntimeError',    'RuntimeWarning',    'StandardError',    'StopIteration',    'SyntaxError',    'SyntaxWarning',    'SystemError',    'SystemExit',    'TabError',    'True',    'TypeError',    'UnboundLocalError',    'UnicodeDecodeError',    'UnicodeEncodeError',    'UnicodeError',    'UnicodeTranslateError',    'UnicodeWarning',    'UserWarning',    'ValueError',    'Warning',    'ZeroDivisionError',    '__debug__',    '__doc__',

 '__import__',    '__name__',    '__package__',    'abs',    'all',    'any',    'apply',    'basestring',    'bin',    'bool',    'buffer',    'bytearray',    'bytes',    'callable',    'chr',    'classmethod',    'cmp',    'coerce',    'compile',    'complex',    'copyright',    'credits',    'delattr',    'dict',    'dir',    'divmod',    'enumerate',    'eval',    'execfile',    'exit',    'file',    'filter',    'float',    'format',    'frozenset',    'getattr',    'globals',    'hasattr',    'hash',    'help',    'hex',    'id',    'input',    'int',    'intern',    'isinstance',    'issubclass',    'iter',    'len',    'license',    'list',    'locals',    'long',    'map',    'max',    'memoryview',    'min',    'next',    'object',    'oct',    'open',    'ord',


To know the functionality of any function, we can use built in function help .

>>> help(max) Help on built-in function max in module __builtin__: max(...)    max(iterable[, key=func]) -> value    max(a, b, c, ...[, key=func]) -> value    With a single iterable argument, return its largest item.    With two or more arguments, return the largest argument.

Built in modules contains extra functionalities. For example to get square root of a number we need to include math module.

>>> import math >>> math.sqrt(16) # 4.0

To know all the functions in a module we can assign the functions list to a variable, and then print the variable.

>>> import math >>> dir(math)

   ['__doc__', '__name__', '__package__', 'acos', 'acosh',   'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign',   'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1',   'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma',   'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10',   'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt',   'tan', 'tanh', 'trunc']

it seems __doc__ is useful to provide some documentation in, say, functions

no image

 Interactive input

To get input from the user, use the input function (note: in Python 2.x, the function is called raw_input instead, although Python 2.x has its own version of input that is completely different):

Python 2.x Version ≥ 2.3 name = raw_input("What is your name? ") # Out: What is your name? _

Security Remark Do not use input() in Python2 - the entered text will be evaluated as if it were a Python expression (equivalent to eval(input()) in Python3), which might easily become a vulnerability. See this article for further information on the risks of using this function.

Python 3.x Version ≥ 3.0 name = input("What is your name? ") # Out: What is your name? _

The remainder of this example will be using Python 3 syntax.

The function takes a string argument, which displays it as a prompt and returns a string. The above code provides a prompt, waiting for the user to input.

name = input("What is your name? ") # Out: What is your name?

If the user types "Bob" and hits enter, the variable name will be assigned to the string "Bob":

name = input("What is your name? ") # Out: What is your name? Bob print(name) # Out: Bob

Note that the input is always of type str, which is important if you want the user to enter numbers. Therefore, you need to convert the str before trying to use it as a number:

x = input("Write a number:") # Out: Write a number: 10 x / 2 # Out: TypeError: unsupported operand type(s) for /: 'str' and 'int' float(x) / 2 # Out: 5.0

NB: It's recommended to use try/except blocks to catch exceptions when dealing with user inputs. For instance, if your code wants to cast a raw_input into an int, and what the user writes is uncastable, it raises a ValueError

no image

 IDLE - Python GUI

IDLE is Python’s Integrated Development and Learning Environment and is an alternative to the command line. As the name may imply, IDLE is very useful for developing new code or learning python. On Windows this comes with the Python interpreter, but in other operating systems you may need to install it through your package manager.

The main purposes of IDLE are:

Multi-window text editor with syntax highlighting, autocompletion, and smart indent Python shell with syntax highlighting Integrated debugger with stepping, persistent breakpoints, and call stack visibility Automatic indentation (useful for beginners learning about Python's indentation)

Saving the Python program as .py files and run them and edit them later at any them using IDLE.

In IDLE, hit F5 or run Python Shell to launch an interpreter. Using IDLE can be a better learning experience for new users because code is interpreted as the user writes.

Note that there are lots of alternatives, see for example this discussion or this list.

Troubleshooting

Windows

If you're on Windows, the default command is python. If you receive a "'python' is not recognized" error, the most likely cause is that Python's location is not in your system's PATH environment variable. This can be accessed by right-clicking on 'My Computer' and selecting 'Properties' or by navigating to 'System' through 'Control Panel'. Click on 'Advanced system settings' and then 'Environment Variables...'. Edit the PATH variable to include the directory of your Python installation, as well as the Script folder (usually C:\Python27;C:\Python27\Scripts). This requires administrative privileges and may require a restart.

When using multiple versions of Python on the same machine, a possible solution is to rename one of the python.exe files. For example, naming one version python27.exe would cause python27 to become the Python command for that version.

You can also use the Python Launcher for Windows, which is available through the installer and comes by default. It allows you to select the version of Python to run by using py -[x.y] instead of python[x.y]. You can use the latest version of Python 2 by running scripts with py -2 and the latest version of Python 3 by running scripts with py -3.

Debian/Ubuntu/MacOS

This section assumes that the location of the python executable has been added to the PATH environment variable.

If you're on Debian/Ubuntu/MacOS, open the terminal and type python for Python 2.x or python3 for Python 3.x.

Type which python to see which Python interpreter will be used.

Arch Linux

The default Python on Arch Linux (and descendants) is Python 3, so use python or python3 for Python 3.x and python2 for Python 2.x.

Other systems

Python 3 is sometimes bound to python instead of python3. To use Python 2 on these systems where it is installed, you can use python2.

no image

 Python uses indentation to define control and loop constructs. This contributes to Python's readability, however, it requires the programmer to pay close attention to the use of whitespace. Thus, editor miscalibration could result in code that behaves in unexpected ways.

Python uses the colon symbol (:) and indentation for showing where blocks of code begin and end (If you come from another language, do not confuse this with somehow being related to the ternary operator). That is, blocks in Python, such as functions, loops, if clauses and other constructs, have no ending identifiers. All blocks start with a colon and then contain the indented lines below it.

For example:

def my_function():    # This is a function definition. Note the colon (:)    a = 2             # This line belongs to the function because it's indented    return a          # This line also belongs to the same function print(my_function())  # This line is OUTSIDE the function block

or

if a > b:             # If block starts here    print(a)          # This is part of the if block else:                 # else must be at the same level as if    print(b)          # This line is part of the else block

Blocks that contain exactly one single-line statement may be put on the same line, though this form is generally not considered good style:

if a > b: print(a) else: print(b)  

Attempting to do this with more than a single statement will not work:

if x > y: y = x    print(y) # IndentationError: unexpected indent

if x > y: while y != z: y -= 1  # SyntaxError: invalid syntax

An empty block causes an IndentationError. Use pass (a command that does nothing) when you have a block with no content:

def will_be_implemented_later():    pass Spaces vs. Tabs

In short: always use 4 spaces for indentation.

Using tabs exclusively is possible but PEP 8, the style guide for Python code, states that spaces are preferred.

Python 3.x Version ≥ 3.0

Python 3 disallows mixing the use of tabs and spaces for indentation. In such case a compile-time error is generated: Inconsistent use of tabs and spaces in indentation and the program will not run.

Python 2.x Version ≤ 2.7


Python 2 allows mixing tabs and spaces in indentation; this is strongly discouraged. The tab character completes the previous indentation to be a multiple of 8 spaces. Since it is common that editors are configured to show tabs as multiple of 4 spaces, this can cause subtle bugs.

Citing PEP 8:

When invoking the Python 2 command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!

Many editors have "tabs to spaces" configuration. When configuring the editor, one should differentiate between the tab character ('\t') and the  Tab  key.

The tab character should be configured to show 8 spaces, to match the language semantics - at least in cases when (accidental) mixed indentation is possible. Editors can also automatically convert the tab character to spaces. However, it might be helpful to configure the editor so that pressing the  Tab  key will insert 4 spaces, instead of inserting a tab character.

Python source code written with a mix of tabs and spaces, or with non-standard number of indentation spaces can be made pep8-conformant using autopep8. (A less powerful alternative comes with most Python installations: reindent.py) Section 1.4: Datatypes

Built-in Types Booleans

bool: A boolean value of either True or False. Logical operations like and, or, not can be performed on booleans.

x or y    # if x is False then y otherwise x x and y   # if x is False then x otherwise y not x     # if x is True then False, otherwise True

In Python 2.x and in Python 3.x, a boolean is also an int. The bool type is a subclass of the int type and True and False are its only instances:

issubclass(bool, int) # True

isinstance(True, bool) # True isinstance(False, bool) # True

If boolean values are used in arithmetic operations, their integer values (1 and 0 for True and False) will be used to return an integer result:

True + False == 1 # 1 + 0 == 1 True * True  == 1 # 1 * 1 == 1

Numbers

int: Integer number

a = 2 b = 100 c = 123456789 d = 38563846326424324

Integers in Python are of arbitrary sizes.

Note: in older versions of Python, a long type was available and this was distinct from int. The two have been unified.

float: Floating point number; precision depends on the implementation and system architecture, for CPython the float datatype corresponds to a C double.

a = 2.0 b = 100.e0 c = 123456789.e1

complex: Complex numbers

a = 2 + 1j b = 100 + 10j

The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number.

Strings Python 3.x Version ≥ 3.0

str: a unicode string. The type of 'hello' bytes: a byte string. The type of b'hello'

Python 2.x Version ≤ 2.7

str: a byte string. The type of 'hello' bytes: synonym for str unicode: a unicode string. The type of u'hello'

Sequences and collections

Python differentiates between ordered sequences and unordered collections (such as set and dict).

strings (str, bytes, unicode) are sequences

reversed: A reversed order of str with reversed function

a = reversed('hello')

tuple: An ordered collection of n values of any type (n >= 0).

a = (1, 2, 3) b = ('a', 1, 'python', (1, 2)) b[2] = 'something else' # returns a TypeError

Supports indexing; immutable; hashable if all its members are hashable

list: An ordered collection of n values (n >= 0)

a = [1, 2, 3] b = ['a', 1, 'python', (1, 2), [1, 2]] b[2] = 'something else' # allowed

Not hashable; mutable.

set: An unordered collection of unique values. Items must be hashable.

a = {1, 2, 'a'}

dict: An unordered collection of unique key-value pairs; keys must be hashable.

a = {1: 'one',     2: 'two'}

b = {'a': [1, 2, 3],     'b': 'a string'}

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare equality must have the same hash value.

Built-in constants

In conjunction with the built-in datatypes there are a small number of built-in constants in the built-in namespace:

True: The true value of the built-in type bool False: The false value of the built-in type bool None: A singleton object used to signal that a value is absent. Ellipsis or ...: used in core Python3+ anywhere and limited usage in Python2.7+ as part of array notation. numpy and related packages use this as a 'include everything' reference in arrays. NotImplemented: a singleton used to indicate to Python that a special method doesn't support the specific arguments, and Python will try alternatives if available.

a = None # No value will be assigned. Any valid datatype can be assigned later Python 3.x Version ≥ 3.0

None doesn't have any natural ordering. Using ordering comparison operators (<, <=, >=, >) isn't supported anymore and will raise a TypeError.

Python 2.x Version ≤ 2.7

None is always less than any number (None < -32 evaluates to True).

Testing the type of variables

In python, we can check the datatype of an object using the built-in function type.

a = '123' print(type(a))

# Out: <class 'str'> b = 123 print(type(b)) # Out: <class 'int'>

In conditional statements it is possible to test the datatype with isinstance. However, it is usually not encouraged to rely on the type of the variable.

i = 7 if isinstance(i, int):    i += 1 elif isinstance(i, str):    i = int(i)    i += 1

For information on the differences between type() and isinstance() read: Differences between isinstance and type in Python

To test if something is of NoneType:

x = None if x is None:    print('Not a surprise, I just defined x as None.') Converting between datatypes

You can perform explicit datatype conversion.

For example, '123' is of str type and it can be converted to integer using int function.

a = '123' b = int(a)

Converting from a float string such as '123.456' can be done using float function.

a = '123.456' b = float(a) c = int(a)    # ValueError: invalid literal for int() with base 10: '123.456' d = int(b)    # 123

You can also convert sequence or collection types

a = 'hello' list(a)  # ['h', 'e', 'l', 'l', 'o'] set(a)   # {'o', 'e', 'l', 'h'} tuple(a) # ('h', 'e', 'l', 'l', 'o') Explicit string type at definition of literals

With one letter labels just in front of the quotes you can tell what type of string you want to define.

b'foo bar': results bytes in Python 3, str in Python 2 u'foo bar': results str in Python 3, unicode in Python 2 'foo bar': results str r'foo bar': results so called raw string, where escaping special characters is not necessary, everything is taken verbatim as you typed

normal  = 'foo\nbar'   # foo

                     # bar escaped = 'foo\\nbar'  # foo\nbar  raw     = r'foo\nbar'  # foo\nbar Mutable and Immutable Data Types

An object is called mutable if it can be changed. For example, when you pass a list to some function, the list can be changed:

def f(m):    m.append(3)  # adds a number to the list. This is a mutation.

x = [1, 2] f(x) x == [1, 2]  # False now, since an item was added to the list

An object is called immutable if it cannot be changed in any way. For example, integers are immutable, since there's no way to change them:

def bar():    x = (1, 2)    g(x)    x == (1, 2)  # Will always be True, since no function can change the object (1, 2)

Note that variables themselves are mutable, so we can reassign the variable x, but this does not change the object that x had previously pointed to. It only made x point to a new object.

Data types whose instances are mutable are called mutable data types, and similarly for immutable objects and datatypes.

Examples of immutable Data Types:

int, long, float, complex str bytes tuple frozenset

Examples of mutable Data Types:

bytearray list set dict Section 1.5: Collection Types

There are a number of collection types in Python. While types such as int and str hold a single value, collection types hold multiple values.

Lists

The list type is probably the most commonly used collection type in Python. Despite its name, a list is more like an array in other languages, mostly JavaScript. In Python, a list is merely an ordered collection of valid Python values. A list can be created by enclosing values, separated by commas, in square brackets:

int_list = [1, 2, 3] string_list = ['abc', 'defghi']

A list can be empty:

empty_list = []

The elements of a list are not restricted to a single data type, which makes sense given that Python is a dynamic language:

mixed_list = [1, 'abc', True, 2.34, None]

A list can contain another list as its element:

nested_list = [['a', 'b', 'c'], [1, 2, 3]]

The elements of a list can be accessed via an index, or numeric representation of their position. Lists in Python are zero-indexed meaning that the first element in the list is at index 0, the second element is at index 1 and so on:

names = ['Alice', 'Bob', 'Craig', 'Diana', 'Eric'] print(names[0]) # Alice print(names[2]) # Craig

Indices can also be negative which means counting from the end of the list (-1 being the index of the last element). So, using the list from the above example:

print(names[-1]) # Eric print(names[-4]) # Bob

Lists are mutable, so you can change the values in a list:

names[0] = 'Ann' print(names) # Outputs ['Ann', 'Bob', 'Craig', 'Diana', 'Eric']

Besides, it is possible to add and/or remove elements from a list:

Append object to end of list with L.append(object), returns None.

names = ['Alice', 'Bob', 'Craig', 'Diana', 'Eric'] names.append("Sia") print(names) # Outputs ['Alice', 'Bob', 'Craig', 'Diana', 'Eric', 'Sia']

Add a new element to list at a specific index. L.insert(index, object)

names.insert(1, "Nikki") print(names) # Outputs ['Alice', 'Nikki', 'Bob', 'Craig', 'Diana', 'Eric', 'Sia']

Remove the first occurrence of a value with L.remove(value), returns None

names.remove("Bob") print(names) # Outputs ['Alice', 'Nikki', 'Craig', 'Diana', 'Eric', 'Sia']

one_member_tuple = tuple(['Only member'])

Dictionaries

A dictionary in Python is a collection of key-value pairs. The dictionary is surrounded by curly braces. Each pair is separated by a comma and the key and value are separated by a colon. Here is an example:

state_capitals = {    'Arkansas': 'Little Rock',    'Colorado': 'Denver',    'California': 'Sacramento',    'Georgia': 'Atlanta' }

To get a value, refer to it by its key:

ca_capital = state_capitals['California']

You can also get all of the keys in a dictionary and then iterate over them:

for k in state_capitals.keys():    print('{} is the capital of {}'.format(state_capitals[k], k))

Dictionaries strongly resemble JSON syntax. The native json module in the Python standard library can be used to convert between JSON and dictionaries.

set

A set is a collection of elements with no repeats and without insertion order but sorted order. They are used in situations where it is only important that some things are grouped together, and not what order they were included. For large groups of data, it is much faster to check whether or not an element is in a set than it is to do the same for a list.

Defining a set is very similar to defining a dictionary:

first_names = {'Adam', 'Beth', 'Charlie'}

Or you can build a set using an existing list:

my_list = [1,2,3] my_set = set(my_list)

Check membership of the set using in:

if name in first_names:    print(name)

You can iterate over a set exactly like a list, but remember: the values will be in an arbitrary, implementationdefined order.

defaultdict

A defaultdict is a dictionary with a default value for keys, so that keys for which no value has been explicitly defined can be accessed without errors. defaultdict is especially useful when the values in the dictionary are collections (lists, dicts, etc) in the sense that it does not need to be initialized every time when a new key is used.

no image

  Creating variables and assigning values

To create a variable in Python, all you need to do is specify the variable name, and then assign a value to it.

<variable name> = <value>

Python uses = to assign values to variables. There's no need to declare a variable in advance (or to assign a data type to it), assigning a value to a variable itself declares and initializes the variable with that value. There's no way to declare a variable without assigning it an initial value.

# Integer a = 2 print(a) # Output: 2

# Integer    b = 9223372036854775807 print(b) # Output: 9223372036854775807

# Floating point pi = 3.14 print(pi) # Output: 3.14

# String c = 'A' print(c) # Output: A

# String    name = 'John Doe' print(name) # Output: John Doe

# Boolean    q = True print(q) # Output: True

# Empty value or null data type x = None print(x) # Output: None

Variable assignment works from left to right. So the following will give you an syntax error.

0 = x => Output: SyntaxError: can't assign to literal

You can not use python's keywords as a valid variable name. You can see the list of keyword by:

import keyword print(keyword.kwlist)

Rules for variable naming:

Variables names must start with a letter or an underscore.1.

 x  = True   # valid _y = True   # valid

 9x = False  # starts with numeral => SyntaxError: invalid syntax  

 $y = False #  starts with symbol => SyntaxError: invalid syntax

The remainder of your variable name may consist of letters, numbers and underscores.2.

has_0_in_it = "Still Valid"

Names are case sensitive.3.

x = 9  y = X*5  =>NameError: name 'X' is not defined

Even though there's no need to specify a data type when declaring a variable in Python, while allocating the necessary area in memory for the variable, the Python interpreter automatically picks the most suitable built-in type for it:

a = 2 print(type(a)) # Output: <type 'int'>

b = 9223372036854775807 print(type(b)) # Output: <type 'int'>

pi = 3.14 print(type(pi)) # Output: <type 'float'>

c = 'A' print(type(c)) # Output: <type 'str'>

name = 'John Doe' print(type(name)) # Output: <type 'str'>

q = True print(type(q)) # Output: <type 'bool'>

x = None print(type(x)) # Output: <type 'NoneType'>

Now you know the basics of assignment, let's get this subtlety about assignment in python out of the way.

When you use = to do an assignment operation, what's on the left of = is a name for the object on the right. Finally, what = does is assign the reference of the object on the right to the name on the left.

That is:

a_name = an_object  # "a_name" is now a name for the reference to the object "an_object"

So, from many assignment examples above, if we pick pi = 3.14, then pi is a name (not the name, since an object can have multiple names) for the object 3.14. If you don't understand something below, come back to this point and read this again! Also, you can take a look at this for a better understanding.

You can assign multiple values to multiple variables in one line. Note that there must be the same number of arguments on the right and left sides of the = operator:

a, b, c = 1, 2, 3 print(a, b, c) # Output: 1 2 3

a, b, c = 1, 2 => Traceback (most recent call last): =>   File "name.py", line N, in <module> =>     a, b, c = 1, 2 => ValueError: need more than 2 values to unpack

a, b = 1, 2, 3 => Traceback (most recent call last): =>   File "name.py", line N, in <module> =>     a, b = 1, 2, 3 => ValueError: too many values to unpack

The error in last example can be obviated by assigning remaining values to equal number of arbitrary variables. This dummy variable can have any name, but it is conventional to use the underscore (_) for assigning unwanted values:

a, b, _ = 1, 2, 3 print(a, b) # Output: 1, 2

Note that the number of _ and number of remaining values must be equal. Otherwise 'too many values to unpack error' is thrown as above:

a, b, _ = 1,2,3,4 =>Traceback (most recent call last): =>File "name.py", line N, in <module> =>a, b, _ = 1,2,3,4 =>ValueError: too many values to unpack (expected 3)

You can also assign a single value to several variables simultaneously.

a = b = c = 1 print(a, b, c)


# Output: 1 1 1

When using such cascading assignment, it is important to note that all three variables a, b and c refer to the same object in memory, an int object with the value of 1. In other words, a, b and c are three different names given to the same int object. Assigning a different object to one of them afterwards doesn't change the others, just as expected:

a = b = c = 1    # all three names a, b and c refer to same int object with value 1 print(a, b, c) # Output: 1 1 1 b = 2            # b now refers to another int object, one with a value of 2 print(a, b, c) # Output: 1 2 1  # so output is as expected.

The above is also true for mutable types (like list, dict, etc.) just as it is true for immutable types (like int, string, tuple, etc.):

x = y = [7, 8, 9]   # x and y refer to the same list object just created, [7, 8, 9] x = [13, 8, 9]      # x now refers to a different list object just created, [13, 8, 9] print(y)            # y still refers to the list it was first assigned # Output: [7, 8, 9]

So far so good. Things are a bit different when it comes to modifying the object (in contrast to assigning the name to a different object, which we did above) when the cascading assignment is used for mutable types. Take a look below, and you will see it first hand:

x = y = [7, 8, 9]     # x and y are two different names for the same list object just created, [7, 8, 9] x[0] = 13             # we are updating the value of the list [7, 8, 9] through one of its names, x in this case print(y)              # printing the value of the list using its other name # Output: [13, 8, 9]  # hence, naturally the change is reflected

Nested lists are also valid in python. This means that a list can contain another list as an element.

x = [1, 2, [3, 4, 5], 6, 7] # this is nested list print x[2] # Output: [3, 4, 5] print x[2][1] # Output: 4

Lastly, variables in Python do not have to stay the same type as which they were first defined -- you can simply use = to assign a new value to a variable, even if that value is of a different type.

a = 2 print(a) # Output: 2

a = "New value" print(a) # Output: New value

If this bothers you, think about the fact that what's on the left of = is just a name for an object. First you call the int object with value 2 a, then you change your mind and decide to give the name a to a string object, having value 'New value'. Simple, right?

ict note in A/L

3/Technology ict note in A/L/post-list

Contact Me

Get in touch