You are on page 1of 47

Basic Programming

CS 111: Computer Science for Scientists


Elements of a Basic Program
All computer programs (i.e., algorithms) consist of the
following components:
Execution Operations
Sequential Operations
Conditional Operations
Iterative Operations
Data Operations
Variables & Assignments
Mathematical Expressions
Output & Input
Starting a program
First things first, how do we start a program
Every language has subtle differences about how you begin a
program, but all employ the same general idea
Designate part of a file as the main and tell the computer to start
there
Pythons Easy Main
Create a python file (ends in .py)
Start writing code
print("Hello world")
Right click to run (i.e., play)
starter.py
Done!

Later, well talk about other


more robust approaches for
creating a main.
Components revisited
Execution Operations
Sequential Operations
Condition Operations
Iterative Operations
Data Operations Code executes in the order
Variables & Assignments you write it generally
Mathematical Expressions
Output & Input
Comments
For an aside, comments are code that is
never executed.
We include comments as notes to
people who read the code (i.e., future # This is ignored
print("Hello world")
you ) # So is this
To write a comment use the # character.
Everything after that will be ignored.
Components revisited
Execution Operations
Sequential Operations
Condition Operations
Iterative Operations
Data Operations
Variables & Assignments Variables allow us to store data
Mathematical Expressions
Output & Input
Creating a variable
Its easy to make a variable in Python.
Just type a word and give assign it a value
hello = 4
Done, Ive made a variable hello
I havent done anything with it aside from give it a value
but there you go.
Rules of Making a Variable
Variables cannot contain spaces
If you want to use mutlipleWordsUseCamelCapitalization
Variable must start with a letter
Numbers are OK, but they must start with a letter
Dont use special characters except _
Thats an underscore not a minus
Some words cannot be variables (e.g., True, False, if, else)
These are called keywords, youll learn more as we go along
Only one variable can have a name in the current scope
Well define scope later. Right now, dont repeat variable names
Types of variables
The type of a variable is based on the data that you assign it
Primarily, you care about four types of variables: int, float,
str, and bool
-3, -2, -1, 0, 1, 2, 3... are integers (int)
Numbers with a decimal are floating point numbers (float)
Words, phrases, or whatever in quotes are strings. (str)
True and False (capitalized) are the Boolean values. (bool)
Examples

x = 45 #integer
z = -3410 #integer
myPie = 3.14 #float
wordsTogether = "Hi there" #string
wordsTogether2 = We are learning Python!" #string
isItRight = True #Boolean
isItWrong = False #Boolean
sadSauce = 25.0 #float
happySauce = 25 #int (no .)
awesomeSauce = "25" #String (quotes)
sillySauce = "True" #String (quotes)
Assignment
A note about assignment.
The right value is always
assigned to the left
x = 45
variable
This allows you to assign
the value of a variable to
another variable.
x = 25 #x has value of 25
y = 33 #y has value of 33
x = y #x has value of 33, y is unchanged
Why bother differentiating float and int?
Even though float and int both represent numbers, we
need to have two different types for these values because of
how they are stored on the computer.
int has no decimal point
float can represent more numbers.
For example,
When you reference pages in a book you use integers
Go to page 45
However, float can express more numbers
1.4234325234
Floats
Essentially floats store a limited number of digits.
So, 2/3 is stored as 0.666666666 not 0.666666666
This means that we cant tell the difference between
0.6666666666 and 0.6666666667. Since its one more digit
than we stored.
This issue is compounded by the fact that how computers
actually store float is crazy.

Long story, use int where you can.


Components revisited
Execution Operations
Sequential Operations
Condition Operations
Iterative Operations
Data Operations Allow us to share data with the
Variables & Assignments user and get data from the user
Mathematical Expressions
Output & Input
Simple Output
The simplest form of output is the
function print()
Whatever you put in the () will be
displayed to the user. print("hello")
print(3)
The place where its displayed is called the x = 420
console. print(x)

If you put a variable in the (), then it will


