0% found this document useful (0 votes)
43 views54 pages

Chapter 1

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 54

INTRODUCTION TO PYTHON

PROGRAMMING

Dr. Zahra Golrizkhatami

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


SOFTWARE DEVELOPMENT
LOOP

Design

Correct
Write
Logic

Correct
Test
Syntax

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


DESIGN
 Programmers need to
establish a solid
foundation before they
begin coding a project
 This involves
understanding the task
that the program must
perform
 Next, we need to
determine the steps
that need to be taken in
order to perform the
task
CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami
UNDERSTAND THE TASK
 Most programming projects begin with an interview with
the end user
 Programmers must ask lots of questions and get as many
details as possible about the task
 Follow ups are usually required
 After an interview a programmer generally constructs a
“software requirement” document
 This amounts to an agreement between the end user and
the programmer on what the program should actually do
 You may have heard the terms ‘user-centered design’ and
‘UX designer’ which are jobs and design methodologies
that are formed out of this process

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


UNDERSTAND THE TASK

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


FLOWCHARTS
 A graphical model that helps programmers
conceptualize the task at hand

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


INPUT, PROCESSING &
OUTPUT
 Programs typically perform the following 3 steps
¤ INPUT is received
¤ Some kind of PROCESSING is performed
¤ OUTPUT is produced

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


INPUT
 Can be from a variety of sources
¤ User: keyboard,mouse,etc.
¤ Hardware: scanner,camera,etc.
¤ Data: file, the Internet,etc.

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


PROCESSING
 A series of mathematical or logical processes are
applied to the input
¤ Compare values
¤ Add,multiply, divide or subtractnumbers
¤ Perform calculations on an item over and over again
(i.e. blurring animage)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


OUTPUT
 Some kind of
tangible / visible /
readable product is
constructed
¤ Printout
¤ Screen display
¤ 3D fabrication

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


BOILING A POT OF WATER

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


BOILING A POT OF
WATER
 Find a measuring cup  Find a stove
 Pick up measuring cup  Walk to stove
 Find a sink  Place the pot on the stove
 Walk to sink  Pour the water into the
 Turn on water pot
 Fill the measuring cup  Put measuring cup down
on countertop
with
 Turn the heat on the stove
 2 cups of water to Medium-High
 Turn off water  Wait until the water
 Find a pot begins to rapidly bubble
 Pick up pot  Turn off stove

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


ALGORITHMS
“A series of well defined,logical steps that must be
taken in order to perform a task”
Algorithms serve as a necessary intermediate step
between understanding the task at hand and
translating it into computer code
These aren’t necessarily overly complicated!

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


PSEUDOCODE
(aka “fake”code)
 A useful technique for breaking down an algorithm
into meaningful chunks and aligning them with the
toolset of a language
 In pseudocode we don’t have to worry about
syntax or spelling

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Pseudocode/Algorithm Practice
What to do in an awkward situation

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


PYTHON: GETTING STARTED
 IDLE:Integrated DeveLopment Environment
 Has two modes
¤ Interactive – commands are immediately processed as
they are received
¤ Script – allows to write a program (saved as a“text
file” on your computer) and have your commands
processed whenever you’d like
 We will mainly be using“script” mode during this
semester

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


PYTHON: CREATING ANEW PROGRAM
 Open IDLE
 Click on File -> NewWindow
 Click on File -> Save
 Save your file somewhere on your computer. You will
need to add the ‘.py’ file extension to your file if IDLE
does not place it there automatically.
 With your program open,click on Run -> Run Module
 If you need to open your program you can click on File
-> Open and browse to find the desired Python
source file (.py extension)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


FUNCTIONS
 A “function” is a pre-written piece of computer code thatwill
perform a specific action or set of actions
 Python comes with a number of built-in functions, and you canalso
write your own (more on that later in the semester)
 Functions always begin with a keyword followed by a series of
parenthesis.
¤ Ex:print ()
 You can“pass” one or more“arguments” into a function by placing
data inside the parenthesis
¤ Ex:print (‘Hello,World!’)
 Different functions “expect” different arguments.The print
function, for example,expects printed text as an argument
 When you ask Python to run a function we say that you have
“called” the function.

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


STRINGS
 Data that is textual in nature (i.e. “Hello,World!”)iscalled
a“String”
 Strings can contain 0 or more printed characters
 “String Literals” are strings that you define inside your
program.They are “hard coded” values and must be
“delimited” using a special character so that Python knows
that the text you’ve typed in should be treated as printed
text (and not a function call)
¤ Ex: print (‘hello,world!’)
 Python supports three different delimiters
