Jump to content
Science Forums

Programming for beginners


phillip1882

Recommended Posts

i know there are plenty of these type of tutorials on the net already, but one more won't make the internet explode. *knocks on wood* for this tutorial i'll be using python. if you don't have python, i highly recommend it. you can download it here, Python Programming Language -- Official Website

so, you want to be a programmer, eh? i must warn you, once you start, it can be hard to stop. i've gotten to the point now where i'm programming my own games, which is where the real fun begins, but it's a long journey to get to that point. if that's your goal, you must be prepared for the long haul. rule #1. in order to become a good programmer, you actually have to write programs. so let's take it one step at a time. we'll start with a question. what exactly is a variable? a variable is a spot in memory where data is stored. "thank you einstein, now would you be so kind as to translate that into english?"

i like to think of variables as storage bins. they usually hold a number, but can hold other things, for later use.

let's take a quick example. open up some kind of word processor. i personally recommend jedit, but if you really want to you can use notepad. write the following

x = 5
print x

save it as twolines.py, now to run it. if your using linux, this is fairly simple, just open a terminal, use cd <folder> to go to the correct folder, and type "python twolines.py" (without the quotes). if your using windows this can be harder, visit python.org for tutorials on how to do it in windows.

as you can see you don't get much, just a 5 on the screen. but let's look at what the program is doing. first we are assigning the number 5 to the variable x. then we are calling the print function, and telling it to give us that x value.

okay, so what? well let's make it a bit more complex. try the following

x = 5
y = 7
print x*y
print x+y
print x/y
print x-y

copy this, save it, and try running. as you can see you get the following.

35

12

0 (?)

-2

what's up with that zero? well unfortunately all variables have a specific type. since we assigned 5 to x and 7 to y, both these variables are assigned as integers. this means that they can be any positive or negative value, but not decimal. there are two ways to get the correct result for the third line. one is to assign one of the variables a decimal value such as assigning y 7.0. the other is to use the "float" function. no, not float as in "hey, that sailor is drowning, let's give him a floating device." but float as in floating decimal point, or a decimal point that can shift position.

lets try it.

x = 5
y = 7
print x*y
print x+y
print float(x)/y
print x-y

"okay that's kind of cool, we got the correct decimal value, but i want to be able in input my own x and y values without having to save every time."

ah now your thinking like a programmer. let's take in some user input.

try saving the following

x = int(raw_input("what x value would you like? "))
y= int(raw_input("what y value would you like? "))
print "x*y =", x*y
print "x+y =", x+y
print "x/y =", float(x)/y
print "x-y =", x-y

run, then run again with different inputs, and a third time with other inputs.

congratulations! you're well on your way to becoming a master programmer. that's it for lesson 1. here's a practice problem for you. write a program that switches the x and y value. (hint: use a third variable.)

Link to comment
Share on other sites

in lesson 1 we explored how to print, store, and get data from the user, as well as types. in this lesson we'll explore conditional statements. by the way, were you able to do the practice problem?

it should look something like this

x = int(raw_input("what x value would you like? "))
y =  int(raw_input("what y value would you like? "))
print x,y
temp =x
x = y
y = temp
print x,y

hopefully you were able to figure this out. if not you may need an even simpler guide.

anyway on to conditional statements. a conditional statement is a piece of code that compares variables and executes the block of code beneath it if the result its true.

x = int(raw_input("what x value would you like? "))
y =  int(raw_input("what y value would you like? "))
if x < y:
  print "wow x is", y-x, "whole values away from y."
elif y != 0:
  print "ah man, x is", x/y,"times greater than y."
else:
  print "whoops, y = 0"
print: "it's the end of the world as we know it!"

this is a fairly simple program that takes two values from the user, and compares them. the first if statement asks "is x less than y?" if so it will execute the print "wow... code.

if not it then goes to the elif statement. elif asks "is y anything but 0?" if so it executes the print "ah man... code. then if y is less than x, and y = 0, it prints "whoops... code. finally no matter which condition executes, the last print "it's the end... gets executed.

note the white space. in python, white space is important, it indicates a group of code.

be sure to use the same amount of white space before each line and use the space bar to indent if you want code together. now let's look at the for statement.

y = 0
for x in range(0,10):
  y = y+x
  print "add", x,"to y."
  print  "y =",y

so x will start off at 0, then go to 1, then 2, etc up to 9. for each x value, the code beneath executes. once again note that the code beneath the for loop is indented. let's take the last example the while loop. while loops are useful when your not entirely sure when you want your code to end.

y= 0, x= 0
while x < 10 and y<x:
  y = y+x
  if y>x:
    y = y/x
  x = x+1

well that's basically it for this lesson. here's another practice problem for you. write code that takes in a value, and then approximates the square root of it.

hint: use two variables, a and b, adding a and b and halfing the result. if this number multiplied by itself is greater than the original number, let a equal the half, else let b.

Link to comment
Share on other sites

were you able to get the practice problem? it should look something like this...