print the value of the variable.
Simple Input
The simplest way to get data from
the user is the function input()
In the console, this will print out
whatever you put in the () and value = input("Please type a word")
print(value)
return whatever the user types in
as a string.
Well come back to that as a string
thing in a bit
Components revisited
Execution Operations
Sequential Operations
Condition Operations
Iterative Operations
Data Operations
Variables & Assignments Allows us to manipulate data
Mathematical Expressions
Output & Input
Mathematical Operations
As youd expect Python has the basic
ability to do math
+, -, *, and / a = 2 + 3 # 5
b = 4 * a # 20
Also, it has a few extra ones x = 12%5 #remainder 2
y = 32/3 #32.666666
** is used for exponent z = 32//3 #32
// is used for integer division (divide to q = 3**4 #3*3*3*3 = 81
numbers, round down)
% is used to calculate the remainder
Adding and Multiplying Strings
Python also lets you use + and * operations on strings.
If you add, i.e., concatenate, two strings then you get one
longer string
"hello" + "goodbye"
This makes "hellogoodbye"
Multiplying a string by an integer repeats the string that
number of time
"hello" * 3
This makes "hellohellohello"
Types and Operations
Notice that 32+3, 32*3, 32-3, 32//3, and 32%3 all
involve two integers and the result is an integer; however
32/3 is a float.
On a related note, 32.0+3, 32.0*3, 32.0-3, 32.0//3,
and 32.0%3 are all floats.
This behavior is called implicit conversion
Explicit Conversion
Sometimes you need a value to have a different type
You can do this via, explicit conversion.
int() will return an integer
float() will return floating point value
str() will return a string
bool() will return a boolean

x = int(25.0) # x is an int
y = int(25.4) # y is 25
z = float(25) #z is a float
a = str(25) #a is the string "25"
q = int(25.4) + 3 # q = 28
w = "q is :"+str(q) # w equals "q is :28"
Input and Conversion
Recall, input() always returns a string.
So, suppose wrote
z = input("Enter an integer")
value = z + 10
print(value)

and had the user enter 12


The program would crash
Because we cant add 12 + 10.
Itd be like adding apple + 24.
Input and Conversion
To fix this, we need to explicitly convert the input value to an
integer.
Like so
z = int(input("Enter an integer"))
value = z + 10
print(value)

Now if the user enters 12 it will print out 22.


Note: if the user enters Apple, then it will crash. However,
this is the behavior wed expect. So, its OK.
Changing yourself
Consider the following code
x = 25
y = x + 30
x = y

What is the value of x at the end of this code?


Changing yourself
Consider the following code
x = 25
y = x + 30
x = y

What is the value of x at the end of this code?


Its equal to 55.
Well what if we took y as a middle man and wrote
x = 25
x = x + 30

x would still be equal to 55


Changing yourself (short)
While this code works
x = 25
x = x + 30

its so LONG! I have to write out x THREE TIMES. Im not made of


xs
Python provides a shortcut for this using +=
x = 25
x += 30
Ahhh! Much better!
Not only is this shorter, its also less error prone.
Changing yourself (more)
You can use this operation with -,*, %, /, and //.
-=
*=
%=
/=
//=
Comparison Operations
We also have comparison
operations as well
Less than <
Greater than > x = 2 < 3 # true
a = 3 < 3 # false
Less than or equal to <= y = 2 <= 3 # true
Greater than or equal to <= b = 3 <= 3 # true
z = 2 > 3 # false
Equal to == w = 5 != 5 # false
Not Equal to != q = 5 == 5 # true

The result of each of these


operations is a Boolean value.
= vs ==
There are two operations = and ==
= is used for assignment
== is used to TEST for equality.
This is one of the most common mistakes early programmers
use.
Boolean Operations
Additionally there are three Boolean
operations we can use: and, or, not.
x and y is True if both x and y are True
x or y is True only if either x or y, or a = True
x = True
both are True y = False
not x is true only if x is False. z = x and y #False
q = x or y #True
j = x or a #True
w = not x #False
Boolean Operations
A A

True False True False

