the easiest way to learn python - teraexethe easiest way to learn python alvaro j. gene 12 exercise...

27
Author: Alvaro J. Gene Alias: Socket_0x03 Website: www.teraexe.com Email: [email protected] © Copyright 2011. Alvaro J. Gene. All rights reserved The Easiest Way to Learn Python Version 1.0

Upload: others

Post on 03-Oct-2020

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

Author: Alvaro J. Gene

Alias: Socket_0x03

Website: www.teraexe.com

Email: [email protected]

© Copyright 2011. Alvaro J. Gene. All rights reserved

The Easiest Way to Learn Python Version 1.0

Page 2: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

1

Table of Contents

Introduction ........................................................................................................................................................................... 3

Exercise One Show Message .................................................................................................................................................. 4

Exercise Two: Variables .......................................................................................................................................................... 4

Exercise Three: Arithmetic Operators – Addition .................................................................................................................... 5

Exercise Four: Arithmetic Operators – Subtraction ................................................................................................................. 5

Exercise Five: Arithmetic Operators – Multiplication .............................................................................................................. 6

Exercise Six: Arithmetic Operators – Division .......................................................................................................................... 6

Exercise Seven: Arithmetic Operators – Power ....................................................................................................................... 7

Exercise Eight: Arithmetic Operators – Floor Division ............................................................................................................. 7

Exercise Nine: Arithmetic Operators – Modulo ....................................................................................................................... 8

Exercise Ten: Relational Operators – Less Than ...................................................................................................................... 8

Exercise Eleven: Relational Operators – Greater Than ............................................................................................................ 9

Exercise Twelve: Relational Operators – Less Than or Equal to ............................................................................................... 9

Exercise Thirteen: Relational Operators – Greater Than or Equal to ..................................................................................... 10

Exercise Fourteen: Relational Operators – Equal to .............................................................................................................. 10

Exercise Fifteen: Relational Operators – Not Equal to .......................................................................................................... 11

Exercise Sixteen: Raw_input ................................................................................................................................................. 11

Exercise Seventeen: String.................................................................................................................................................... 12

Exercise Eighteen: While Loop .............................................................................................................................................. 12

Page 3: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

2

Exercise Nineteen: If Statement ........................................................................................................................................... 13

Exercise Twenty: The If-else Statement ................................................................................................................................ 13

Exercise Twenty-One: elif Statement .................................................................................................................................... 14

Exercise Twenty-Two: def function ....................................................................................................................................... 14

Exercise Twenty-Three: Read a File....................................................................................................................................... 15

Exercise Twenty-Four: File Readlines .................................................................................................................................... 15

Exercise Twenty-Five: For Loop ............................................................................................................................................ 16

Exercise Twenty-Six: Time Module – Current Time – Part 1 .................................................................................................. 16

Exercise Twenty-Seven: Time Module – Current Time – Part 2 ............................................................................................. 17

Exercise Twenty-Eight: Calendar Module .............................................................................................................................. 17

Exercise Twenty-Nine: Exception Type ................................................................................................................................. 18

Exercise Thirty: Tkinter Message .......................................................................................................................................... 18

Exercise Thirty-One: Sending Message with Tkinter .............................................................................................................. 19

Exercise Thirty-Two: Capturing Clicks in a Window ............................................................................................................... 21

Exercise Thirty-Three: Network Socket ................................................................................................................................. 22

Exercise Thirty-Four: Information from HTTP Server ............................................................................................................ 23

Exercise Thirty-Five: Teraexe Chat (Client and Server with if – else) ...................................................................................... 25

Page 4: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

3

INTRODUCTION

This tutorial has been created to provide information about Python, which is a computer programming

language where you can develop a great variety of applications; for instance, you can use your creativity and

knowledge to create network traffic monitors, password decoders, port scanners, exploits, and much more. Like

others tutorials about information technology that I have been created, this guide includes theory and practice because