x = float(raw_input("what value would you like to square root? "))
a = 0
b = x
temp = x/2
while temp*temp < x-.001 or temp*temp > x+.001:
  print temp
  if temp*temp <x:
     a = temp
     temp = (a +:QuestionM/2
  else:
     b = temp
     temp = (a+:hihi:/2
print temp

 

in lesson 2 we explored conditional statements. in lesson 3 we'll explore functions.

a function is basically a piece of code that you write when you want to reuse it.

for example, i could rewrite the sqrt code above to be...

def sqroot(x):
  a = 0
  b = x
  temp = x/2
  while temp*temp < x-.001 or temp*temp > x+.001:
  etc.

and replace the print x with return x. then if i saved it as mymath.py, i could later access it. for example...

import mymath
n = 10
val = mymath.sqroot(n)

val will now approximately be the square root of 10. this can be quite handy, and you can write functions to do pretty much anything. lets take a recursive example. a recursive function is a function which calls itself, until it reaches a terminating condition.

def fibonacci(a,b,n):
  if n ==0:
     return a
  elif n ==1:
     return b
  else:
     a =a+b
     b = a+b
     n= n-2
     val =fibonacci(a,b,n)
     return val

x = fibonacci(1,1,7)
print x

in case you can't guess, the above code produces a modified fibonacci sequence. in this particular case, you can pick any two start values, and go as high as you like, within reason. let's trace the recursive calls, just so you can see what this code is doing.

first, fib is called with parameters 1,1,and 7.

then a gets the value 1, b also 1, and n gets 7.

so it runs though the two checks for n, find them both false, then sets a to be 1+1 =2, b to be 2+1 = 3, and n to be 5. then it calls fib again with these parameters.

a = 2+3 = 5, b = 5+3 = 8, n = 3.

a = 5 +8 = 13, b = 13 +8 = 21, n = 1.

finally one of the terminating conditions is met. 21 gets returned up the path 3 times before finally becomes val, then val gets returned.

now would be a good time to go over global and local variables i think.

the names are pretty self descriptive, but basically a global variable is known to everything, whereas a local variable in only known to that particular function. lets do a quick example to display the difference.

def increment1():
  global x
  x = x+1
  return x

def increment2(y):
  y = y+1
  return y

x = 5
z = increment1()
print z, x

y = 5
z = increment2(y)
print z, y

at first it may seem like you want global variables all the time, but for recursive functions they can be very hard to deal with. (try declaring a and b global in the fib function and see what you get.) for most purposes you need the local version, but there are cases that crop up when global is needed. well that's it for this lesson.

two homework problems, write a recursive function that does factorials. (x *(x-1) *(x-2) etc down to 1.) found that one too easy? try a recursive function that does all permutations of 1, 2, 3, 4, 5, 6.

Link to comment
Share on other sites

so how was the homework? did you get the permutations one?

if not, don't feel too bad it was fairly tough.

here's the two functions

def factorial(val,n):
  if n ==1:
     return val
  else:
     n = n-1
     val = val*factorial(val-1,n)
     return val

def permute( variation, word, index):
  if len(word) == 0:
     print variation
     return
  if index >= len(word):
     return
  permute(variation,word,index+1)
  permute(variation+word[index],word[:index]+word[index+1:],0)

note that the solution for permutations assume you enter in the digits in the form of a array, which though i haven't gone over yet, will do so now.

an array is a fairly simple thing, its simply a block of data, such as integers.

for example, array= 10*[0] declares an array of 10 integers, starting value of 0. in python, you have a powerful array accessing tool called slicing. for example, array = array[1:4] will give all array elements from 1 to 3. lets take a specific example.

string1 = "this is a long string of many words that does nothing."
string2 = string1[4:10]
print string2
string2 = string1[:20:2]
print string2

it will print " is a " first, then "ti saln ti". (the 2 means to skip every other character.)

though strings can be accessed they are difficult to modify. for example

string1 = "hi"

string1[0] = "b"

would result in an error.

you could however do something like this

string1 ="hi"

string1 = "b" +string[1]

note however that strings are just one possible thing you can do with an array.

for example, say you want a list of all primes up to 100.

using arrays would allow easy access for this.

index = 2
x =2
mark = [1,1] +[0]*98
while x*x<len(mark):
  while index*x <len(mark):
     if mark[index] == 0:
        mark[index*x] =1
     if mark[index] == 1:
        mark[index*x] = 1
        mark[index] = 2
     index = index+1
  x = x+1
  while mark[x] != 0:
     x = x+1
  index = x
for i in range(0,100):
  if mark[i] == 0:
     print i,

the above code may look a little confusing, but basically here's what its doing. first it declares an array of size 100, then it marks all multiples of 2, then all multiples of 3, then 5, then 7. any unmarked numbers are prime. well that's it for this lesson. practice problem for you. write a program that sorts an array of integers.

Link to comment
Share on other sites

the sorting one should be fairly simple, here's one of my personal favorites.


def quicksort(left,right,valarray):
  a= left
  b = right-1
  while a != b:
     if valarray[a] <=valarray[a+1]:
       temp = valarray[a]
       valarray[a] = valarray[a+1]
       valarray[a+1] = temp
       a= a+1
     else:
       temp = valarray[a+1]
       valarray[a+1] =valarray[b]
       valarray[b] = temp
       b = b-1
  print valarray
  if a+1<right-1:
     quicksort(a+1,right,valarray)
  if a > left+1:
     quicksort(left,a,valarray)

this basically takes the first element, places all elements smaller than it on the right, all elements greater than it on the left, and the recursively sorts the left and right

 

well that's basically the guts of programming. there's still a lot to learn of course, such as object oriented programming, but this is beyond the scope of a beginner tutorial. if you would like to hone your skills, the website topcoder.com has hundreds of practice problems ranging from easy to advanced. if you need more help, there's plenty of stuff online for more information.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...