• Sign in to Neowin Faster!

    Create an account on Neowin to contribute and support the site.

Sign in to follow this  

[HOWTO] Program using Python

Recommended Posts

Lechio    15

Lesson #1

Part 1: Say Hello!

Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python's elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

This first tutorial is meant to be an informal introduction to programming with python. It will describe how to make a basic routine from the category of the "Hello World!" program. It is very advisable to first read the python documentation that comes with your python distribution. What will be covered here is nothing but the basics, in an informal way. Other more advanced lessons will be posted afterwards. This tutorial is made using a Linux system, some of the bellow may not apply if you are using Windows, especially the header section. Read your python manual about this part.

OK, let's start. There are two ways of running simple python code like the one that is going to be shown in this tutorial:

- Interactively by opening a console and typing "python" (this will start the python interpreter interactively and "run as you type");

- Creating a python file and running it.

Here we will cover the method of creating a python file, as it is more easy to keep track of the code this way, but please feel free to use any method you wish.

Creating the python file:

  • Create a new empty text file named "hello.py";
  • Open it with an editor of your choice. An editor that supports python syntax highlighting and indentation will be preferred. To program in python my favorite editor is kate, feel free to use your editor of choice;
  • Change the file header to reflect that this is a python program and declare what encoding it will use. Will not go into details explaining this section, the header will be different if for instance you are using Windows to program. Please consult your python manual to find out more about this section.
    Add the following lines to the beginning of your file:
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-


  • The instruction that prints the actual hello to the world. Add the following line to your file:
    print "Hello neowin.net!"


  • That's it! There is not further step, the "Hello World!" program is now complete. Just save the file, open a terminal on the directory where you have your python file and run it by typing on the terminal:
    python hello.py

The entire "Hello World!" program will look something like this (newlines added to make the code more readable):

#!/usr/bin/env python
# -*- coding: utf-8 -*-


print "Hello neowin.net!"

The output of our little program will, of course, be:

Hello neowin.net!

Understanding the code:

In our code we only have one line of instruction. This line does what it says, prints the "Hello neowin.net!" sentence on screen. If you understand C programming, this will be the equivalent of the printf or puts instruction.

print "Hello neowin.net!"

Learning tips:

Don't just copy>paste the code, take time to understand what the code does.

______________________________________________________________________

Part 2: Calculate this.

In this part we will be doing a calculator that given two members and an operation will say the result between those two same members to the user! This is the same as saying we will be doing a program similar to the previous "Hello World!" program, but that instead of just printing some sentence it will be printing the result of a simple arithmetic operation between two integer numbers, in the most lame way possible.

  • Create a new empty text file named "talking_calculator.py";
  • Copy>paste the code bellow.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#	Talking calculator by Lechio
#	This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
#	the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
#	Copyright (C) 2008   Lechio (TM)




#The import statement.
import sys





#Analyze the arguments provided.
try:
	#First argument provided. At the same time we check if this is argument is of int type.
	member1 = int( sys.argv[1] )

	#Second argument provided, the operation type.
	operation = str( sys.argv[2] )

	#Third argument provided. At the same time we check if this is argument is of int type.
	member2 = int	( sys.argv[3] )


except:
	#Print an error if the arguments are invalid.
	print "Invalid data provided.","Correct usage:"
	print "member1 operation member2"

	sys.exit(1)




#Our operation types:

if sys.argv[2]=="+" or sys.argv[2]=="plus" or sys.argv[2]=="sum":#Sum
	result = member1 + member2#calculate
	pretty_operation_name = "sum"

elif sys.argv[2]=="-" or sys.argv[2]=="minus" or sys.argv[2]=="subtract":#Subtraction
	result = member1 - member2#calculate
	pretty_operation_name = "subtraction"

elif sys.argv[2]=="*" or sys.argv[2]=="X" or sys.argv[2]=="x" or sys.argv[2]=="times" or sys.argv[2]=="multiply":#Multiplication
	result = member1 * member2#calculate
	pretty_operation_name = "multiplication"