one of the best ways to learn about computer programming is through theory and practice. Not only will you find a

great variety of exercises with theory and practice, but also short instructions and concepts that are very effective to

facilitate the comprehension of the lector. One of the examples where I developed short terms is on the first

exercise—Exercise One: Show Message—where you can see some codes and only a few lines to explain each code.

Page 5: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

4

Exercise One: Show Message Theory:

• print: If you want to print a message, you can use this code.

• #: If you want to write something in your source code, you can use those symbols—your program will not

show that message.

Practice:

print "The Easiest Way to Learn Python by Alvaro J. Gene (Socket_0x03)" # This is a comment... Note: For each exercise, you will use the same method to run your applications: First, you have to place the

source codes inside of a text file. As you can see, in this tutorial, the source codes are in blue color. Then, you

have to save those codes with a .py extension; for example, you can save those codes in this way: C:\file.py.

Finally, you have to run your application using an interpreter like Python.

Result:

Exercise Two: Variables Theory:

• letter = number: This is a method to select variables; in addition, you can modify variables using math

symbols, such as plus (+) or minus (-).

Practice:

v = 3 # You can use this method to select a value. Now, v is equal to 3. print "The value of v is:", v v = v + 3 # V plus tree is six. Now, v is equal to 6. print "Now, The value of v is:", v v = 5 # You can use this method to select a new value. Now, v is equal to 5. print "Now, The value of v is:", v print "5 x 5 is:", v*5 # You can use an asterisk to multiply that value by other number. # In this case, the application will print 25. print "The value of v do not change to 25. The value of v is the same:", v # The value of v is the same, which is 5.

Page 6: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

5

Result:

Exercise Three: Arithmetic Operators – Addition Theory:

• The Plus Symbol (+): The plus symbol (+) can be used to add numbers. Practice:

a = 10 b = 13 Teraexe_Add = a + b print Teraexe_Add

Result:

Exercise Four: Arithmetic Operators – Subtraction Theory:

• The Minus Symbol (-): The minus symbol (-) can be used to subtract numbers. Practice:

a = 30 b = 7 Teraexe_Sub = a - b print Teraexe_Sub

Page 7: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

6

Result:

Exercise Five: Arithmetic Operators – Multiplication Theory:

• The Asterisk Symbol (*): The asterisk symbol (*) can be used to multiply numbers. Practice:

a = 3 b = 9 Teraexe_Mult = a * b print Teraexe_Mult

Result:

Exercise Six: Arithmetic Operators – Division Theory:

• The Slash Symbol (/): The slash symbol (/) can be used to divide numbers. Practice:

a = 81 b = 9 Teraexe_Div = a / b print Teraexe_Div

Result:

Page 8: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

7

Exercise Seven: Arithmetic Operators – Power Theory:

• The Double Asterisk (**): The double asterisk can be used to elevate a number to the power of another

number.

Practice:

a = 2 b = 4 Teraexe_Power = 2 ** 4 print Teraexe_Power

Result:

Exercise Eight: Arithmetic Operators – Floor Division Theory:

