Posts Tagged ‘source code’

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ΤЯΞМΞ

Advertisements

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ΤЯΞМΞ

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