elif sys.argv[2]=="/" or sys.argv[2]=="by" or sys.argv[2]=="divide":#Division
	result = member1 / member2#calculate
	pretty_operation_name = "division"

else:#Invalid operation type.
	print "Operation failed! Invalid operation type."
	sys.exit(1)






#Printing the result:
try:
	#Check if the result obtained is of type int.
	result = int(result)



	#Print the result in a pretty form.
	print "\n\n\n"#print a few empty lines.
	print "\t\t\tThe" , pretty_operation_name , 'of' , member1 , "and", sys.argv[3] , "is:", result
	print "\n\n\n"#print a few empty lines.


except:
	#Print an error if the result isn't of type int.
	print "Operation failed! Invalid data obtained, the result is not of type int."



#Talking calculator ends here

Do not be overwhelmed by all of these new things in the code, these will now be explained step by step.

The header.

We've already covered this part in our previous "Hello World!" program. Only a new thing was added, the comments. One line comments in python can be done by putting a '#' in the part of the code where we want to make the comment, all that is to the right of the '#' char will be ignored by the python interpreter and seen as comment. Comments are important if you want to keep your code readable to others (and even to you). A good practice is to always make a comment on an important part of the code, explaining what it does for instance.

Here we've just included simple comments that contain the name of the program, author, license type and copyright notice.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#	Talking calculator by Lechio
#	This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
#	the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
#	Copyright (C) 2008   Lechio (TM)

The import statment.

Python is a modular language. This means we can import anything we want from the modules that come with a python distribution or import our own modules (we will get to that later), and use those to extend the capabilities of our program.

In this example we've imported the "sys" module. This is one of the most important modules (if we can attribute that role to any) from python:

"This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available".

#The import statment.
import sys

Analyze the arguments provided.

This part of the code analyses the arguments provided by the user and checks if those are valid.

The "try - except" is used here to validate the arguments. This statement analyses the conditions right after the "try:" part, if these conditions aren't valid for some reason, the code after the "except:" part will be executed.

In this example we check if the first and third argument ( sys.argv[1] and sys.argv[3] ) provided by the user are (or can be converted to) "int" type. If that is possible we attribute those values to two variables (member1 and member2) for later use and attribute the second argument provided by the user to another variable (operation). If that is not possible then the part after the "except:" will be executed to print an error message and to terminate the program here ("sys.exit(1)").

#Analyze the arguments provided.
try:
	#First argument provided. At the same time we check if this is argument is of int type.
	member1 = int( sys.argv[1] )

	#Second argument provided, the operation type.
	operation = str( sys.argv[2] )

	#Third argument provided. At the same time we check if this is argument is of int type.
	member2 = int	( sys.argv[3] )


except:
	#Print an error if the arguments are invalid.
	print "Invalid data provided.","Correct usage:"
	print "member1 operation member2"

	sys.exit(1)

Operation type and calculations.

This part of the code will make the calculations. The "if (...) elif (...) else" condition is used to check what type of operation should be performed. The second argument provided by the user ( sys.argv[2] ) is analyzed, the correspondent operation will be made and the resulting value of that operation will attributed to a variable (result). At the same time we attribute a value to another variable for later printing (pretty_operation_name). If the operation type is not of a valid type (valid for us) the else part will be used to print an error message and terminate the program.

#Our operation types:

if sys.argv[2]=="+" or sys.argv[2]=="plus" or sys.argv[2]=="sum":#Sum
	result = member1 + member2#calculate
	pretty_operation_name = "sum"

elif sys.argv[2]=="-" or sys.argv[2]=="minus" or sys.argv[2]=="subtract":#Subtraction
	result = member1 - member2#calculate
	pretty_operation_name = "subtraction"