¤ The single “tick” (‘ )
¤ The single quote (“ )
¤ The triple quote ( “””)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


PRINTING MULTIPLE ARGUMENTS
 The print() function can accept zero or more more
arguments
 If you decide to pass multiple arguments to the print()
function you should separate them by a comma. Example:
print (“Hello! My name is”, “Craig”)
 Note that when Python executes the function call above it
will insert a space between the two arguments for you
automatically.
 Also note that the print() function will automatically add a
line break after it prints the last argument it was passed.
We will discuss how to override this behavior in our next
class.

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


LINE ENDINGS
 When using the print() function you probably have
noticed that Python automatically places a newline
character at the end of each line
 You can override this behavior and have Python use a
character of your choice by using the optional ‘end’
argument when using the print() function
 Example:

print (‘one’, end=‘’)


print (‘two’, end=‘’)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


SEPARATING PRINT() FUNCTION
ARGUMENTS
 By default, Python will place a space between
arguments that you use in print() function calls
 You can override this behavior by using the
optional‘sep’ argument
 Example:

print (‘one’, ‘two’, sep=‘*’)

# output: one*two

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


COMBING BOTH LINE ENDINGS AND
SEPARATORS

 Youcan use both the‘sep’ and the‘end’arguments


at the same time in the same print() function call.
 Example:

print (‘a’, ‘b’, ‘c’, sep=‘*’,


end=‘’)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


VARIABLES
 Variables are like little “buckets” that can store information
in your computer’s memory
 You will be using variables constantly when writing your
programs in order to keep track of various pieces of
information
 You can create a variable by using the following syntax:
¤ variablename = somedata
 Examples:
 speed = 5
 myname =‘Batman’
 The‘=‘ symbol is called the‘assignment operator’ andwill
cause Python to store the data on the right side of the
statement into the variable name printed on the left side

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


VARIABLES

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


VARIABLE NAMING RULES
 You can’t use one of Python’s“reserved
words” (see the next slide for a list)
 Variables can’t contain spaces (though you can use
the underscore character (“_”) in place of a space)
 The first character of a variable name must be a
letter or the underscore character.Any character
after the first can be any valid alphanumeric
character (or the underscore character)
 Python is case sensitive

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


PYTHON RESERVED WORDS
(these words can’t be used when declaring a variable in
your program)

'False’,'None','True','and','as','assert','break','class',
'continue','def','del','elif','else','except','finally','for',
'from',
'global','if','import','in','is','lambda','nonlocal','not',
'or',
'pass','raise','return','try','while','with','yield'

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


LEGAL OR ILLEGAL VARIABLE
NAME?
class = 2
class_avg = 125
classAvg = 99
_class_avg = 99
2ndclassavg = 125
classavg! = 99

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


LEGAL OR ILLEGAL VARIABLE
NAME?
class = 2 • Illegal: “class” is a reserved
class_avg = 125 word
classAvg = 99 • Legal
_class_avg = 99
• Legal
• Legal
2ndclassavg = 125 • Illegal: can’t start with a
classavg! = 99 number
• Illegal: can only use
alphanumeric values and
the “_” symbol in variable
names

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


COMMON VARIABLENAMING
CONVENTIONS
rockettopspeed = # can be hard to
1000 read
rocket_top_speed # underscored
= 1000 # “camel case”
rocketTopSpeed =
1000

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


DISPLAYING VARIABLES WITH
THE PRINT FUNCTION
 You can print the data that is currently being held by a
variable by passing the variable name to the print()
function as an argument. Example:
print (myvar)
 As with string literals, you can tell the print() function
to display more than one item in the same function call
by separating your arguments with commas. Example:
name_var = “Slim Shady”
print (“Hi, my name is”, name_var)
>> Hi, my name is Slim Shady

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


REASSIGNING VARIABLES
 Variables are called variables because they can“vary”
the data that they store.
 You an re-assign the value that a variable stores by
simply using a second assignment statement. Example:

dollars = 10000000.99
print (‘I have’, dollars, ‘in my
account’)
dollars = 9.99
print (‘Now I have’, dollars, ‘in my
account)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


MULTIPLE ASSIGNMENTS
 It’s possible to set the value of multiple variables on the
same line. For example:
x, y, z = ‘a’, ‘b’, ‘c’

 In this case the variables x, y and z will assume the values


‘a’,‘b’,‘c’ in that order
 You can also assign the same value to multiple variables at
the same time by doing the following:
# a, b and c will all contain the
integer 100
a = b = c = 100

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


READING INPUT FROM
THE KEYBOARD
 So far we have learned how to:
