Showing posts with label Progrramming. Show all posts
Showing posts with label Progrramming. Show all posts

Phython:File Positions

The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file.

The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position.

Example:

Let's take a file foo.txt, which we have created above.
#!/usr/bin/python
 
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
 
# Check current position
position = fo.tell();
print "Current file position : ", position
 
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opend file
fo.close()
This would produce the following result:
Read String is :  Python is
Current file position :  10

Again read String is :  Python is

Phython: Reading and Writing Files

Reading and Writing Files:

The file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to read and write files.

The write() Method:

The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string:

Syntax:

fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.

Example:

#!/usr/bin/python
 
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
 
# Close opend file
fo.close()
The above method would create foo.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have following content.
Python is a great language.
Yeah its great!!

The read() Method:

The read() method reads a string from an open file. It is important to note that Python strings can have binary data and not just text.

Syntax:

fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.

Example:

Let's take a file foo.txt, which we have created above.
#!/usr/bin/python
 
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
This would produce the following result:
Read String is :  Python is

First Python Program

:

Interactive Mode Programming:

Invoking the interpreter without passing a script file as a parameter brings up the following prompt:
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
Type the following text to the right of the Python prompt and press the Enter key:
>>> print "Hello, Python!";
If you are running new version of Python, then you would need to use print statement with parenthesis like print ("Hello, Python!");. However at Python version 2.4.3, this will produce following result:
Hello, Python!

Script Mode Programming:

Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.
Let us write a simple Python program in a script. All python files will have extension .py. So put the following source code in a test.py file.
print "Hello, Python!";
Here, I assumed that you have Python interpreter set in PATH variable. Now, try to run this program as follows:
$ python test.py
This will produce the following result:
Hello, Python!
Let's try another way to execute a Python script. Below is the modified test.py file:
#!/usr/bin/python
 
print "Hello, Python!";
Here, I assumed that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows:
$ chmod +x test.py     # This is to make file executable
$./test.py
This will produce the following result:

Hello, Python!

Script from the Command-line

A Python script can be executed at command line by invoking the interpreter on your application, as in the following:
$python  script.py          # Unix/Linux

or

python% script.py           # Unix/Linux

or

C:>python script.py         # Windows/DOS
Note: Be sure the file permission mode allows execution.
(3) Integrated Development Environment
You can run Python from a graphical user interface (GUI) environment as well. All you need is a GUI application on your system that supports Python.
  • Unix: IDLE is the very first Unix IDE for Python.
  • Windows: PythonWin is the first Windows interface for Python and is an IDE with a GUI.
  • Macintosh: The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files.
Before proceeding to next chapter, make sure your environment is properly set up and working perfectly fine. If you are not able to set up the environment properly, then you can take help from your system admin.

All the examples given in subsequent chapters have been executed with Python 2.4.3 version available on CentOS flavor of Linux.

Python:Setting up PATH


Programs and other executable files can live in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables.
The path is stored in an environment variable, which is a named string maintained by the operating system. These variables contain information available to the command shell and other programs.
The path variable is named PATH in Unix or Path in Windows (Unix is case-sensitive; Windows is not).
In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path.
Setting path at Unix/Linux:
To add the Python directory to the path for a particular session in Unix:
  • In the csh shell: type
    setenv PATH "$PATH:/usr/local/bin/python" and press Enter.
  • In the bash shell (Linux): type
    export PATH="$PATH:/usr/local/bin/python" and press Enter.
  • In the sh or ksh shell: type
    PATH="$PATH:/usr/local/bin/python" and press Enter.
Note: /usr/local/bin/python is the path of the Python directory
Setting path at Windows:
To add the Python directory to the path for a particular session in Windows:
  • At the command prompt : type
    path %path%;C:\Python and press Enter.

Note: C:\Python is the path of the Python directory 

Install Python:


Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python.
If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation.
Here is a quick overview of installing Python on various platforms:
Unix & Linux Installation:
Here are the simple steps to install Python on Unix/Linux machine.
  • Open a Web browser and go to http://www.python.org/download/
  • Follow the link to download zipped source code available for Unix/Linux.
  • Download and extract files.
  • Editing the Modules/Setup file if you want to customize some options.
  • run ./configure script
  • make
  • make install
This will install python in a standard location /usr/local/bin and its libraries are installed in /usr/local/lib/pythonXX where XX is the version of Python that you are using.
Windows Installation:
Here are the steps to install Python on Windows machine.
  • Open a Web browser and go to http://www.python.org/download/
  • Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you are going to install.
  • To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Just save the installer file to your local machine and then run it to find out if your machine supports MSI.
  • Run the downloaded file by double-clicking it in Windows Explorer. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you're ready to roll!
Macintosh Installation:
Recent Macs come with Python installed, but it may be several years out of date. See http://www.python.org/download/mac/ for instructions on getting the current version along with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is available."
Jack Jansen maintains it and you can have full access to the entire documentation at his Web site - Jack Jansen Website : http://www.cwi.nl/~jack/macpython.html
Just go to this link and you will find complete installation detail for Mac OS installation.