elif sys.argv[2]=="*" or sys.argv[2]=="X" or sys.argv[2]=="x" or sys.argv[2]=="times" or sys.argv[2]=="multiply":#Multiplication
	result = member1 * member2#calculate
	pretty_operation_name = "multiplication"

elif sys.argv[2]=="/" or sys.argv[2]=="by" or sys.argv[2]=="divide":#Division
	result = member1 / member2#calculate
	pretty_operation_name = "division"

else:#Invalid operation type.
	print "Operation failed! Invalid operation type."
	sys.exit(1)

Printing the result.

This final part of the code will print the result.

It checks if the result is of type "int" and prints it on screen in form of a sentence.

#Printing the result:
try:
	#Check if the result obtained is of type int.
	result = int(result)



	#Print the result in a pretty form.
	print "\n\n\n"#print a few empty lines.
	print "\t\t\tThe" , pretty_operation_name , 'of' , member1 , "and", sys.argv[3] , "is:", result
	print "\n\n\n"#print a few empty lines.


except:
	#Print an error if the result isn't of type int.
	print "Operation failed! Invalid data obtained, the result is not of type int."

To run this program just save the file, open a terminal on the directory where you have your python file and run it by typing on the terminal:

python talking_calculator.py 1337 plus 1337

Change the numbers and the operation type.

Learning tips:

Try to find a way to do a more advanced calculator, by making it able to perform more complex calculations.

This completes this part of lesson #1.

______________________________________________________________________

Part 3: Get in func.

What we've manged to achieve so far is nothing but a big pile of instructions that get executed one after the other. What if we could organize this a bit more? And at the same time optimize our code for execution?

In comes the functions.

Again, this is yeat another "Hello World!" type program. Nothing too advanced will be done here.

  • Create a new empty text file named "get_in_func.py";
  • Copy>paste the code bellow.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#	Get in func by Lechio
#	This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
#	the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
#	Copyright (C) 2008   Lechio (TM)



#The import statement.
import sys



#Who to salute.
try:who=sys.argv[1]
except:who="Mr. Bill"

#Way to salute.
try:way=sys.argv[2]
except:way="shacking hands with you"

#How to salute.
try:how=sys.argv[3]
except:how="cordial"




def salute( who_to_salute , way_to_salute , how_to_salute ):
	"""Salute the individual"""

	print "\n\n\n"#print a few empty lines.
	print "I slatute you" , who_to_salute , "by" , way_to_salute , "in the most" , how_to_salute , "way."
	print "\n\n\n"#print a few empty lines.



#Run the salutation function
salute( who , way , how )



#Get in func ends here.

Getting the arguments.

Get the arguments provided by the user and store them in a variable. Default those when not found.

#Who to salute.
try:who=sys.argv[1]
except:who="Mr. Bill"

#Way to salute.
try:way=sys.argv[2]
except:way="shacking hands with you"

#How to salute.
try:how=sys.argv[3]
except:how="cordial"

The function.

In this part of the code we declare and write our function. This function takes 3 parameters: "who_to_salute" , "way_to_salute" , "how_to_salute". We will need to provide those arguments when calling it later.

def salute( who_to_salute , way_to_salute , how_to_salute ):
	"""Salute the individual"""

	print "\n\n\n"#print a few empty lines.
	print "I slatute you" , who_to_salute , "by" , way_to_salute , "in the most" , how_to_salute , "way."
	print "\n\n\n"#print a few empty lines.

Call the function.

Here we call the function with our 3 arguments.

#Run the salutation function
salute( who , way , how )

To run this program just save the file, open a terminal on the directory where you have your python file and run it by typing on the terminal:

python get_in_func.py "Mr.John" "shacking hands with you" "cordial"

Change the arguments.

Learning tips:

Make another more complex function, with a few more arguments.

This completes this part of lesson #1.

______________________________________________________________________

Part 4: Classified.

