0% found this document useful (0 votes)
2 views

Introduction to Programming

The document provides an introduction to Python programming, emphasizing the importance of using comments, handling strings, and performing mathematical operations. It covers variable assignment, user input, and basic string manipulation techniques, including concatenation and slicing. Additionally, it highlights best practices for naming variables and the use of built-in functions for data type conversion.

Uploaded by

ali.alekber0700
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Introduction to Programming

The document provides an introduction to Python programming, emphasizing the importance of using comments, handling strings, and performing mathematical operations. It covers variable assignment, user input, and basic string manipulation techniques, including concatenation and slicing. Additionally, it highlights best practices for naming variables and the use of built-in functions for data type conversion.

Uploaded by

ali.alekber0700
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 77

Pick up good habits right away!

■ Comments in your code help you or someone else understand


■ What your program does
– What a particular line or section of code does
– Why you chose to do something a particular way
– Anything that might be helpful to know if I am looking at the code later and
trying to understand it!
– Turn off a line of code - perhaps temporarily
In Python we use a # to indicate
#Mycomments
first Python Application
#Created by me!
#Print command displays a message on the screen
print('Hello World')

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")

You can use single quotes or double quotes


Does it matter if you use single
or double quotes?
print("It's a beautiful day in the neighborhood")

print('It's a beautiful day in the neighborhood')

Only if the string you are displaying contains a single or


double quote.

It’s a good habit to pick one and stick with it as much as


possible.
What if I want my text to appear
on multiple lines?
You can use multiple print statements
print('Hickory Dickory Dock!')
print('The mouse ran up the clock')
You can also use “\n” to force a
new line

print('Hickory Dickory Dock!\nThe mouse ran up the clock')


Here’s a neat Python trick: triple
quotes!
print("""Hickory Dickory Dock!
The mouse ran up the clock""")
print('''Hickory Dickory Dock!
The mouse ran up the clock''')

When you put the string in triple quotes, it will be


displayed the way you have the string in the text editor
Which do you think is better?

print('Hickory Dickory Dock!')


print('The mouse ran up the clock')
print('Hickory Dickory Dock!\nThe mouse ran up the
clock')
print('''Hickory Dickory Dock!
The mouse ran up the clock''')
So it might be useful to practice
finding our mistakes

print(Hickory Dickory Dock)


print('Hickory Dickory Dock')
print('It's a small world')
print("It's a small world")
print("Hi there') print("Hi there")
prnit("Hello World!") print("Hello World!")
Which do you think is better?

print('Hickory Dickory Dock!')


print('The mouse ran up the clock')

print('Hickory Dickory Dock!\nThe mouse ran up the clock


print('''Hickory Dickory Dock!
The mouse ran up the clock''')
STORING
NUMBERS
So it’s important to be able to store and
manipulate numbers as well as strings
age = 42
print(age)
You can perform math operations on
numeric values or on variables containing
numeric values

width = 20
height = 5

area = width * height

perimeter = 2*width + 2*height

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 (=)

• An assignment statement consists of an expression on the


right-hand side and a variable to store the result

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

The right side is an expression.


0.936
Once the expression is evaluated, the
result is placed in (assigned to) x.
A variable is a memory location used to
store a value. The value stored in a x 0.6 0.936
variable can be updated by replacing the
old value (0.6) with a new value (0.936).
0.6 0.6
x = 3.9 * x * ( 1 - x )

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”

• Programmers get to choose the names of the variables

• You can change the contents of a variable in a later statement

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”

• Programmers get to choose the names of the variables

• You can change the contents of a variable in a later statement

x = 12.2 x 12.2 100


y = 14
x = 100 y 14
STRING VARIABLES AND
ASKING A USER TO ENTER A
VALUE
INPUT
How can we ask a user for
information?
name = input("What is your 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 _

• Must consist of letters, numbers, and underscores

• Case Sensitive

Good: spam eggs spam23 _speed


Bad: 23spam #sign var.12
Different: spam Spam SPAM
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b
print(x1q3p9afd) print(c)

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

Variable Operator Constant Function


Reserved Words
You cannot use reserved words as variable names / identifiers

False class return is finally


None if for lambda continue
True def from while nonlocal
and del global not with
as elif try or yield
assert else import pass
break except in raise
MANIPULATING
VARIABLES
You can combine variables and
strings with the + symbol
firstName = input("What is your first name? ")
lastName = input("What is your last name? " )
print("Hello" + firstName + lastName)
Often you need to add punctuation or
spaces to format the output correctly
firstName = input("What is your first name? ")
lastName = input("What is your last name? " )
print("Hello " + firstName + " " + lastName)
Now you can create a story teller
program!
animal = input("What is your favorite animal? " )
building = input("Name a famous building: ")
color = input("What is your favorite color? ")
print("Hickory Dickory Dock!")
print("The "+color+" "+animal+" ran up the "+building)
Why did we get the wrong answer when
we ask the user to enter their bonus and
salary values?

salary = input("Please enter your salary: ")


bonus = input("Please enter your bonus: ")
g ?
payCheck = salary + bonus
print(payCheck)
ro n
t w
en
t w
h a
The program thought salary and bonus
were strings so it concatenated instead of
adding
salary = 5000
bonus = 500
payCheck = salary + bonus
print(payCheck)
Here is a hint: The input
statement returns strings
salary = '5000'
bonus = '500'
payCheck = salary + bonus
print(payCheck)
There are functions to convert
from one datatype to another.
int(value) converts to an integer
long(value) converts to a long integer
float(value) converts to a floating number
(i.e. a number that can hold decimal places)
str(value) converts to a string

Which function should we use to fix our code?


If we convert the string to a float
we get the desired result
salary = input("Please enter your salary: ")
bonus = input("Please enter your bonus: ")
payCheck = salary + bonus
payCheck = float(salary) + float(bonus)
print(payCheck)
What do you think will happen if someone
types “BOB” as their salary?
The code crashes because we can’t convert
the string “BOB” into a numeric value. We will
learn how to handle errors later!
Your Challenge – create a loan
calculator
■ Have the user enter the cost of the loan, the interest rate, and the number of years
for the loan
■ Calculate monthly payments with the following formula
M = L[i(1+i)n] / [(1+i)n-1]
■ M = monthly payment
■ L = Loan amount
■ i = interest rate (for an interest rate of 5%, i = 0.05)
■ n = number of payments
String Data Type
>>> str1 = "Hello"
>>> str2 = 'there'
>>> bob = str1 + str2
>>> print(bob)
• A string is a sequence of characters Hellothere
>>> str3 = '123'
• A string literal uses quotes >>> str3 = str3 + 1
'Hello' or "Hello" Traceback (most recent call
last): File "<stdin>", line 1,
• For strings, + means “concatenate” in <module>
TypeError: cannot concatenate
• When a string contains numbers, it is 'str' and 'int' objects
still a string >>> x = int(str3) + 1
>>> print(x)
• We can convert numbers in a string 124
>>>
into a number using int()
Variables also allow you to manipulate
the contents of the variable

message = 'Hello world'


print(message.lower())
print(message.upper())
print(message.swapcase())
What do you think these
functions will do?
message = 'Hello world'
print(message.find('world'))
print(message.count('o'))
print(message.capitalize())
print(message.replace('Hello','Hi'))
Functions and variables allow us to
make new mistakes in our code…
Each line of code below has a mistake…

message = Hello world message = 'Hello world'


23message = 'Hello world' 23message = 'Hello world'
New message = 'Hi there' New message = 'Hi there'
print(message.upper) print(message.upper())
print(mesage.lower()) print(message.lower())
print(message.count()) print(message.count('H'))
String Library
str.capitalize() str.replace(old, new[, count])
str.center(width[, fillchar]) str.lower()
str.endswith(suffix[, start[, end]]) str.rstrip([chars])
str.find(sub[, start[, end]]) str.strip([chars])
str.lstrip([chars]) str.upper()

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

>>> s = 'Monty Python'


If we leave off the first number >>> print(s[:2])
or the last number of the slice, Mo
it is assumed to be the >>> print(s[8:])
beginning or end of the string
thon
respectively
>>> print(s[:])
Monty Python
■Get the character at position 1 (remember
that the first character has the position 0):

■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

• IT REPLACES ALL >>> nstr = greet.replace('o','X')


>>> print(nstr)
OCCURRENCES OF HellX BXb
THE SEARCH STRING >>>
WITH THE
REPLACEMENT
STRING
STRIPPING WHITESPACE
• SOMETIMES WE WANT TO
TAKE A STRING AND
REMOVE WHITESPACE AT
THE BEGINNING AND/OR >>> greet = ' Hello Bob '
END >>> greet.lstrip()
'Hello Bob '

• LSTRIP() AND RSTRIP() >>> greet.rstrip()


' Hello Bob'
REMOVE WHITESPACE AT >>> greet.strip()
THE LEFT OR RIGHT 'Hello Bob'
>>>
• STRIP() REMOVES BOTH
BEGINNING AND ENDING
WHITESPACE
Prefixes
>>> line = 'Please have a nice day'
>>> line.startswith('Please')
True
>>> line.startswith('p')
False
Parsing and
21 31 Extracting
From [email protected] Sat Jan 5 09:14:16 2008

>>> data = 'From [email protected] Sat Jan 5 09:14:16 2008'


>>> atpos = data.find('@')
>>> print(atpos)
21
>>> sppos = data.find(' ',atpos)
>>> print(sppos)
31
>>> host = data[atpos+1 : sppos]
>>> print(host)
uct.ac.za
WORKING WITH
DATES AND
TIMES
DATETIME
If I want to know how many days until
my birthday, first I need today’s date
■ The datetime class allows us to get the current date and time

#The import statement gives us access to


#the functionality of the datetime class
import datetime
#today is a function that returns today's date
print (datetime.date.today())
You can store dates in variables

import datetime

#store the value in a variable called current


Date
currentDate = datetime.date.today()
print (currentDate)
You can access different parts of
the date
import datetime
currentDate = datetime.date.today()
print (currentDate)
print (currentDate.year)
print (currentDate.month)
print (currentDate.day)
Date formats
In Python we use strftime to
format dates
import datetime
currentDate = datetime.date.today()
#strftime allows you to specify the date for
mat
print (currentDate.strftime('%d %b,%Y'))
Here’s a few more you may find
useful
■ %b is the month abbreviation
■ %B is the full month name
■ %y is two digit year
■ %a is the day of the week abbreviated
■ %A is the day of the week
Could you print out a wedding
invitation?
“Please attend our event Sunday, July 20 in the year 1997”

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

if we want to treat it like a date (for example use


the datetime functions to print it in a particular
format) we must convert it to a date
The strptime function allows you
to convert a string to a date
import datetime
birthday = input ("What is your birthday? ")
birthdate =
datetime.datetime.strptime(birthday,"%m/%d/%Y").date()
#why did we list datetime twice?
#because we are calling the strptime function
#which is part of the datetime class
#which is in the datetime module
print ("Your birth month is " + birthdate.strftime('%B')
Dates seem like a lot of hassle, is it worth
it? Why not just store them as strings!
■ You can create a countdown to say how many days until a big event or holiday

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

You might also like