• The Double Slash (//): The double flash (//) can be used to realize a floor division.

Practice:

a = 9 b = 4.0 Teraexe_FloorDivision = a // b print Teraexe_FloorDivision

Result:

Page 9: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

8

Exercise Nine: Arithmetic Operators – Modulo Theory:

• Modulo (%): A programmer can use a modulo (%) to print a remainder.

Practice:

a = 14 b = 3 Teraexe_Modulo = a % b print Teraexe_Modulo

Result:

Exercise Ten: Relational Operators – Less Than Theory:

• Less Than (<): The less than symbol (<) can be used to determine if a variable is less than other.

Practice:

a = 10 b = 20 Teraexe_LessThan = a < b print Teraexe_LessThan

Result:

Page 10: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

9

Exercise Eleven: Relational Operators – Greater Than Theory:

• Greater Than (>): The greater than symbol (>) can be used to determine if a variable is greater than other.

Practice:

a = 20 b = 10 Teraexe_GreaterThan = a > b print Teraexe_GreaterThan

Result:

Exercise Twelve: Relational Operators – Less Than or Equal to Theory:

• Less Than or Equal to (<=): The less than or equal to symbol (<=) can be used to determine if a variable is

less than or equal to other variable.

Practice:

a = 50 b = 100 c = 100 Teraexe_A = a <= b Teraexe_B = b <= a Teraexe_C = c <= b print Teraexe_A print Teraexe_B print Teraexe_C

Result:

Page 11: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

10

Exercise Thirteen: Relational Operators – Greater Than or Equal to Theory:

• Greater Than or Equal to (>=): The greater than or equal to symbol (>=) can be used to determine if a variable

is greater than or equal to other variable.

Practice:

a = 50 b = 100 c = 100 Teraexe_A = a >= b Teraexe_B = b >= a Teraexe_C = c >= b print Teraexe_A print Teraexe_B print Teraexe_C

Result:

Exercise Fourteen: Relational Operators – Equal to Theory:

• The Double equal symbol (==): The double equal symbol (==) can be used to determine if a variable is equal

to other.

Practice: a = 50 b = 100 c = 100 Teraexe_A = a == b Teraexe_B = b == c print Teraexe_A print Teraexe_B

Page 12: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

11

Result:

Exercise Fifteen: Relational Operators – Not Equal to Theory:

• The Not Equal to symbol (!= or <>): The not equal to symbol (==) can be used to determine if a variable is

not equal to other.

Practice:

a = 50 b = 100 c = 100 Teraexe_A = a != b Teraexe_B = b <> c print Teraexe_A print Teraexe_B

Result:

Exercise Sixteen: Raw_input Theory:

• raw_input: You can use this command to read a line and return its value. Practice:

var = raw_input("Now, you can type something: ") print "You typed: ", var

Result:

Page 13: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

12

Exercise Seventeen: Strings Theory:

• Strings: Python is a computer programming language that an individual can use to manipulate strings; in other

words, a programming language that a person can use to print a string of variables.

Practice:

First_Variable = "One" # The first variable will store a text, which is one Second_Variable = "Two" # The second variable will store a text, which is two Third_Variable = "Three" # The third variable will store a text, which is three print First_Variable, Second_Variable sentence = First_Variable + " " + Second_Variable + " " + Third_Variable # A String print sentence # The application will print "one two tree", which is a string

Result:

Exercise Eighteen: While Loop Theory:

• While Loop: You can use this statement to print a word several times; for that reason, you do not have to

write an instruction ten or twenty times in your source code.

Practice:

teraexe = 10 # You can use this method to define a variable. In this case, Teraexe is equal to 10 while teraexe < 20: # The number 10 will increase to 20. The application will print 11, 12, 13... teraexe = teraexe + 1 print teraexe

Result:

Page 14: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

13

Exercise Nineteen: If Statement Theory:

• If Statement: If something is true, the application will print some instruction. Practice:

Teraexe = 1 # You can use this method to define a variable. Teraexe is equal to 1 if Teraexe == 1: # if "y" is equal to "1" the application will print "Teraexe is equals 1". # if you change "1" for other number, the application will not print "Teraexe is equals 1". print "Teraexe is equal 1"

Result:

Exercise Twenty: The If – else Statement Theory:

• If – else Statement: If something is true, the application will print an instruction. If something is false, the application will print other instruction.

Practice:

Teraexe = 10 # You can use this method to define a variable. Teraexe is equal to 10. if Teraexe < 30: # If "Teraexe" is less than "30", the application will print the next instruction. print "Teraexe is less than 30" else: # If "Teraexe" is more than "30", the application will print the next instruction. print "Teraexe is more than 30"

Result:

Page 15: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

14

Exercise Twenty One: elif Statement Theory:

• Elif statement: When if statement fails to be true, elif statement will do an action. Practice:

Teraexe = 3 # You can use this method to define a variable. Teraexe is equal to 3. if Teraexe > 10: # If "Teraexe" is more than "10", the application will print the next instruction. print "Teraexe is more than 10" elif Teraexe < 5: # If teraexe is less than "5", the application will print the next instruction. print "Teraexe is less than 5" # Note: If teraexe is 6, 7, 8 or 9, the application will not print anything.

Result:

Exercise Twenty Two: def function Theory:

• def function: You can use this function to define something. Practice:

def teraexe(a): return a + a # 5 + 5 print teraexe(5) # the last result will be 10 because 5 + 5 is 10. a = 5

Result:

Page 16: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

15

Exercise Twenty Three: Read a File

Theory:

• f.read: You can use this to read files. • f.open: You can use this to open files. • f.close: You can use this to close files.

Practice:

f = open(r'c:\Teraexe.txt') print f.read() f.close()

Note: Before running your application, you have to create a file—C:\teraexe.txt—and write something in this file. Result:

Exercise Twenty Four: File Readlines Theory:

• for i in range(5): We select the number of lines that we will see… Practice:

f = open(r'C:\teraexe.txt') # This will open a file. In this case, teraexe.txt for i in range(5): # Numbers of lines. Now, it has a range of five lines. print str(i) + ': ' + f.readline(), f.close() # This will close a file. In this case, teraexe.txt

Note: Before running your application, you have to create a file—C:\teraexe.txt—and write those lines in teraexe.txt:

The Easiest Way to Learn Python by Socket_0x03. Exercise 1. The Easiest Way to Learn Python by Socket_0x03. Exercise 2. The Easiest Way to Learn Python by Socket_0x03. Exercise 3. The Easiest Way to Learn Python by Socket_0x03. Exercise 4. The Easiest Way to Learn Python by Socket_0x03. Exercise 5. This line will not be showed...

Result:

Page 17: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

16

Exercise Twenty Five: For Loop Theory:

• For loop: A programmer can use this instruction to print some letters of a word. Practice:

for letter in 'Teraexe': print 'for loop: ', letter

Result:

Exercise Twenty Six: Time Module – Current Time – Part 1 Theory:

• Time Module: A coder can import the time module to work with times; furthermore, a programmer can use

this module to print the current time of his/her computer.

Practice:

import time # This line is to import the time module Teraexe_Time = time.localtime(time.time()) print "Current Time: ", Teraexe_Time # Year - Month - Day - Hour - Minutes - Seconds...

Result:

Page 18: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

17

Exercise Twenty Seven: Time Module – Current Time – Part 2 Theory:

• Time Module: In the next example, I am going to use the time module to print the current time in a different

way than the previous exercise.

Practice:

import time Teraexe_Time = time.asctime( time.localtime(time.time()) ) print "Current Time :", Teraexe_Time

Result:

Exercise Twenty Eight: Calendar Module Theory:

• Calendar Module: A programmer can use the calendar module to print different kinds of calendars.

Practice:

import calendar # This line is to import the calendar module Teraexe_Calendar = calendar.month(2012, 6) print Teraexe_Calendar;

Result:

Page 19: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

18

Exercise Twenty Nine: Exception Type Theory: Exceptions: You can use this command if you do not want to accept some actions. Practice:

try: num = float(raw_input("\nType a number: ")) # If you type a letter, the app will print: you did not typed a number except(ValueError): print "You did not typed a number..."

Result:

Exercise Thirty: Tkinter Message Theory:

• “from Tkinter import *”: You can use this code to import the Tkinter module. Tkinter is the standard Python

interface to the Tk GUI—graphical user interface—toolkit from scriptic; furthermore, you can import this

module typing import Tkinter.

• widget = Label(tkroot, text='Message'): Labels are used to write something that users will see when they run

your application.

• widget.config: You can use this to realize configurations. For example, measurement of your application likes

height or width. In addition, you can use this command to realize others modifications related to colors.

Page 20: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

19

Practice:

from Tkinter import * tkroot = Tk() labelfont = ('courier', 15, 'bold') widget = Label(tkroot, text='The Easiest Way to Learn Python by Socket_0x03') widget.config(bg='blue', font=labelfont) widget.config(height=4, width=50) widget.pack(expand=YES, fill=BOTH) widget.focus() tkroot.title('The Easiest Way to Learn Python by Socket_0x03') tkroot.mainloop()

Result:

Exercise Thirty One: Sending Message with Tkinter Theory:

• root = tk (): After importing Tkinter, you can use root = tk () to start using all those codes that are related to

Tkinter.

• self.button = Button: You can use this code if you want to include different kinds of buttons inside of your

application.

• command=frame.quit: You can use this code if you want to finish an application.

• root.mainloop (): The main loop is also known as the main event loop. You can use this code if you want to

develop an application that is going to use the event loop, so your application will be in that kind of event

until you closes your program.

Page 21: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

20

Practice:

from Tkinter import * # You can use this method to start the Tkinter module class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="Exit", height=2, width=20, command=frame.quit) self.button.pack(side=LEFT) self.Send_Message = Button(frame, text="Send Message", height=2, width=20, command=self.Message_Sent) self.Send_Message.pack(side=LEFT) def Message_Sent(self): print "The message was sent" root = Tk() app = App(root) root.mainloop()

Result:

Page 22: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

21

Exercise Thirty Two: Capturing clicks in a window Theory:

• Events: An event is something that happens with a mouse, a keyboard, or something similar. This is the

syntax of an event: <modifier-type-detail>

• Event Formats:

<Button-1>: If the mouse button is clicked, something will happen. <B1-Motion>: If the mouse button is clicked and moved, something will happen. <Double-Button-1>: If the mouse button is clicked two times, something will happen. <Enter>: If the mouse enters in an application, something will happen. <Leave>: If the mouse leaves an application, something will happen. <Return>: If someone pressed the Enter key, something will happen. <Key>: If someone pressed any key, something will happen.

The Event Objects: You can use this to assign events that will happen in an application.

• Event Attributes:

Widget: You can use this code when you are developing an application where a user has to interact with a graphical user interface. x, y: You can use those characters when you are developing an application that is using the position of your mouse. As you can see, x means the x position of your mouse, and y means the y position of your mouse. x_root, y_root: Those codes are related to the root position of a mouse. char: You can use this code when you want to include a keyboard event that is related to characters, such as a, b, and c. keysym: You can use this code if you want to develop an application that can interpret those kinds of key symbols that a user is using while he/she is using your application. keycode: You can use this code if you want to develop an application that can read some key symbols. width, hight: You can use those codes to specify the size of your application. type: You can use this code to represent those kinds of events related to types; to put it another way, the event type.

Practice:

from Tkinter import * Socket_0x03 = Tk() def teraexe_mouse(event): print "clicked at", event.x, event.y frame = Frame(Socket_0x03, width=333, height=333) frame.bind("<Button-1>", teraexe_mouse) frame.bind("<Enter>", teraexe_mouse) frame.pack() Socket_0x03.mainloop()

Page 23: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

22

Result:

Exercise Thirty Three: Network Socket Theory (Part 1: Concepts):

• IP (Internet Protocol) address: The IP is a group or set of digits that identifies a system inside of a network.

• TCP/IP (Internet Protocol Suite): The TCP/IP is a group or set of protocols that a system can use to

communicate to other systems inside of a network.

• TCP (Transmission Control Protocol): The TCP is one of the Internet Protocol Suite. You can use the TCP

protocol to start or initiate a connection among two different systems.

• UDP (User Datagram Protocol): The UDP is one of the Internet Protocol Suite. This protocol is used by an

internaut to send datagrams to other systems inside of a network without prior communications.

• Datagram: In information technology, datagrams are packet for an unreliable service.

• Server: In computer programming, a server is designed to provide services to clients.

• Client: In computer programming, a client is an application that connects to a server.

Theory (Part 2: Commands):

• socket.AF_INET: This code represents the address and protocol families.

• socket.AF_UNIX: This code represents the address and protocol families.

• socket: If you want to create a socket, you can use this function.

• socket.accept: If you want to accept a connection from a socket, you can use this function.

• socket.connect (address): If you want to connect with a socket, you can use this function.

• socket.send: If you want to send information with sockets, you can use this function.

• socket.recv: If you want to receive a connection from a socket, you can use this function.

Page 24: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

23

Practice:

import socket # You can use this code to import the socket module server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(("", 3333)) # this code will connect on port 3333 server.listen(3) # this code will use only three connections while 1: add, port = server.accept() add.send("The Easiest Way to Learn Python by Socket_0x03") # This code will send data to a client. Note: First, you have to run your application. Second, you have to open your command line: Click on Start,

Run, Type cmd, and click on OK. Then, you have to type telnet 127.0.0.1 3333. Finally, you will see this

message: The Easiest Way to Learn Python by Socket_0x03.

Result:

Exercise Thirty Four: Information from HTTP Server Theory:

• sck . connect((host,port)): This code is used to connect to an specific host and port, which was selected before.

• sck.recv(1024): You can use this code to receive bytes. In the next source code, your application will receive

1024 bytes.

• Print data_buffer: This code will print those bytes—1024 bytes—that where received in a previous line.

Page 25: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

24

Practice:

import socket # You can use this method to import the socket module sck = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host = "www.nic.com" # You can use this method to select a host port = int(80) # You can use this method to select a port. In this case, port 80 sck . connect((host,port)) # You can use this method to realize a connection. data = "GET / HTTP\1.1\r\n\r\n" # sck.send(data) data_buffer = sck.recv(1024) # Number of bytes that your application will receive print data_buffer #to see the data

Result:

Page 26: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

25

Exercise Thirty Five: Teraexe Chat (client and server with if – else) Theory:

• import socket: You can use this method to import the socket module.

• socket.accept: If you want to accept a connection from a socket, you can use this function.

• socket.connect (address): If you want to connect with a socket, you can use this function.

• socket.send: If you want to send information with sockets, you can use this function.

• socket.recv: If you want to receive a connection from a socket, you can use this function.

Practice (Part 1-Creating a Server): import socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("", 3333)) server_socket.listen(5) print "Teraexe Chat is Activated. Waiting for a client." while 1: client_socket, address = server_socket.accept() print "A Client is connected. As you can see, this is his/her IP and Port: ", address while 1: data = raw_input ( "Type 'q' to Close or Send a Message:" ) if (data == 'q'): client_socket.send (data) # data is sended client_socket.close() # close connection break; else: client_socket.send(data) data = client_socket.recv(512) if ( data == 'q'): client_socket.close() break; else: print "A Message is Received:" , data

Page 27: The Easiest Way to Learn Python - TERAEXEThe Easiest Way to Learn Python Alvaro J. Gene 12 Exercise Seventeen: Strings Theory: • Strings: Python is a computer programming language

The Easiest Way to Learn Python Alvaro J. Gene

26

Practice (Part 2 - Creating a Client): import socket client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(("localhost", 3333)) while 1: data = client_socket.recv(512) if ( data == 'q'): client_socket.close() break; else: print "A Message is Received:" , data data = raw_input ( "Type 'q' to Close or Send a Message:" ) if (data <> 'q'): client_socket.send(data) else: client_socket.send(data) client_socket.close() break;

© Copyright 2011. Alvaro J. Gene. All rights reserv ed