We've already seen how useful functions can be to help keep our code optimized and organized too. But what if we could go one step further and get our code even more optimized and organized, Classifying it into sections where we could write our code inside functions and keep it really organized?

In comes the Classes.

If you program in C++ you will recognize these. For this example (for a change) we are going to make something really "useful", a program that checks a Gmail inbox and tells the mail count! Pretty lame thing to be doing, with so many mail applications that can do this task, oh well... A Gmail checker in under 50 lines of code:

  • Create a new empty text file named "get_my_gmail.py";
  • Copy>paste the code bellow.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#	Script from Adrien Vermeulen made for Aero-AIO superkaramba theme
#	Small modifications by Lechio
#	This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
#	the Free Software Foundation; either version 3 of the License, or (at your option) any later version.


import os,re,sys



#This outputs the number of messages of mailbox. Usage: get_my_gmail.py [LOGIN] [PASSWORD]
class GetGmail:
	def __init__ (self, login, password ):
		self.getGMailNum(login, password)


	def getGMailNum(self, login, password):
		password = password.replace("@","%40")

		#Get mail count (requires wget)
		f=os.popen("wget  -qO - --timeout=10 --no-check-certificate https://" + str(login) + ":" + str(password) + "@mail.google.com/mail/feed/atom")
		a=f.read()
		f.close()

		match=re.search("<fullcount>([0-9]+)</fullcount>",a)

		print "\n\n\n"#print a few empty lines.
		if (match != None):#Print the mail count
			print "\t\t\tYou have ", str(match.group(1)), " message(s)."
		else:
			print "\t\t\tCould not check Gmail"

		print "\n\n\n"#print a few empty lines.


#Call the GetGmail class with the arguments provided by the user, print an error if it fails.
try:
	login=str(sys.argv[1])
	passwd=str(sys.argv[2])
except:
	print "\t\t\tCould not check Gmail. Usage"
	print "\t\t\tpython get_my_gmail.py LOGIN PASSWORD"
else:
	GetGmail(login,passwd)

The Class.

Notice how we declare our class with no arguments. Arguments are then provided to the "__init__" function. This function is always present in a class and runs (initializes) with the arguments provided to call this class. After the "__init__" function we then can declare other functions, these functions can use global variables or private variables that belong only to this class. Prefixing the term "self" will indicate that a member belongs to this class, may it be a variable or a function.

In our code we have the "__init__" function initializing with two arguments (login and password), it then calls the "getGMailNum" function with these two same arguments. We can initialize our class with any function or code we want. We can also call/use a member from this class from outside the class, by prefixing the name of this class to the member we will be using. Code gets contained.

#This outputs the number of messages of mailbox. Usage: get_my_gmail.py [LOGIN] [PASSWORD]
class GetGmail:
	def __init__ (self, login, password ):
		self.getGMailNum(login, password)


	def getGMailNum(self, login, password):
		password = password.replace("@","%40")

		#Get mail count (requires wget)
		f=os.popen("wget  -qO - --timeout=10 --no-check-certificate https://" + str(login) + ":" + str(password) + "@mail.google.com/mail/feed/atom")
		a=f.read()
		f.close()

		match=re.search("<fullcount>([0-9]+)</fullcount>",a)

		print "\n\n\n"#print a few empty lines.
		if (match != None):#Print the mail count
			print "\t\t\tYou have ", str(match.group(1)), " message(s)."
		else:
			print "\t\t\tCould not check Gmail"

		print "\n\n\n"#print a few empty lines.

To run this program just save the file, open a terminal on the directory where you have your python file and run it by typing on the terminal:

python get_my_gmail.py GMAIL_LOGIN GMAIL_PASSWORD

Change the arguments.

Learning tips:

Make other classes and try to use members from outside those classes.

This completes this part of lesson #1.

______________________________________________________________________

Part 5: Hello tool.

Till now we've only made CLI type of programs. Those would print some useless text in our console and quit. What if we could do those in a graphical way and have that same useless text printed using a nice graphical window?

