Introduction to Programming
Introduction to Programming
the
ti c e
n o
y o u
i d
D s?
The print statement is used to
display text
print('Hickory Dickory Dock! The mouse ran up the
clock')
print("Hickory Dickory Dock! The mouse ran up the clock")
width = 20
height = 5
perimeter = 2*(width+height)
These are the most common
math operations
Symbol Operation Example
+ Addition 5+2 = 7
- Subtraction 5-2 = 3
* Multiplication 5*2 = 10
/ Division 5/2 = 2.5
** Exponent 5**2 = 25
% Modulo 5%2 = 1
Math rules haven’t changed
since school
Order of operations
( ) parentheses
** exponent (e.g. **2 squared **3 cubed)
*/ multiplication and division
+ - addition and subtraction
Assignment Statements
• We assign a value to a variable using the assignment statement (=)
x = 3.9 * x * ( 1 - x )
A variable is a memory location x 0.6
used to store a value (0.6)
0.6 0.6
x = 3.9 * x * ( 1 - x )
0.4
0.4
The right side is an expression. Once the
expression is evaluated, the result is
placed in (assigned to) the variable on the
0.936
left side (i.e., x).
INPUTTING
NUMBERS
Constants
• Fixed values such as numbers, letters, and strings, are called
“constants” because their value does not change
• Numeric constants are as you expect
>>> print(123)
• String constants use single quotes (') 123
or double quotes (") >>> print(98.6)
98.6
>>> print('Hello world')
Hello world
Variables
• A variable is a named place in the memory where a programmer can store
data and later retrieve the data using the variable “name”
x = 12.2 x 12.2
y = 14
y 14
Variables
• A variable is a named place in the memory where a programmer can store
data and later retrieve the data using the variable “name”
The input function allows you to specify a message to display and returns the
value typed in by the user.
We use a variable to remember the value entered by the user.
We called our variable “name” but you can call it just about anything as long the
variable name doesn’t contain spaces
Think of a variable as a box where you
can store something and come back to
get it later.
name
Chris
If you need to remember more than
one value, just create more variables
name favoriteMovie
Real
Chris
Genius
city
Pasaden
a
You can access the value you
stored later in your code
name = input("What is your name? ")
print(name)
You can also change the value of
a variable later in the code
name = input("What is your name? ")
print(name)
name = "Mary"
print(name)
Variable names
■ Rules
– Can not contain spaces
– Are case sensitive
■ firstName and firstname would be two different variables
– Cannot start with a number
■ Guidelines
– Should be descriptive but not too long (favoriteSign not
yourFavoriteSignInTheHoroscope)
– Use a casing "scheme"
■ camelCasing or PascalCasing
Which of the following do you think
would be good names for variables?
■ Variable1
■ First Name
■ Date
■ 3Name
■ DOB
■ DateOfBirth
■ YourFavoriteSignInTheHoroscope
Python Variable Name Rules
• Must start with a letter or underscore _
• Case Sensitive
hours = 35.0
What are these bits rate = 12.50
of code doing? pay = hours * rate
print(pay)
Sentences or Lines
x = 2 Assignment statement
x = x + 2 Assignment with expression
print(x) Print statement
https://www.w3schools.com/python/
python_strings_methods.asp
Slicing Strings M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11
• We can also look at any
continuous section of a string
using a colon operator >>> s = 'Monty Python'
>>> print(s[0:4])
• The second number is one Mont
beyond the end of the slice - >>> print(s[6:7])
“up to but not including” P
• If the second number is >>> print(s[6:20])
beyond the end of the string, Python
it stops at the end
Slicing Strings M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11
■a = "Hello, World!"
print(a[1])
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
■Get the characters from position 2 to
position 5 (not included):
■b = "Hello, World!"
print(b[2:5])
Get the characters from the start to
position 5 (not included):
■b = "Hello, World!"
print(b[:5])
Get the characters from position
2, and all the way to the end:
■b = "Hello, World!"
print(b[2:])
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
■b = "Hello, World!"
print(b[-5:-2])
The split() method splits the string into
substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', '
World!']
SEARCH AND REPLACE
• THE REPLACE()
FUNCTION IS LIKE A
“SEARCH AND
REPLACE” >>> greet = 'Hello Bob'
OPERATION IN A >>> nstr = greet.replace('Bob','Jane')
>>> print(nstr)
WORD PROCESSOR
Hello Jane
import datetime
import datetime
currentDate = datetime.date.today()
#strftime allows you to specify the date format
print (currentDate.strftime
('Please attend our event %A, %B %d in the
year %Y'))
Let’s get back to calculating days until
your birthday,
I need to ask your birthday.
birthday = input ("What is your birthday?
")
print ("Your birthday is " + birthday)
What datatype is birthday?
string
extBirthday = \
datetime.datetime.strptime('12/20/2014','%m/%d/%Y').date(
urrentDate = datetime.date.today()
If you subtract two dates you get back the number of days
between those dates
ifference = nextBirthday - currentDate
rint (difference.days)
Dates seem like a lot of hassle, is it worth
it? Why not just store them as strings!
■ You can tell someone when the milk in their fridge will expire
currentDate = datetime.date.today()
#timedelta allows you to specify the time
#to add or subtract from a date
print (currentDate + datetime.timedelta(days=15))
print (currentDate + datetime.timedelta(hours=15))
Working with time
What about times?
■ It is called Datetime, so yes, it can store times.
import datetime
currentTime = datetime.datetime.now()
print (currentTime)
print (currentTime.hour)
print (currentTime.minute)
print (currentTime.second)
Just like with dates you can use strftime()
to format the way a time is displayed
import datetime
currentTime = datetime.datetime.now()
print (datetime.datetime.strftime(currentTime,'%H:%M'))
%H Hours (24 hr clock)
%I Hours (12 hr clock)
%p AM or PM
%M Minutes
%S Seconds