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 2

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 22 August 2012 - 09:26 AM

Previous tutorial is available here: http://forum.codecal...nners-–-part-1/

Previous tutorial used only print statements. This tutorial will show you how to take input from user and techniques for repeating a code.

Taking input from user is simple:

raw_input(“Enter your name”)

Input taken from user must be stored in a variable so we can use it later in a code.

userInput=raw_input(“Enter your name:”)
print “You entered:”+userInput

At the bottom of Eclipse IDE Python is waiting for input as shown on the following picture:

userInput.png

To make application more readable it is better to take input from user on a new line like on the following picture:

userInputNewLine.png

print “Enter your name:”
userInput=raw_input()

It is time for an example. This time we are going to write an application which takes input from user and sums numbers up to the number user gave us. To do that we must learn how to repeat a block of statements. There are several ways to do this. We will use while statement. This statement has the following form:

while yourCondition:
block of statements

Blocks of statements are executed until yourCondition becomes false. Conditions are constructed using comparison operators and/or logical operators.

Full list of Python operators is available here:
http://docs.python.o...y/stdtypes.html

Python comparison operators:

==
Checks if the value of two operands are equal or not, if yes then condition becomes true.

!=
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.

<>
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.

>
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

<
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

<=
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.


Logical operators

There are three types of logical operators: and, or and not. I will explain them later.

While statement

Let's go back to while statement. If you want to print numbers from 1 to 10 then you can write 10 statements:

print 1
print 2
print 3

It is a boring task. Better solution is to use while statement. Since we want to print numbers from 1 then it is a good idea to store it in a variable. Inside while loop we will print current value of number and then increase that number by 1. It look like this:

number=1
while number<=10:
print number
number=number+1

Make sure you type code with all spaces. It is recommended to use 4 space-bars instead of a tab. If you forget to initialize (give a value) variable number outside while you will get an error because there is no way for Python to figure out is a condition met. Instead of writing number=number+1 there is a shortcut to do that:

number+=1

Statement is translated into number=number+1. There are also other shortcuts as +=. -=. *=, /=, %=, **=, //= Try all combinations in a Eclipse. When you are making condition make sure to put == instead of =. Like I said in previous tutorial = is used to assign a value to a variable. Whenever you are writing a while loop make sure you initialize variable OUTSIDE loop and then change its value INSIDE loop. If you don't do that then your code will run forever.

Finally, we have enough knowledge to finish program from the beginning. When we receive input from user using statement raw_input we must convert it to the number. It is done using command int(). As a programmer in your future programs you will need to convert number to string. You do it by using str() statement.

userInput=int(raw_input("Enter number:")
numberSum=0
number=1
while number<=userInput:
numberSum=numberSum+number
number=number+1
print "Sum of numbers form 1 to",userInput,"is",numberSum


Variable numberSum must have value before application enters while loop. If it doesn't have value then Python interpreter will not be able to evaluate

numberSum=numberSum+number

because on the right side the value of numberSum is not known. Same applies to a variable number.
Also notice that while finishes using : and the body of statements is called block. Block must be indented 4 spaces.

Now when we know how to use while let's learn how to use if statement. If statement has the form:

if condition:
statements
else:
statements

Condition must be true to execute statements. If the condition is false then statements located below else will be executed. There is also if with elif statements which is used for checking multiple values of a variable.

To demonstrate usage of if statement we will write an application which takes input from user as a number and prints if the number is even or odd. Number is even if it is divisible by 2 and odd if not. To check that we will use % operator. % is called remainder operator.
Mathematical way of calculating remainder:
5%3 = 5 / 3 = 1 1*3=3 5-3=2
Remainder is 2. Conclusion: if number doesn't have remainder then it is even else it is odd.

Code for checking is number even or odd is following:
userInput=int(raw_input(“Enter number:”))
if userInput % 2 == 0:
print “Number is even”
else:
print “Number is odd”
Now lets write application which takes day from user as number and prints it as string. For example, if user types 2 the application outputs Tuesday.

After analyzing problem you see we must check for few values of a variable. We will use if and elif combination:

if userInput==1:
print “Monday”
elif userInput==2:
print “Tuesday”
elif userInput==3:
print “Wednesday”
elif userInput==4:
print “Thursday”
elif userInput==5:
print “Friday”
elif userInput==6:
print “Saturday”
elif userInput==7:
print “Sunday”
else:
print “Number must be between 1 and 7”

Continue and break

While loop and for loop (we will learn this later) have statements continue and break. Break immediately leaves loop and executes command after loop. Continue starts executing code from the beginnig of the loop.

Example:

number=0
while number<10:
number=number+1
if number==5:
	 continue
print number

Previous code would print numbers from 1 to 10 without number 5. When number gets value 5 the loop starts from the beginning and it wouldn't be printed. Notice that number=number+1 is at the top of while loop. If it is at the end of while loop then the loop will never finish. It will come to if statement execute continue and then come again at if statement. Use debugger to make it more clear.
Now let's consider example of using logical operators and, or and not.
Suppose you want to take number from user and print if the number is in interval from 10 to 50.

userInput=int(raw_input(“Enter number”))
if userInput>=10 and userInput<=50:
print “Number is in interval from 10 to 50!”
else:
print “Number is not in interval from 10 to 50!”


And is used to check if both conditions are satisfied.
Or is used to check if only one condition is satisfied.
If a condition is true then logical NOT operator will make false.

For statement

For statement has more than one form. For now you will learn only one. Later I will show you other forms.
Form of for loop:

for variable in range(start,end,stepsize):

While is often used when we don't know how many times the code will be repeated. For is used when we know exactly how many times it will be repeated. You can use which you like.
Lets rewrite previous application which printed numbers from 1 to 10 using for:

for number in range(1,11):
print number


You can see it doesn't take 11 and print it. Be careful when using for loop. Just like while loop for also have break and continue statement.
Another form is using stepsize. Stepsize tells how much the variable will be increased.
Example: Printing odd numbers from 1 to 10:

for number in range(1,11,2):
print number



As you can see you don't need to initialize variable like you did in for loop.


Challenge 1:

Write an application which takes numbers from user until he presses 0. When he press 0 application prints the sum of previous numbers.



Challenge 2 (Hard):

In this tutorial I showed you how to sum numbers from 1 to number entered by user using while loop. Your task is to write application which sums numbers from 1 to the number user enters without using any loops. (Mathematics can help you)

Challenge 3:

Write an application which prints number of days in a month. User enters August and application outputs number 31.

Attached Files


  • 0