Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Programming in Python for beginners – part 1

tutorial python2 for beginner

  • Please log in to reply
No replies to this topic

#1 tux

tux

    CC Regular

  • Member
  • PipPipPip
  • 29 posts
  • Programming Language:Java, Python, Visual Basic .NET, Fortran, Bash
  • Learning:C++

Posted 21 August 2012 - 08:27 AM

This tutorial is intended for everyone who wants to learn programming. Before I start with a tutorial I warn you that English is my second language so there will be grammatical errors.

Before we start please make sure you have installed Python version 2.x. Linux users and OS X users have it shipped with operating system. If you are Windows user then go to the following link: http://www.python.or...ython-2.7.3.msi

Here in this tutorial I am not going to explain how to install it. I assume you are able to do it alone. There are two ways of writing python applications: 1. using text editor (Notepad++. Gedit...) and 2. using Integrated Development Environment (IDE). In this tutorial we will use IDE because it is easier to write code (code completion, debugger...). On the market there are few IDEs for Python development. The most known is IDLE but we are not going to use it. The reason we are not going to use it is the lack of quality debugger. As a beginner you will need to learn how to use a debugger.

Preparation for development

The IDE we are going to use is Eclipse. Notice also that Eclipse is used mainly for Java but it is possible to develop applications in other languages like python. To use Eclipse with a Python we need to install “extension” pyDev. If you haven't downloaded Eclipse now it is time to do it. After you have installed Eclipse go to Help → Install new software. Now you should see the following window:

Install.png

Make sure you choose the same options as shown in the previous picture.

After installation is completed go to File > New > PyDev Project. You should see the following window:

project.png

In our example I gave the project name codecall. Please make sure you have chosen option Create 'src' folder. That is folder where all our code will be stored. Click Finish

On the right side you should see the name of our project. Do right click on folder icon and choose New > PyDev Module. Choose any project name. In my case it is Hello World. From the template choose <Empty>. Finally we are ready to start programming.

Printing, printing and printing

Delete all code you see in your editor. The first thing we are going to learn is printing message to the screen. Python provides an easy way to accomplish this. All you need to do is write

print "Hello World"

Now suppose you are writing application which uses non-English alphabet. For example if we try to print Hello world using Arabic characters it should look like this:

print "您好世界"

If you run it you will get an error: SyntaxError: Non-ASCII character '\xe6' in file
By default Python uses ASCII character encoding which means there is no support for languages as Chinese. So, to use non-English characters add the following line to the top of file:
# -*- coding: utf-8 -*-

Now it should work. By default Python uses character encoding called ASCII which doesn't contain languages like Chinese or Arabic. To tell python to use UTF-8 we added a line at the top of file.
Lets imagine next situation. What if you want to write the sentence in quotes? Everything you want to print is surrounded by quotes.

If you try:

print "He said, "Python is awesome!""

You will get an error: SyntaxError: invalid syntax
Python strings can be printed using characters like ' or ". For printing previous sentence we use character ':
print 'He said, "Python is awesome!" '


What if you want to print the message?

"Today's lesson is amazing" he said.
Then you can do it using the following statement:

print '''"Today's lesson is amazing",he said.'''


Another approach is using escape sequence, also known as escape characters. On the link http://www.python.or...l_analysis.html you can see all escape sequences. Better approach to previous sentence would be:
print "\"Today\'s lesson is amazing\", he said"

Comments

Now when you know how to print messages you can also add comments to your code.
Python comments starts with #

Example:

# This is one line comment

Multi-line comments:

''
This is a multiline
comment.
'''

Arithmetic operators

Arithmetic operators in Python are:

+ Addition
- Subtraction
* Multiplication
/ Division
//Floor division
%Modulo
**Power

They can be used for strings, not just for numbers. This is valid in Python:

print 3* "I love Python "

Output: I love Python I love Python I love Python

You can do string concatenation using symbol +

Example:
print '10'+'11'

outputs 10111

If we try the following statement:

print 5+"a"

Python would say: TypeError: unsupported operand type(s) for +: 'int' and 'str'

It means we can't mix strings and numbers.

Statement “5”+”a” is valid in Python.

Variables

Now when we know how to print messages in Python let's look at variables. Variables are used for storing values while application is running. When you close the application all data will be lost. If you want to store data and make it available even after the application is closed then we will use files. We will talk about it later. Imagine variables as a boxes where you store values. Operator = is assignment operator and it is used for storing values in variables.
Lets store our name in a variable and use it in combination with print statement.

name="Tux"
print "My name is" + name

Output:
My name is Tux

We can also use the following statements:

numberSum=1+2
print "Sum is " , numberSum

From the example you can see that I used comma instead plus. It is important to know that + is used only for string concatenation. If you really want to use + in previous example then you must somehow convert numbers to string. The way you can do it is using str(yourNumber) statement. To make it more clear let's look at example:
numberSum=str(1+2)
print "Sum is " + numberSum

Never give variable names like x, y or something else. When the project grows it is easy to get lost in code and you won't be able to figure out for what is variable is used. Variables deserves meaningful names.

Debugging

The most important skill for any future programmer is debugging skill. Now when you know how to use variables you can easily write an application which sums digits in number.
To make it simple we will make application for summing three digits number.
Summing all digits in number 234 should output 9 as a result.
To solve this problem we store number 234 in a variable named number like this:
number=234

If you were careful while reading this tutorial you will know how to solve this problem. Before we continue to write our code take a piece of paper and solve it without using python code. Here is the way I have solved it on a paper using simple math:

Extracting numbers can be solved using operators / and %.
Operator / will give us the first number in the 3 digit number:
234/100=2 (first digit)
Operator % (remainder) will give us the last two numbers.
234%100=34 (remaining digits)
Number 34 has 2 digits, so we will divide it by 10 instead of 100.
34/10=3 (second digit)
34%10=4 (third digit)

Now when we know how to solve it manually without programming it is easy to translate it into Python
number=234
# 234 is stored in variable number. Instead of using 234 we use variable number
firstDigit=number/100
remainingDigits=number%100
# to get second digit we divide remaining digits by 10
secondDigit=remainingDigits/10
thirdDigit=remainingDigits%10
digitsSum=firstDigit+secondDigit+thirdDigit
print "Sum of digits in number " , number , " is ", digitsSum

Let's debug to see how our application works. Breakpoints are used for stopping application at line where you put breakpoint. Putting breakpoint is done by pressing key combinations Ctrl+F10 and choosing Add Breakpoint. Easier way is to do double click at left side of statement. When th breakpoint is set you will see the following picture:

Selection_006.png



Press F11 and run through code using F6. On the right side you can see the values stored in a variable. When variable changes its value it is shown as yellow.


Challenge 1:

Write a program to compute the sum of digits of a given number.

Number is given as:

number="1234"


Challenge 2:

The following program should exchange variable values. Assume that number1=1 and number2=2, then after application execution it should print "Value of number1 is 2 and value of number2 is 1". Edit the following program to print correct values:

number1=1
number2=2
number1=number2
number2=number1

(Try to debug it and see what happens with variable values)

Challenge 3 (hard):
Imagine that your keyboard doesn't have the key * used for multiplication of numbers. Can you multiply numbers 3 and 4 without * ?


NOTE: Attached source code files contains commented lines. To test output of specific command you will need to uncomment it.

Attached Files


  • 2





Also tagged with one or more of these keywords: tutorial, python2, for beginner