Python Features:


Python's feature highlights include:
  • Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language in a relatively short period of time.

  • Easy-to-read: Python code is much more clearly defined and visible to the eyes.

  • Easy-to-maintain: Python's success is that its source code is fairly easy-to-maintain.

  • A broad standard library: One of Python's greatest strengths is the bulk of the library is very portable and cross-platform compatible on UNIX, Windows and Macintosh.

  • Interactive Mode: Support for an interactive mode in which you can enter results from a terminal right to the language, allowing interactive testing and debugging of snippets of code.
  • Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms.

  • Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient.

  • Databases: Python provides interfaces to all major commercial databases.

  • GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh and the X Window system of Unix.

  • Scalable: Python provides a better structure and support for large programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are listed below:

  • Support for functional and structured programming methods as well as OOP.
  • It can be used as a scripting language or can be compiled to byte-code for building large applications.
  • Very high-level dynamic data types and supports dynamic type checking.
  • Supports automatic garbage collection.
  • It can be easily integrated with C, C++, COM, ActiveX, CORBA and Java.

CPU LAB Tutorials

There are given simple to advanced level programming is given below. If you need source code then you can download the code which is given below.

Assignment 1[DOWNLOAD]

  1. Program to print your name and address.
  2. a program that reads two nos. from key board and gives their addition, subtraction, multiplication, division and modulo.
  3. Write a program that swap two values.(Using third variable).
  4.  Write a program that calculate the area and circumference of circle
  5.  A program accept year and shows, weather is leap year or not.
  6. Write a program that accept three numbers from user and display maximum out of them using nested if else.
  7. Program that accept three subject marks from user and count the total and average of them. Also calculate and display grades on basis of percentage using else if ladder.
  8. Write a program that convert days into days and months.


Assignment 2[DOWNLOAD]

  1.  Program that accept an integer from user and display whether the entered value is negative or positive until user says no. (using goto).
  2. Write a program to find sum of first N odd numbers.
  3. Write a program to display multiplication table.
  4.  Write a program to print 1+1/2+1/3+1/4+………+1/N series.
  5. Write a program to find sum of all integers greater than 100 & less than 200 and are divisible by 5.
  6. Add, subtract and multiply two nos. using switch statement.
  7. w. a. p. to compute the electricity bill. The rules for electricity charges are given as follows.


Assignment - 3[DOWNLOAD]

 Write a program for use of putchar( ) and getchar( ) function.
 Program to print Patterns.
 *
* *
** *
* * * *

1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
AAAAA
BBBB
CCC
DD
E
1
0 1
1 0 1
0 1 0 1

Assignment-4[DOWNLOAD]
1
Write a program to print Fibonacci series. 1,1,2,3,5,……N
2
Write a program to reverse the digit.
3
Write a program to add two matrixes and multiplication of two matrices.
4
Write a program to arrange given no of array in ascending order.
5
W.A.P. to accept one number from user and find if it is prime or not.
6
W.A.P to read array of integers and print it in reverse order

Assignment-5[DOWNLOAD]
1. Write a program to count total words in text.
2. Write a program to implement total no. of odd and even elements in one dimensional array and print the sum of them.
3. Find length of string using strlen( ) function,
4. Write a program to copy one string to another string.
5. Write a program to join two strings.
6. Write a program to remove all spaces in the string.
7. Find given string is palindrom or not using string library function.

Assignment-6

[DOWNLOAD]

1. Write a function program to add first N numbers.
2. Write a function find out maximum out of three numbers.
3. Write a function power that computes x raised to the power y for integer x and y and returns double type value.
4. Write a program to find factorial of a number using recursion.
5. Write a program that used user defined function Swap ( ) and interchange the value of two variable.
6. Write a function prime that return 1 if it‘s argument is prime and return 0 otherwise.
7. Write a calculator program(add,subtract,multiply,divide). Prepare user defined function for each functionality.

Assignment-7

[DOWNLOAD]

1. Define a structure type, person, that would contain person name, date of joining and salary. Using this structure, write a program to read this information for one person from the key board and print the same on the screen.
 2. Define a structure called cricket that will describe the following information:  
 a. Player name
b. Team name
c. Batting average
3. Write a function to enter rollno, marks of the three subject for 3 student and find total obtained by each student.

Assignment - 8

[DOWNLOAD]


1. Write a program using pointer and function to determine the length of string.
2. Write a program using pointer to compare two strings.
3. Write a program using pointer to concate two strings.
4. Write a program using pointer to copy one string to another string.

Assignment - 9

[DOWNLOAD]


1. Write a program that uses a table of integers whose size will be specified interactively at run time.
2. Write a program to store a character string in block of memory space created by malloc and then modify the same to store a large string.

Assignment-10

[DOWNLOAD]


1. A program to illustrate reading files contents.
2.  A program to illustrate the use of fgets( ).
3. A program to illustrate the use of fputs().