True True False True True True True False


B
B B
False False False False True False False True

A and B A or B not B
Combing Boolean Operations
Lets go ahead and combine some Boolean operations!
Components revisited
Execution Operations
Sequential Operations
Condition Operations
Iterative Operations
Conditions allow you to
Data Operations
Variables & Assignments chose which code is
Mathematical Expressions executed
Output & Input
if
The heart of conditional operations
is the if statement
The if statement evaluates a val = int(input("enter value"))
Boolean expression and will run a if val < 10:
print("The value is < 10")
segment of code if that Boolean print("Another thing")
expression is True. print("Conditional")
val = -3
The segment of conditional code is print("always runs")
designated via indention. print(val)

Note: you need the : only in the if


line
else
Sometimes if the if statement is
False, you want to do something
else. val = int(input("enter value"))
if val < 10:
Hence, ifs twin: else. print("The value is < 10")
It runs code if the if fails. val = -3
else:
else can only be used immediately print("Only if false")
after the ifs segment of code. val = 100
print("always runs")
print(val)
elif
How about if the if statement
fails but some other condition val = int(input("enter value"))
is True. if val < 10:
print("The value is < 10")
Thus, elif val = -3
elif val < 20:
print("Only if >=10 and < 20")
val = 18
else:
print(">= 20")
val = 30
print("always runs")
print(val)
Stacking elif
We can have as many elif val = int(input("enter value"))
if val < 10:
statements as we want. print("The value is < 10")
However, an elif statement will only val = -3
elif val < 20:
be executed if everything before it print("Only if >=10 and < 20")
has failed val = 18
elif val < 40:
The else statement always comes print("Only if >=20 and < 40")
val = 22
last else:
else only executes if everything fails print(">= 40")
val = 30
You dont need an else print("always runs")
print(val)
Unreachable code
Its possible to write code that can
never execute. val = int(input("enter value"))
You need to be careful about the if val < 10:
print("The value is < 10")
order you put your elif statements val = -3
elif val < 0:
print(Never run")
else:
print(">= 10")
val = 30
print("always runs")
print(val)
Iterative Operations
Execution Operations
Sequential Operations
Condition Operations Iterative operations allow
Iterative Operations
us to repeat a segment of
Data Operations
Variables & Assignments
code a given number of
Mathematical Expressions times
Output & Input
While its true Dont forget the :

The main way we iterate segments of code is by using the


while loop.
This repeats the independent segment of code while a
Boolean expression is True.
When its False we stop.

val = int(input("Enter a no."))


while val > 0:
print("Larger > 0")
val = int(input("Enter a no."))
print("we're done!")
Loop a set number of times
Suppose we want to loop 10 times?
Heres how:

count = 0
while count < 10:
print("The count is"+str(count))
print("Whatever code you want")
count+=1
print("we're done")
Components of a while loop
Generally all while loops have the same four components

count = 0
while count < 10:
print("The count is"+str(count))
print("Whatever code you want")
count+=1
print("we're done")

Initialization: Set the initial value of test variable


Components of a while loop
Generally all while loops have the same four components

count = 0
while count < 10:
print("The count is"+str(count))
print("Whatever code you want")
count+=1
print("we're done")

Test: The Boolean expression is evaluated before EVERY


iteration of the loop. If it fails, the loop is done. If its never
true, the loop never runs.
Components of a while loop
Generally all while loops have the same four components

count = 0
while count < 10:
print("The count is"+str(count))
print("Whatever code you want")
count+=1
print("we're done")

Body: The segment of code that is executed. It is designated


by the indention.
Components of a while loop
Generally all while loops have the same four components

count = 0
while count < 10:
print("The count is"+str(count))
print("Whatever code you want")
count+=1
print("we're done")

Increment: This is part of the body and modifies at least one


of the variables in the Boolean Expression
Components
At their heart every program is just the six components weve
covered.
In the rest of this class, well learn how to combine these six
pieces to solve a wide-range of problems.
Also, well learn about other components that can improve
on the six weve covered.

You might also like