¤ OUTPUT information (via the print function)
¤ STORE information (via variables)
 However, all of our programs have been “hardcoded,”
meaning that we have predefined the operating
environment using information that we ourselves have
defined.Example:
myname = ‘Harry Potter’

print (‘Welcome to my program’,


myname)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


READING INPUT FROM
THE KEYBOARD
 You can make your programs more interactive by involving
the user in the process
 One of the simplest ways to do this is to request
information from the keyboard using the input() function.
 Example:
# ask the user their name
username = input (‘What is your name?’)

# welcome them!
print (‘Welcome,‘, username)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


THE INPUT FUNCTION
 Input is a built-in function
 It accepts one argument – a String
 It then prompts the user with that string and waits for
them to type in a series of characters.Your program
will resume when the user hits the ENTER key
 Whatever the user typed in during that time is sent
back to your program as a string. You can store that
string in a variable. Example:

user_age = input(‘How old are you?’)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


THE INPUT FUNCTION
 The input() function always“returns” a String.
 This means that the output it generates is a string,
and when you store that output in a variable it will
be treated as though it is a string.

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


THE INPUT FUNCTION
 Note that these two line work using the same
mechanics:
var1 = “Blue”
var2 = input(“What is your favorite
color?”)
 In the first line of code we are assigning the String
Literal into the variable‘var1’
 In the second line of code we are assigning the
RESULT of the input function into the variable‘var2’
 Both ‘var1’ and‘var2’ will be filled with data afterthese
lines execute

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


PERFORMING CALCULATIONS
 Algorithms generally require some kind of
calculation to be performed
 All programming languages have tools for
manipulating numeric data – we generally call these
“math operations”

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


PYTHON MATH
OPERATIONS
Operation Operator

Addition +
Subtraction -
Multiplication *
Division (floating point) /
Division (integer) //

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


EXPRESSIONS
 We use operators along with numeric data to
create “math expressions” that Python can
“evaluate” on our behalf

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


EXPRESSIONS
+ Addition

5+2
operator
- Subtraction
* Multiplication
/ Division
operand operand ** Exponent
% Remainder
// Floor division

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


OUTPUTTING MATH
EXPRESSIONS
print (5+2)
print (100 * 5 – 12)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


STORING THE RESULTS OF AN
EXPRESSION

answer = 5 + 2
print (‘the answer to 5 + 2 is’,
answer)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


USING VARIABLES IN MATH
EXPRESSIONS
 Math expressions don’t necessarily need to involve
only numeric literals
 Example:

price = 100.00
sales_tax = 0.07

total = price + sales_tax*price

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Problem #1: Variables and Print Statements

Write a program that does the following:


•Create four variables that store the following pieces of data. Be sure
to name your variables in a way that makes sense to someone else
(i.e. don't name your variables something simple that doesn't relate
to the data that is being stored (like 'x' or 'y')).
•A title (store the string: Calories in desserts)
•Slice of cake (store the number: 239)
•Slice of pie (store the number: 310)
•Bowl of ice cream (store the number: 267)
•Using the print function and your variables, generate the following
output. Note the formatting in the output below –
•make your program match the formatting exactly (same # of spaces,
line breaks, etc)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Problem #1: Variables and
Print Statements

Health information for - Calories in desserts


- Slice of cake: 239
- Slice of pie: 310
- Bowl of ice cream: 267

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


SOLUTION

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


Problem #2: MATH EXPRESSIONS

• Write a program to calculate the user’s age in the format


of Years, Months, Days, Hours and Seconds.

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


SOLUTION

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


COMMENTS
 Commenting your code is EXTREMELY
IMPORTANT.
 In the real world, multiple people work on projects,
so programmers need to know what other team
members were thinking when they were writing code
a certain way.
 Scripts also get very large very quickly,and I swear you
forget what you were thinking when you wrote some lines
of code.

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


COMMENTS
 Starting now, the the first assignment, and for
everything you ever do after,comment,comment,
comment
 These lines of code are not executed but seen in
the source code explaining the code.A line of code
is commented out with a‘#’
#Variable to get users name
user_name = input(“What’s your name?”)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


COMMENTS
 If you want to comment multiple lines of code, you can use
three apostrophes on each side

• ‘’’Belowis a variable to get the


user’s name and say Hello’’’

• user_name=input(“enter your name:”)


• print(“Hello ”,user_name)

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami


COMMENTS
 You NEED to comment your work for better
understanding and make your code clear.
 Especially when our programs get more
complicated,logic, absolutely needs to be
commented

CS101 Introduction to Python Programming - Dr. Zahra Golrizkhatami

You might also like