Posts Tagged ‘beginner’

Hi guys, this is a post on creating a simple text mode menu in Python 2.7.x. Hope this helps! Below is the output of the sample menu that we will be creating:

Sample Menu

------------------------------ MENU ------------------------------
1. Menu Option 1
2. Menu Option 2
3. Menu Option 3
4. Menu Option 4
5. Exit
-------------------------------------------------------------------
Enter your choice [1-5]: 

Here we have a function print_menu() which is used only to print the menu and the options available. This function does not take any inputs.

The source we have here creates a menu with 5 options with the 5th option to exit the menu.

Here, we create a Boolean variable named “loop” and set its value to “True“. Then we create a while loop which will run until the value of “loop” is “False”.

And within the while loop, we call the function print_menu() in which the user is presented with a menu and the list of options. We now request the user input and store it in a variable named “choice” [NOTE: The input must be a number and not any character or else it will through a error].

Now, we use create if statements to check the value of choice. For example: the first if statement checks if choice==1 and if it prints “Menu 1 has been selected”. Similar, We make use of elif statements to check other values of choice.

And when choice==5, we change the value of “loop” to “False” , which will end the while loop as it will only run when the value of “loop” is “True“.

Finally, for all other numbers other than 1,2,3,4 and 5, we simply print and error message and requests the user to enter a valid input and to try again.

Source Code:

## Text menu in Python
     
def print_menu():       ## Your menu design here
    print 30 * "-" , "MENU" , 30 * "-"
    print "1. Menu Option 1"
    print "2. Menu Option 2"
    print "3. Menu Option 3"
    print "4. Menu Option 4"
    print "5. Exit"
    print 67 * "-"
 
loop=True       
 
while loop:          ## While loop which will keep going until loop = False
    print_menu()    ## Displays menu
    choice = input("Enter your choice [1-5]: ")
    
    if choice==1:     
        print "Menu 1 has been selected"
        ## You can add your code or functions here
    elif choice==2:
        print "Menu 2 has been selected"
        ## You can add your code or functions here
    elif choice==3:
        print "Menu 3 has been selected"
        ## You can add your code or functions here
    elif choice==4:
        print "Menu 4 has been selected"
        ## You can add your code or functions here
    elif choice==5:
        print "Menu 5 has been selected"
        ## You can add your code or functions here
        loop=False # This will make the while loop to end as not value of loop is set to False
    else:
        # Any integer inputs other than values 1-5 we print an error message
        raw_input("Wrong option selection. Enter any key to try again..")

Feel feel to leave a comment if you have any queries or want to reach out to me. You can also Follow/Subscribe to my blog to get future blog posts! Happy Bloggin! 🙂

Regards
ΞXΤЯΞМΞ

This is a quick tutorial on reverse loops in Python 2.7.x  and also will be showing you an example on how to reverse a list. There are many methods you can do achieve this. In this tutorial, we will not be using the list.reverse() method which is simpler but will be using a simple loop and another method i.e. using the reversed() function to learn more about reverse loops.Hope this helps!

Lets say we have some numbers stored in a list (u can make use of any random numbers, here I have used numbers 0-9 for simplicity) as follows:

number_list= [0,1,2,3,4,5,6,7,8,9]

And now if we need to store & display these numbers in reverse order, we can use the reverse loop as follows:

## Reverse Loops in Python 2.7.x
number_list= [0,1,2,3,4,5,6,7,8,9]       ## Sample list 

print "Original List = ", number_list  ## Displays list

reversed_list=[]        ## Create an empty list named reversed_list

for item in number_list[::-1]:      ## Reverse Loop
    reversed_list.append(item)      ## Add/Append current item to reversed_list

print "Reversed List = ", reversed_list ## Print Reversed List

Output:

Original List =  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Reversed List =  [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Alternative Method  (using reversed function):

Consider the below list:

number_list= [0,1,2,3,4,5,6,7,8,9]

First, we will calculate the size/length of the list, by using the function len() and storing it into a variable size_of_list

size_of_list=len(number_list)

Here, the value of  the size_of_list will be 10.

[NOTE :Here range(10) will be a list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] . And we use reversed(range(10)) function to reverse the values of range list, and then use the for loop to assign the first value of item as 9, second value as 8 and so on. ]

## Reverse Loop in Python 2.7.x using reversed function

number_list= [0,1,2,3,4,5,6,7,8,9]       ## Sample list
print "Original List = ", number_list  ## Displays list

reversed_list=[]            ## Create an empty list named reversed_list
size_of_list=len(number_list) ## Store Size/length of list , (here length is 10)

for item in reversed(range(size_of_list)): ## Reverse loop
    reversed_list.append(number_list[item]) ## Add/Append current item to reversed_list

print "Reversed List = " , reversed_list  ## Print Reversed List

Output:

Orginal List =  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Reversed List =  [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Feel feel to leave a comment if you have any queries or want to reach out to me. You can also Follow/Subscribe to my blog to get future blog posts! Happy Bloggin! 🙂

Regards
ΞXΤЯΞМΞ

This is a simple guide on installing Python 2.7.8 in Windows 8.1 operating system with screenshots.

Requirements:

  1. Windows 8.1 / Windows 8 OS
  2. Python 2.7.8 : Download Link (~15.92 MB)

Step 1: Installation

Download the python setup file mentioned above and run the installer.

 

installer window picture

Click “Next”.

2

Leave it to the defaults and then click “Next“,

installation directory picture

Now in customize screen, you may see a RED X next to “Add python.exe to Path”.

Customization Screen picture

Click on the RED X and then select the first option option “Will be installed on local hard drive”.

custom selection picture

So finally you will have the below screen:

customization final

Then click on “Next“, and follow the on screen instructions:

progress picture

Finally, click on “Finish“.

python installation complete

 

Step 2: Running the Python Interpreter.

Now, to open Python Interpreter in your Windows 8.1 machine, Press Windows key+X (Press Windows key and while pressing CTRL , tap the letter R once) , you will see a context menu (shown below), click on “Command Prompt (Admin)“. (Click Yes if prompted from User Account Control)

cmd run as admin picture

You will now see the windows command prompt window as shown below:

command prompt admin window picture

Now, type python and then “Enter” in your keyboard to start using the DOS interactive python interpreter.

12

Now, you test it by writing a simple print statement, such as:

print “Hi EXTR3ME”

and then hit “Enter“, you will see the output in the next line as shown below:

python dos shell output

You should have by now installed Python 2.7.8 in your Windows 8/8.1 systems and also written a sample program to test it.

Hope this helps. Feel free to leave a comment below or if have any further queries. 

Don’t forget to subscribe to get future updates! 🙂

Regards
ΞXΤЯ3МΞ

  • Creating a .tar archive:

In Linux, we can create an archive file using the tar program and use gzip to compress the archive. This is similar to the WinZip program in Windows where you can compress multiple files or directories into a compressed .zip archive.

For example, first just create a directory called “testdir

# mkdir testdir

Now, change your working directory to testdir and create files “test1.txt”, “test2.txt”, “test3.txt“.

            # cd testdir

            # touch test1.txt

            # touch test2.txt

            # touch test3.txt

Now, create another directory called “testdir2

            # mkdir testdir2

Now, change your working directory to testdir2 and create files “test4.txt”, “test5.txt”, “test6.txt“.

            # cd testdir2

            # touch test4.txt

            # touch test5.txt

            # touch test6.txt

Now, go back your initial directory

            # cd ../..

To see the list of the created directories and files:

            # tree testdir

Now, to create an tar archive using the “c” (create) and “f” (file) arguments with the tar command as follows:

            # tar cf testdir.tar testdir

Now, to seeif the archive was created. You can type the following command:

            # ls -l *.tar

If you want to see if all the files are inside the archive, or if you want to see the contents of the archive, you use the following command:         

            # tar tf testdir.tar

If you want to see the progress in the archiving process, you can add the “v” argument. For example, the command would then would be:

            # tar cvf testdir.tar testdir

You can also make an tar archive in “Interactive Mode” to select which files needed to be added to the archive and which ones you need 2 exclude. This can be done by using the ‘w‘ argument . You can add a file by typing ‘y’ when prompted and ‘n’ for the file you do not need to add to the archive.

For example, if you wanted to exclude files “test2.txt” and “test4.txt from the archive, all you have to do is , use the following command and type ‘n’ when  prompted for “test2.txt” and “test4.txt” and type “y” for the rest of the files.

            # tar cwf testdir.tar testdir        

  • Extracting a .tar archive:

To extract a .tar archive, you can use tar with ‘-x‘ (for extracting) and “-f” and “-v“(to see what is happening or progress of extraction) arguments.

            # tar xvf testdir.tar

To select which files to be extracted you need to use the ‘w’ argument. For example:

            # tar xvwf testdir.tar

Now, if you want to just want to extract a single file from the archive, for example, “testdir/testdir2/test4.txt”, you can use the following command:

            # tar xvf testdir.tar testdir/testdir2/test4.txt

  • Compressing Files using gzip:

We can compress a .tar archive using gzip and the compressed file will be either a .tgz or .tar.gz file.

For example, if you want to compress “testdir.tar” using gzip, you can do it by using the following command:

            # gzip testdir.tar

The resulting compressed file will be “testdir.tar.gz”. So, the compressed file will be the filename with a “.gz” extension by default.

To see the details of the compressed file, you use the following command:

            # gzip -l testdir.tar.gz

To check if the compressed “.tar.gz” file is proper, you can use the following command:

            # gzip -tv testdir.tar.gz

You can also compress the “.tar” archive to a custom extension using the “-S” argument. For example, if you want to compress the arhive “testdir.tar” to “.gzipped”, by using:      

            # gzip -S .gzipped testdir.tar

  • Decompressing using gzip or gunzip:

We can decompress a compressed file using the “gunzip“. The compressed file should have any of these extensions “.gz”, “.z”, “.Z”, “-z” or “-Z” in order to decompress or it will not work.

For example, if you want to decompress the file “testdir.tar.gz

# gunzip testdir.tar.gz

Another way to decompress is by using the gzip program itself by using the “-d” argument. For example:

            # gzip -d testdir.tar.gz

ΞXΤЯ3МΞ

There are many ways in which you can get help with commands. One way of getting help with a command is by using the “man” command which provides the manual page.

For example, if you want to know more about how to use the “cp” command, you can read its manual page by using the following command in the terminal:

# man cp

Another way is to use the “–help” command. This will give you a brief outline of the arguments that can used with the command.

For example, if want to find what all options or parameters can be used along with the command “mv” or remove command, you can use it by typing the following:

# mv –help

 

 ΞXΤЯ3МΞ

These are some of the basic Linux commands which can be used in the terminal . To open the terminal, press ALT+F2 and type gnome-terminal and hit ENTER. This will show you the terminal window where you can type in all your commands.

ls
Shows the list of files in the current directory.

pwd
pwd is used to show which directory you are in at that time

cd
cd directoryname”  will change current working directory to the inputed directory name.For example, if you want to change to directory “abc”, then you type: “cd abc

cd ..
Change the current directory to the previous directory.

cd ~
Go to the current user directory. For example, if your username is “root”, then it will go the user directory of root.

cat filename
This is used to display the contents of a file.
For example, you want to show the contents of a file named hello.txt , then you use the command “cat hello.txt

cal
Prints the calender of the current month

date
This will print today’s date

su
su is used to switch user. You can use it by using the ” su username” .
For example, “su root” will switch current user to root. You will be prompted to enter the password, and after you enter the password you will be switched to user root.

mkdir directoryname
This is used to create a directory . For example : If you want to create a directory named abc, then type “mkdir abc

uname -a
This will print all your system related information like the operating system , kerenel version etc

uname -o
This will print the operating system that is currently in use.

cp
This is used to copy a file to another location. For example you have a file name test1.txt and you want to copy it to /home/documents/ , then you have to type “cp test1.txt /home/documents

cp -R
This is used to copy directories. For example, to copy the folder /home/documents/dir1 to /home/root/ folder,  you use the command “cp -R /home/documents/dir1 /root/documents/

mv
This is used to move a file or folder to another location. For example, if you want to move the folder /home/documents/dir1 to the location /root/, then you use the command “mv /home/documents/dir1 /root/

rm
This command is used to the delete files or directories . For example, to delete the file hello.txt, you use the command “rm hello.txt

vi filename
This is used to create or open  a file in the vi editor. For example, if you want to create a file named “hey.txt” , you use the command “vi hey.txt” . To enter or insert text into the file, press i or INSERT button on your keyboard. After you have entered the text, to save the file and exit , press ESC and type :wq and hit ENTER on your keyboard. This will save your file and exit the editor and will go back to your terminal window.

touch filename
touch is used for creating text files. For example, to create  a text file name hello.txt, you type “touch hello.txt

ΞXΤЯ3МΞ

In the server side, we have to create a socket, Bind the socket to the address and port, and then set it to listening state and waits for the client to connect. When a client requests a connection, the server then accepts the connection.

Make sure you opened up two Python Shells (or Python IDLEs) so that you can run both the client and server.

This is a very basic program that sends a string of data from the server to the client and displays it to the client.

TCP SERVER

# TCP Server Code

host="127.0.0.1"			    # Set the server address to variable host
port=4446 				    # Sets the variable port to 4446
from socket import *	 		    # Imports socket module

s=socket(AF_INET, SOCK_STREAM)

s.bind((host,port))     		    # Binds the socket. Note that the input to
                                            # the bind function is a tuple

s.listen(1) 		        	    # Sets socket to listening state with a  queue
                                            # of 1 connection

print "Listening for connections.. "

q,addr=s.accept()			    # Accepts incoming request from client and returns
                                            # socket and address to variables q and addr

data=raw_input("Enter data to be send:  ")  # Data to be send is stored in variable data from
                                            # user

q.send(data) 		        	    # Sends data to client

s.close()

# End of code

 ___________________________________________________________________________________

TCP Client

In the TCP Client, we need to create the socket first, then connect to the server by using the socketname.connect((ipaddress,port)) . Then you need to receive the data which is send from the server, this is done by using the function socketname.recv(size)

# TCP Client Code

host="127.0.0.1" 			# Set the server address to variable host

port=4446 				# Sets the variable port to 4446

from socket import *			 # Imports socket module

s=socket(AF_INET, SOCK_STREAM)		# Creates a socket

s.connect((host,port))			# Connect to server address

msg=s.recv(1024)			# Receives data upto 1024 bytes and stores in variables msg

print "Message from server : " + msg

s.close()                            # Closes the socket
# End of code

Happy Coding!

CheerS!!

ΞXΤRΞМΞ-X