In comes the graphical toolkits.

Python with his modular feature has the possibility of using a lot of graphical interfaces. GTK, QT, Tcl/Tk are some of the most commonly used but there are many, many more. It's a matter of choice.

In this example we will be using Tcl/Tk. This toolkit is one of the more easy and basic ones, a good way to start making graphical interfaces. To use this toolkit, it must (of course) be installed in the system, install the "python-tk" package first if it isn't yet installed.

A graphical "Hello World!" type program in 35 lines of code:

  • Create a new empty text file named "hello_tool.py";
  • Copy>paste the code bellow.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#	This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
#	the Free Software Foundation; either version 3 of the License, or (at your option) any later version.


import sys

#Import all the components from the Tkinter module. Close everything if the module is not available.
try:from Tkinter import *
except:sys.exit(1)


class Window(Frame):
	def __init__(self, parent=None):
		Frame.__init__(self, parent)
		self.pack()
		self.helloNeowin()


	def helloNeowin(self):
		self.helloButt = Button(self)
		self.helloButt["fg"] = "blue"
		self.helloButt["text"] = "Hello neowin.net!"
		self.helloButt["command"] = self.quit
		self.helloButt.pack()
		self.lift()



if __name__ == "__main__":
	mainWin = Tk()
	app = Window(parent=mainWin)
	app.mainloop()

The imports.

To use the Tk libs we will, of course, need to import them. Here we are using "from Tkinter import *" as it is a more convenient way for us to import all the Tkinter components. We could instead use "import Tkinter", but that would require us to append the name "Tkinter" to every Tkinter component used implying more typing for us, we don't need that...

import sys

#Import all the components from the Tkinter module. Close everything if the module is not available.
try:from Tkinter import *
except:sys.exit(1)

Building the widgets.

We've already seen how classes work. This is the class where we build our widgets. The main window is a simple frame available from our Tkinter module. To find out more about this module it would be a good idea to do a reading on the modules documentation. Using the command "pydoc -w Tkinter" will generate the documentation for this module in form of an HTML file.

class Window(Frame):
	def __init__(self, parent=None):
		Frame.__init__(self, parent)
		self.pack()
		self.helloNeowin()


	def helloNeowin(self):
		self.helloButt = Button(self)
		self.helloButt["fg"] = "blue"
		self.helloButt["text"] = "Hello neowin.net!"
		self.helloButt["command"] = self.quit
		self.helloButt.pack()
		self.lift()

Calling the widget builder and looping the window.

This get2 executed when the application is invoked. It's used to call our class above so the widget can be created. It also creates a loop so the window executes until it quits.

if __name__ == "__main__":
	mainWin = Tk()
	app = Window(parent=mainWin)
	app.mainloop()

To run this program just save the file, open a terminal on the directory where you have your python file and run it by typing on the terminal:

python hello_tool.py

post-52106-1228751780.jpg

Learning tips:

Make it use other widgets from the Tkinter module.

This completes this part of lesson #1.

This concludes lesson #1.

Proceed to Lesson #2

Edited by Lechio

Share this post


Link to post
Share on other sites
Farstrider    298

Cool stuff! Now all you need to do is keep this going! I will definitely keep this bookmarked! Thanks!

Share this post


Link to post
Share on other sites
Lechio    15

Thank you. :)

This one is more of an introduction than anything else. Hope to be able to provide some more lessons. With the help and input of everyone who wants to help out in making this a complete, yet readable tutorial on how to make simple scripts and even more advanced programs using the python language.

Share this post


Link to post
Share on other sites
Farstrider    298

I have just installed Kate, it is on the context menu but does not seem to open! Giving the PC a restart and then will have a look!

Share this post


Link to post
Share on other sites
Lex224    0

These lessons are awesome. Kusods to you my amigo and many thanks for making and sharing it!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.