Docsity

Python Programming: Conditionals, Loops, and Functions, Summaries of Functional Programming

Partial preview of the text

Download Python Programming: Conditionals, Loops, and Functions and more Summaries Functional Programming in PDF only on Docsity!

Week Three

Conditionals, Loops, and Functions

Conditionals

  • (^) A conditional defines a certain “condition” in your code, which the computer determines as being “met”, or “not met.”
  • (^) The primary conditional is the “IF” statement.
  • (^) When you begin a line with “if” and indent a block of code, python will only run that code if the condition you define is met.

Conditionals

  • (^) You are not limited to using only one condition- you can use the special word ‘and’ to require multiple conditions to be met, or you can use ‘or’ to require only one of several possible conditions be met. You can also use parenthesis to group any combination of these together, and use contractions like <= and >=.
  • (^) Example

Conditionals

  • (^) What happens if the condition is not met? We can include an else statement: if x > 5: print ‘Yay!’ else: print ‘Aw’

Loops

  • (^) Loops allow us to set off a block of code to be repeated under various conditions.
  • (^) Two main kinds of loops: While-loops, and For-loops

While-Loops

  • (^) A while loop is a block of indented code that will continue to run over and over so long as the conditional statement at the top is evaluated as true.
  • (^) Example
  • (^) Note: Be careful defining while loops! If the code doesn’t have some mechanism within the loop to make sure the conditional will eventually be broken, then your code will hang in the while-loop forever!

Functions

  • (^) So far, the functions we have used are built into python or part of a package (e.g., numpy, matplotlib). Python also allows you to define your own functions
  • (^) You can specify which arguments your function takes, and what it returns
  • (^) Unlike a script (just code in a file), your function doesn’t “run” when your code is run; instead you have to actively call your function (and if your function returns something, you have to set a variable).

Script vs. Function

Example script:

x=

y=

print x+y

Example function:

def add(num1, num2):

x=num

y=num

sum = x+y

return sum

print add(5,7)

var = add(12,15)