1 / 35

Introduction to Programming

Introduction to Programming. A program is a sequence of precise instructions Common programming languages: Python, Perl, Java, C++ Elements of a programming language: keywords – words that have special meaning (the vocabulary)

creola
Download Presentation

Introduction to Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Programming • A program is a sequence of precise instructions • Common programming languages: Python, Perl, Java, C++ • Elements of a programming language: • keywords – words that have special meaning (the vocabulary) • syntax – rules that describe the valid constructs (the grammar) • Some of the keywords in Python if else def elif for return in

  2. Python Environment • Python Shell: for executing and testing the programs • Python Editor: for typing/creating the programs

  3. Introduction to Python • Using Python as a fancy calculator >>> 2 + 3 5 >>> 2 + 3 * 4 14 >>> (2 + 3) * 4 20 >>> exams = 100 >>> labs = 70 >>> total = exams + labs >>> print total 170

  4. Functions • Adding your own constructs • describe how to convert from Fahrenheit to Celsius To CONVERT to Celsius a given temperature: 1. subtract 32.0 from the given temperature 2. multiply the value from step 1 by 5.0 3. divide the value from step 2 by 9.0 4. report the value from step 3 defconvert(degrees): value1 = degrees - 32.0 value2 = value1 * 5.0 result = value2 / 9.0 return result

  5. Functions • Adding your own constructs • describe how to convert from Fahrenheit to Celsius defconvert(degrees): value1 = degrees - 32.0 value2 = value1 * 5.0 result = value2 / 9.0 return result • Testing the new construct (in the Python Shell): >>> convert(32) 0 >>> convert(-40) 170

  6. Functions • Adding your own constructs • describe how to convert from Fahrenheit to Celsius defconvert(degrees): value1 = degrees - 32.0 value2 = value1 * 5.0 result = value2 / 9.0 return result • The first two keywords – def and return: • def– define a new construct • return–computation is done, send the "result" back

  7. Variables • Adding your own constructs • describe how to convert from Fahrenheit to Celsius defconvert(degrees): value1 = degrees - 32.0 value2 = value1 * 5.0 result = value2 / 9.0 return result • A new concept – variables: • places to store values • keep track of intermediate quantities • Variable names can be anything (other than keywords) but: • must contain only letters, digits, and _ symbol • cannot start with a digit

  8. Functions • Adding another construct • describe how to compute the average of two numbers To compute the AVERAGE of two numbers x and y: 1. Add the numbers x and y 2. Divide the value from step 1 by 2.0 3. report the value from step 2 defaverage(x, y): total = x + y result = total / 2.0 return result >>> average(20, 70) 45 >>> exams = 90 >>> labs = 80 >>> average(exams, labs) 85

  9. Functions • Multiple steps can be carried out at once defaverage(x, y): total = x + y result = total / 2.0 return result defaverage(x, y): result = (x + y) / 2.0 return result defconvert(degrees): result = (degrees - 32.0) * 5.0 / 9.0 return result defconvert(degrees): value1 = degrees - 32.0 value2 = value1 * 5.0 result = value2 / 9.0 return result

  10. Functions Summary • Functions describe useful computations • Functions take input, process the input, and return a result convert average

  11. Functions Summary • Choose good names for the function, inputs, and variables defaverage(x, y): result = (x + y) / 2.0 return result defcompute(tic, tac): toe = (tic + tac) / 2.0 return toe

  12. Expressing Decisions • Write a function that computes absolute value of a number To compute the Absolute Value of a given number x: 1. if x is greater than 0: the result is x itself otherwise: the result is negative x 2. report the result defabsValue(x): if x > 0: result = x else: result = -x return result >>> absValue(5) 5 >>> absValue(-3) 3

  13. Chaining Decisions • Write a function that converts a student’s exam score to a grade in the range [0 .. 4] To convert a given exam score to [0..4]: 1. if the score is at least 90: the result is 4.0 otherwise if the score is at least 80: the result is 3.0 otherwise if the score is at least 70: the result is 2.0 otherwise if the score is at least 60: the result is 1.0 otherwise: the result is 0.0 2. report the result defcomputeGrade(score): if score >= 90: grade = 4.0 elif score >= 80: grade = 3.0 elif score >= 70: grade = 2.0 elif score >= 60: grade = 1.0 else: grade = 0.0 return grade defcomputeGrade(score): if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F" return grade >>> computeGrade(93) 4.0 >>> computeGrade(68) 1.0

  14. Decisions Summary • The new keywords:if, elif, else • Expressing comparisons if value1 == value2: if value1 <> value2: ... do something ... ... do something ... if value1 < value2: if value1 > value2: ... do something ... ... do something ... if value1 <= value2: if value1 >= value2: ... do something ... ... do something ...

  15. Strings • Variables can contain strings (sequence of characters) course = "Bioinformatics" fragment = "GATTACA" • Representation course ---> • Accessing individual elements print course[0] displays B print course[1] displays i printcourse[13] displays s • Finding the length of a string len(course)

  16. 5 (stop value) is not included Expressing Repetition • General form for variable inrange(start, stop): ... DO SOMETHING ... • Example >>> for iinrange(1, 5): print i 1 2 3 4 >>>

  17. Expressing Repetition • Write a function that takes two inputs (low, high) representing Fahrenheit temperatures and displays the Celsius equivalents of all temperatures in between To print all Celsius temps. between the values low, high: 1. for each temperature in the range (low, high): 1.1. compute Celsius for current temperature 1.2. print the value from step 1.1. defprintCelsius(low, high): for f inrange(low, high): c = convert(f) print c >>> printCelsius(32, 40) 0.0 0.555 1.111 1.666 2.222 2.777 3.333 3.888 4.444

  18. Repetition and Strings • Write a function that takes one input (a DNA sequence) and displays each individual character from the sequence To print the individual characters in a given DNA string: 1. for each indexin the range of valid DNA indices: 1.2 print the DNA character at the current index defprintBases(sequence): for index inrange(0, len(sequence)): print sequence[index] >>> printBases("GATTACA") G A T T A C A

  19. Repetition and Accumulation • Write a function that takes one integer, n, as input and returns the sum of all integers from 1 to n. To add the integers from 1 to the given number n: 1. for each number in the range from 1 to n: update the total sum byadding the current number 2. report the total sum To add the integers from 1 to the given number n: 1. set up a blank variable for the total sum 2. for each number in the range from 1 to n: update the total sum byadding the current number 3. report the total sum >>> addIntegers(5) 15 >>> addIntegers(6) 21

  20. Repetition and Accumulation • Write a function that takes one integer, n, as input and returns the sum of all integers from 1 to n. To add the integers from 1 to the given number n: 1. set up a blank variable for the total sum 2. for each number in the range from 1 to n: update the total sum byadding the current number 3. report the total sum defaddIntegers(n): total = 0 for numberinrange(1, n): total = total + number return total

  21. Executing a Program Line by Line

  22. Computing GC Content • Version I with two counters – one for G’s and one for C’s defcomputeGCcontent(strand): countC = 0 countG = 0 for index inrange(0, len(strand)): if strand[index] == "G": countG = countG + 1 elifstrand[index] == "C": countC = countC + 1 content = 100.0 * (countG + countC) / len(strand) return content

  23. Computing GC Content • Version II with one counter for the total of G’s and C’s defcomputeGCcontent(strand): countGC = 0 for index inrange(0, len(strand)): if strand[index] == "G": countGC = countGC + 1 elifstrand[index] == "C": countGC = countGC + 1 content = 100.0 * countGC / len(strand) return content

  24. Computing GC Content • Version III with one counter using the or keyword defcomputeGCcontent(strand): countGC = 0 for index inrange(0, len(strand)): if strand[index] == "G" or strand[index] == "C": countGC = countGC + 1 content = 100.0 * countGC / len(strand) return content

  25. returnvsprint • return sends a value back that can be stored and used • print only displays a value on the screen defaverage(x, y): result = (x + y) / 2.0 return result >>> labs = average(2.0, 4.0) OK >>> grade = labs + average(3.3, 3.6) OK defaverage(x, y): result = (x + y) / 2.0 print result >>> labs = average(2.0, 4.0) Nothing to store!! >>> grade = labs + average(3.3, 3.6) Nothing to add!!

  26. returnvsprint • return sends a value back that can be stored and used • print only displays a value on the screen • In functions typically should usereturn • Remember that returnterminates the function immediately; put return at the point where the result is ready to report

  27. Decisions Revisited • The else portion is not mandatory: if base == "A": count = count + 1 else: count = count • This is fine – if the condition fails, we simply do nothing: if base == "A": count = count + 1 no need

  28. Decisions Revistied • Difference between if-elif-elif(chained if) vs. if-if-if What is the result from computeGrade(80)? defcomputeGrade(score): if score >= 90: grade = "A" elif score >= 80: grade = "B" elifscore >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F" return grade defcomputeGrade(score): if score >= 90: grade = "A" ifscore >= 80: grade = "B" if score >= 70: grade = "C" ifscore >= 60: grade = "D" else: grade = "F" return grade

  29. 5 (stop value) is not included Repetition Revisited • General form for variable inrange(start, stop): ... DO SOMETHING ... • Example >>> for iinrange(1, 5): printi 1 2 3 4 >>>

  30. Repetition with Skips • Adding a step to skip at regular intervals(optional) : for variable inrange(start, stop, step): ... DO SOMETHING ... • Example >>> for iinrange(1, 9, 2): printi 1 3 5 7 >>> Same outcome for stop value of 8: >>> for iinrange(1, 8, 2): printi 1 3 5 7 >>>

  31. Slicing Strings • Extracting portions from a given string (slices) course = "Bioinformatics“ course ---> printcourse[0 : 3]displays Bio printcourse[3 : 7] displays info printcourse[5 : 11] displays format print course[10 : 14] displays tics • In general course[start : stop] will extract all characters from index start up to (but not including) index stop

  32. Skipping and Slicing • An example that uses skipping and slicing • write a function that prints the 3-letter codons in a given RNA >>> printCodons("GAUUACAUGAACGUU") GAU UAC AUG AAC GUU To print the 3-letter codons: 1. for every 3-rd index in the given RNA: - extract the codon at current index - print the codon from previos step

  33. Accumulation (count = count + 1) • To keep a running total use the construct: count = count + 1 • This just means: • evaluate the expression on the right side • store the result in the variable on the left side • For example >>>total = 0 >>> total = total + 1 # total is now 1 >>> total = total + 1 # total is now 2 >>> total = total + 1 # total is now 3

  34. Accumulation (count = count + 1) • Also works with strings, but it means “append” >>>name = "" >>> name = name + "B" # name is now "B" >>> name = name + "i" # name is now "Bi" >>> name = name + "o" # name is now "Bio" • However, it could mean “prepend” if the order is flipped >>>name = "" >>> name = "B" + name # name is now "B" >>> name = "i" + name # name is now "iB" >>> name = "o" + name # name is now "oiB"

  35. Commenting the Code • Comments are programmer’s notes ignored by Python • descriptions of the purpose of functions • annotations of subtle points in the code • annotations of meaning of variables • Comments aid in clarifying your programs to other programmers (and to you after a long break) • Comments can be added via # – anything after # until the end of the line is ignored by Python # computes the average of the given numbers x and y # e.g. average(20, 40) returns 30 defaverage(x, y): result = (x + y) / 2.0 return result

More Related