SlideShare a Scribd company logo
Outlines of presentation
Python Basis
C:usersHPpython
Python 3.10.8 (tags/v3.10.8:aaaf517, Oct 11 2022, 16:50:30)
[MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more
information.
>>> x = 1
>>> print(x)
1
>>> x = x + 1
>>> print(x)
2
>>> exit()
This is a good test to make sure that you have
Python correctly installed. Note that quit() also
works to end the interactive session.
Constants
• Fixed values such as numbers, letters, and strings,
are called “constants” because their value does not
change
• Numeric constants are as you expect
• String constants use single quotes (')
or double quotes (")
>>> print(123)
123
>>> print(98.6)
98.6
>>> print('Hello world')
Hello world
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
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
12.2
x
14
y
x = 12.2
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
12.2
x
14
y
100
x = 12.2
y = 14
x = 100
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
Mnemonic Variable Names
• Since we programmers are given a choice in how we choose our
variable names, there is a bit of “best practice”
• We name variables to help us remember what we intend to store
in them (“mnemonic” = “memory aid”)
• This can confuse beginning students because well-named
variables often “sound” so good that they must be keywords
http://en.wikipedia.org/wiki/Mnemonic
Sentences or Lines
x = 2
x = x + 2
print(x)
Variable Operator Constant Function
Assignment statement
Assignment with expression
Print statement
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 )
x = 3.9 * x * ( 1 - x )
0.6
x
The right side is an expression.
Once the expression is evaluated, the
result is placed in (assigned to) x.
0.6 0.6
0.4
0.936
A variable is a memory location
used to store a value (0.6)
x = 3.9 * x * ( 1 - x )
0.6 0.936
x
0.4
0.936
The right side is an expression. Once the
expression is evaluated, the result is
placed in (assigned to) the variable on the
left side (i.e., x).
A variable is a memory location used to
store a value. The value stored in a
variable can be updated by replacing the
old value (0.6) with a new value (0.936).
0.6 0.6
Numeric Expressions
• Because of the lack of mathematical
symbols on computer keyboards - we
use “computer-speak” to express the
classic math operations
• Asterisk is multiplication
• Exponentiation (raise to a power) looks
different than in math
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
** Power
% Remainder
>>> xx = 2
>>> xx = xx + 2
>>> print(xx)
4
>>> yy = 440 * 12
>>> print(yy)
5280
>>> zz = yy / 1000
>>> print(zz)
5.28
>>> jj = 23
>>> kk = jj % 5
>>> print(kk)
3
>>> print(4 ** 3)
64
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
** Power
% Remainder
5 23
4 R 3
20
3
Numeric Expressions
Order of Evaluation
• When we string operators together - Python must know which one
to do first
• This is called “operator precedence”
• Which operator “takes precedence” over the others?
x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
Highest precedence rule to lowest precedence rule:
Parentheses are always respected
Exponentiation (raise to a power)
Multiplication, Division, and Remainder
Addition and Subtraction
Left to right
Parenthesis
Power
Multiplication
Addition
Left to Right
1 + 2 ** 3 / 4 * 5
1 + 8 / 4 * 5
1 + 2 * 5
1 + 10
11
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print(x)
11.0
>>>
Parenthesis
Power
Multiplication
Addition
Left to Right
Operator Precedence
• Remember the rules top to bottom
• When writing code - use parentheses
• When writing code - keep mathematical expressions simple enough
that they are easy to understand
• Break long series of mathematical operations up to make them
more clear
Parenthesis
Power
Multiplication
Addition
Left to Right
What Does “Type” Mean?
• In Python variables, literals, and
constants have a “type”
• Python knows the difference between
an integer number and a string
• For example “+” means “addition” if
something is a number and
“concatenate” if something is a string
>>> ddd = 1 + 4
>>> print(ddd)
5
>>> eee = 'hello ' + 'there'
>>> print(eee)
hello there
concatenate = put together
Type Matters
• Python knows what “type”
everything is
• Some operations are
prohibited
• You cannot “add 1” to a string
• We can ask Python what type
something is by using the
type() function
>>> eee = 'hello ' + 'there'
>>> eee = eee + 1
Traceback (most recent call last):
File "<stdin>", line 1, in
<module>TypeError: Can't convert
'int' object to str implicitly
>>> type(eee)
<class'str'>
>>> type('hello')
<class'str'>
>>> type(1)
<class'int'>
>>>
Several Types of Numbers
• Numbers have two main types
- Integers are whole numbers:
-14, -2, 0, 1, 100, 401233
- Floating Point Numbers have
decimal parts: -2.5 , 0.0, 98.6, 14.0
• There are other number types - they
are variations on float and integer
>>> xx = 1
>>> type (xx)
<class 'int'>
>>> temp = 98.6
>>> type(temp)
<class'float'>
>>> type(1)
<class 'int'>
>>> type(1.0)
<class'float'>
>>>
Type Conversions
• When you put an integer and
floating point in an
expression, the integer is
implicitly converted to a float
• You can control this with the
built-in functions int() and
float()
>>> print(float(99) + 100)
199.0
>>> i = 42
>>> type(i)
<class'int'>
>>> f = float(i)
>>> print(f)
42.0
>>> type(f)
<class'float'>
>>>
Integer Division
Integer division produces a floating
point result
>>> print(10 / 2)
5.0
>>> print(9 / 2)
4.5
>>> print(99 / 100)
0.99
>>> print(10.0 / 2.0)
5.0
>>> print(99.0 / 100.0)
0.99
This was different in Python 2.x
String
Conversions
• You can also use int() and
float() to convert between
strings and integers
• You will get an error if the string
does not contain numeric
characters
>>> sval = '123'
>>> type(sval)
<class 'str'>
>>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object
to str implicitly
>>> ival = int(sval)
>>> type(ival)
<class 'int'>
>>> print(ival + 1)
124
>>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
with base 10: 'x'
User Input
• We can instruct Python to
pause and read data from
the user using the input()
function
• The input() function
returns a string
nam = input('Who are you? ')
print('Welcome', nam)
Who are you? Chuck
Welcome Chuck
Converting User Input
• If we want to read a number
from the user, we must
convert it from a string to a
number using a type
conversion function
• Later we will deal with bad
input data
inp = input('Europe floor?')
usf = int(inp) + 1
print('US floor', usf)
Europe floor? 0
US floor 1
Comments in Python
• Anything after a # is ignored by Python
• Why comment?
- Describe what is going to happen in a sequence of
code
- Document who wrote the code or other ancillary
information
- Turn off a line of code - perhaps temporarily
# Get the name of the file and open it
name = input('Enter file:')
handle = open(name, 'r')
# Count word frequency
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1
# Find the most common word
bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
# All done
print(bigword, bigcount)
Summary
• Type
• Reserved words
• Variables (mnemonic)
• Operators
• Operator precedence
• Integer Division
• Conversion between types
• User input
• Comments (#)
Exercise
Write a program to prompt the user for hours
and rate per hour to compute gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
Conditional Execution
Chapter 3
Python for Everybody
www.py4e.com
Conditional Steps
Output:
Smaller
Finis
Program:
x = 5
if x < 10:
print('Smaller')
if x > 20:
print('Bigger')
print('Finis')
x = 5
x < 10 ?
print('Smaller')
x > 20 ?
print('Bigger')
print('Finis')
Yes
No
Yes
No
Comparison Operators
• Boolean expressions ask a
question and produce a Yes or No
result which we use to control
program flow
• Boolean expressions using
comparison operators evaluate to
True / False or Yes / No
• Comparison operators look at
variables but do not change the
variables
http://en.wikipedia.org/wiki/George_Boole
Remember: “=” is used for assignment.
Python Meaning
< Less than
<= Less than or Equal to
== Equal to
>= Greater than or Equal to
> Greater than
!= Not equal
Comparison Operators
x = 5
if x == 5 :
print('Equals 5')
if x > 4 :
print('Greater than 4')
if x >= 5 :
print('Greater than or Equals 5')
if x < 6 : print('Less than 6')
if x <= 5 :
print('Less than or Equals 5')
if x != 6 :
print('Not equal 6')
Equals 5
Greater than 4
Greater than or Equals 5
Less than 6
Less than or Equals 5
Not equal 6
One-Way Decisions
x = 5
print('Before 5')
if x == 5 :
print('Is 5')
print('Is Still 5')
print('Third 5')
print('Afterwards 5')
print('Before 6')
if x == 6 :
print('Is 6')
print('Is Still 6')
print('Third 6')
print('Afterwards 6')
Before 5
Is 5
Is Still 5
Third 5
Afterwards 5
Before 6
Afterwards 6
x == 5 ?
Yes
print('Still 5')
print('Third 5')
No print('Is 5’)
Indentation
• Increase indent indent after an if statement or for statement (after : )
• Maintain indent to indicate the scope of the block (which lines are affected
by the if/for)
• Reduce indent back to the level of the if statement or for statement to
indicate the end of the block
• Blank lines are ignored - they do not affect indentation
• Comments on a line by themselves are ignored with regard to indentation
Warning: Turn Off Tabs!!
Atom automatically uses spaces for files with ".py" extension (nice!)
• Most text editors can turn tabs into spaces - make sure to enable this
feature
- NotePad++: Settings -> Preferences -> Language Menu/Tab Settings
- TextWrangler: TextWrangler -> Preferences -> Editor Defaults
• Python cares a *lot* about how far a line is indented. If you mix tabs and
spaces, you may get “indentation errors” even if everything looks fine
This will save you
much unnecessary
pain.
x = 5
if x > 2 :
print('Bigger than 2')
print('Still bigger')
print('Done with 2')
for i in range(5) :
print(i)
if i > 2 :
print('Bigger than 2')
print('Done with i', i)
print('All Done')
increase / maintain after if or for
decrease to indicate end of block
x = 5
if x > 2 :
print('Bigger than 2')
print('Still bigger')
print('Done with 2')
for i in range(5) :
print(i)
if i > 2 :
print('Bigger than 2')
print('Done with i', i)
print('All Done')
Think About begin/end Blocks
x = 42
if x > 1 :
print('More than one')
if x < 100 :
print('Less than 100')
print('All done')
Nested
Decisions
x > 1
print('More than one’)
x < 100
print('Less than 100')
print('All Done')
yes
yes
no
no
Two-way Decisions
• Sometimes we want to
do one thing if a logical
expression is true and
something else if the
expression is false
• It is like a fork in the
road - we must choose
one or the other path but
not both
x > 2
print('Bigger')
yes
no
x = 4
print('Not bigger')
print('All Done')
Two-way Decisions
with else:
x > 2
print('Bigger')
yes
no
x = 4
print('All Done')
x = 4
if x > 2 :
print('Bigger')
else :
print('Smaller')
print('All done')
print('Not bigger')
Visualize Blocks
x = 4
if x > 2 :
print('Bigger')
else :
print('Smaller')
print('All done')
x > 2
print('Bigger')
yes
no
x = 4
print('All Done')
print('Not bigger')
More Conditional
Structures…
Multi-way
if x < 2 :
print('small')
elif x < 10 :
print('Medium')
else :
print('LARGE')
print('All done')
x < 2 print('small')
yes
no
print('All Done')
x < 10 print('Medium')
yes
print('LARGE')
no
Multi-way
x = 0
if x < 2 :
print('small')
elif x < 10 :
print('Medium')
else :
print('LARGE')
print('All done')
x < 2 print('small')
yes
no
print('All Done')
x < 10 print('Medium')
yes
print('LARGE')
no
x = 0
Multi-way
x = 5
if x < 2 :
print('small')
elif x < 10 :
print('Medium')
else :
print('LARGE')
print('All done')
x < 2 print('small')
yes
no
print('All Done')
x < 10 print('Medium')
yes
print('LARGE')
no
x = 5
Multi-way
x = 20
if x < 2 :
print('small')
elif x < 10 :
print('Medium')
else :
print('LARGE')
print('All done')
x < 2 print('small')
yes
no
print('All Done')
x < 10 print('Medium')
yes
print('LARGE')
no
x = 20
Multi-way
# No Else
x = 5
if x < 2 :
print('Small')
elif x < 10 :
print('Medium')
print('All done')
if x < 2 :
print('Small')
elif x < 10 :
print('Medium')
elif x < 20 :
print('Big')
elif x < 40 :
print('Large')
elif x < 100:
print('Huge')
else :
print('Ginormous')
Multi-way Puzzles
if x < 2 :
print('Below 2')
elif x < 20 :
print('Below 20')
elif x < 10 :
print('Below 10')
else :
print('Something else')
if x < 2 :
print('Below 2')
elif x >= 2 :
print('Two or more')
else :
print('Something else')
Which will never print
regardless of the value for x?
Summary
• Comparison operators
== <= >= > < !=
• Indentation
• One-way Decisions
• Two-way decisions:
if: and else:
• Nested Decisions
• Multi-way decisions using elif
Exercise
Rewrite your pay computation to give the
employee 1.5 times the hourly rate for hours
worked above 40 hours.
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15
Exercise
Rewrite your pay program using try and except so
that your program handles non-numeric input
gracefully.
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input
Enter Hours: forty
Error, please enter numeric input

More Related Content

PDF
03-Variables, Expressions and Statements (1).pdf
MirHazarKhan1
 
PPTX
Pythonlearn-02-Expressions123AdvanceLevel.pptx
AninditaSarkarNaha
 
PDF
python2oxhvoudhuSGFsughusgdogusuosFU.pdf
rohithzach
 
PPTX
Lec2_cont.pptx galgotias University questions
YashJain47002
 
PPT
PythonCourse_02_Expressions.ppt Python introduction turorial for beginner.
sakchaisengsui
 
PPTX
Intro to CS Lec03 (1).pptx
FamiDan
 
PDF
cel shading as PDF and Python description
MarcosLuis32
 
PPTX
unit1.pptx for python programming CSE department
rickyghoshiit
 
03-Variables, Expressions and Statements (1).pdf
MirHazarKhan1
 
Pythonlearn-02-Expressions123AdvanceLevel.pptx
AninditaSarkarNaha
 
python2oxhvoudhuSGFsughusgdogusuosFU.pdf
rohithzach
 
Lec2_cont.pptx galgotias University questions
YashJain47002
 
PythonCourse_02_Expressions.ppt Python introduction turorial for beginner.
sakchaisengsui
 
Intro to CS Lec03 (1).pptx
FamiDan
 
cel shading as PDF and Python description
MarcosLuis32
 
unit1.pptx for python programming CSE department
rickyghoshiit
 

Similar to PPT_1_9102501a-a7a1-493e-818f-cf699918bbf6.pptx (20)

PPTX
Introduction to Python Values, Variables Data Types Chapter 2
Raza Ul Mustafa
 
PPTX
An Introduction To Python - Python Midterm Review
Blue Elephant Consulting
 
PPTX
Python Lecture 2
Inzamam Baig
 
PPTX
Review old Pygame made using python programming.pptx
ithepacer
 
PPTX
03 Variables - Chang.pptx
Dileep804402
 
PDF
Introduction to Python
Mohammed Sikander
 
PPTX
unit1 python.pptx
TKSanthoshRao
 
PDF
1_Python Basics.pdf
MaheshGour5
 
PDF
PPE-Module-1.2 PPE-Module-1.2 PPE-Module-1.2.pdf
ArjayBalberan1
 
PPTX
MODULE. .pptx
Alpha337901
 
PDF
Variables in Python & Data Types and Their Values
Raza Ul Mustafa
 
PPTX
Lecture-2-Python-Basic-Elements-Sep04-2018.pptx
AbdulQadeerBilal
 
PPT
Input Statement.ppt
MuhammadJaved672061
 
PPTX
python fudmentalsYYour score increaseases
ssuser61d324
 
PPTX
PPt Revision of the basics of python1.pptx
tcsonline1222
 
PPTX
Python-Certification-Training-Day-1-2.pptx
muzammildev46gmailco
 
PPTX
Python Programming | JNTUK | UNIT 1 | Lecture 4
FabMinds
 
PPTX
An Introduction To Python - Variables, Math
Blue Elephant Consulting
 
PPTX
Lecture 1 .
SwatiHans10
 
PPTX
Python PPT2
Selvakanmani S
 
Introduction to Python Values, Variables Data Types Chapter 2
Raza Ul Mustafa
 
An Introduction To Python - Python Midterm Review
Blue Elephant Consulting
 
Python Lecture 2
Inzamam Baig
 
Review old Pygame made using python programming.pptx
ithepacer
 
03 Variables - Chang.pptx
Dileep804402
 
Introduction to Python
Mohammed Sikander
 
unit1 python.pptx
TKSanthoshRao
 
1_Python Basics.pdf
MaheshGour5
 
PPE-Module-1.2 PPE-Module-1.2 PPE-Module-1.2.pdf
ArjayBalberan1
 
MODULE. .pptx
Alpha337901
 
Variables in Python & Data Types and Their Values
Raza Ul Mustafa
 
Lecture-2-Python-Basic-Elements-Sep04-2018.pptx
AbdulQadeerBilal
 
Input Statement.ppt
MuhammadJaved672061
 
python fudmentalsYYour score increaseases
ssuser61d324
 
PPt Revision of the basics of python1.pptx
tcsonline1222
 
Python-Certification-Training-Day-1-2.pptx
muzammildev46gmailco
 
Python Programming | JNTUK | UNIT 1 | Lecture 4
FabMinds
 
An Introduction To Python - Variables, Math
Blue Elephant Consulting
 
Lecture 1 .
SwatiHans10
 
Python PPT2
Selvakanmani S
 
Ad

Recently uploaded (20)

PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
PPTX
Color Model in Textile ( RGB, CMYK).pptx
auladhossain191
 
PDF
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
PPT
Ppt for engineering students application on field effect
lakshmi.ec
 
PDF
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PPTX
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
PDF
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
PPTX
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPT
SCOPE_~1- technology of green house and poyhouse
bala464780
 
PDF
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
PDF
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
PPTX
AgentX UiPath Community Webinar series - Delhi
RohitRadhakrishnan8
 
PDF
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
PDF
Software Testing Tools - names and explanation
shruti533256
 
PDF
Principles of Food Science and Nutritions
Dr. Yogesh Kumar Kosariya
 
PDF
top-5-use-cases-for-splunk-security-analytics.pdf
yaghutialireza
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
Color Model in Textile ( RGB, CMYK).pptx
auladhossain191
 
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
Ppt for engineering students application on field effect
lakshmi.ec
 
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
SCOPE_~1- technology of green house and poyhouse
bala464780
 
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
AgentX UiPath Community Webinar series - Delhi
RohitRadhakrishnan8
 
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
Software Testing Tools - names and explanation
shruti533256
 
Principles of Food Science and Nutritions
Dr. Yogesh Kumar Kosariya
 
top-5-use-cases-for-splunk-security-analytics.pdf
yaghutialireza
 
Ad

PPT_1_9102501a-a7a1-493e-818f-cf699918bbf6.pptx

  • 2. C:usersHPpython Python 3.10.8 (tags/v3.10.8:aaaf517, Oct 11 2022, 16:50:30) [MSC v.1933 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> x = 1 >>> print(x) 1 >>> x = x + 1 >>> print(x) 2 >>> exit() This is a good test to make sure that you have Python correctly installed. Note that quit() also works to end the interactive session.
  • 3. Constants • Fixed values such as numbers, letters, and strings, are called “constants” because their value does not change • Numeric constants are as you expect • String constants use single quotes (') or double quotes (") >>> print(123) 123 >>> print(98.6) 98.6 >>> print('Hello world') Hello world
  • 4. 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
  • 5. 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 12.2 x 14 y x = 12.2 y = 14
  • 6. 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 12.2 x 14 y 100 x = 12.2 y = 14 x = 100
  • 7. 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
  • 8. Mnemonic Variable Names • Since we programmers are given a choice in how we choose our variable names, there is a bit of “best practice” • We name variables to help us remember what we intend to store in them (“mnemonic” = “memory aid”) • This can confuse beginning students because well-named variables often “sound” so good that they must be keywords http://en.wikipedia.org/wiki/Mnemonic
  • 9. Sentences or Lines x = 2 x = x + 2 print(x) Variable Operator Constant Function Assignment statement Assignment with expression Print statement
  • 10. 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 )
  • 11. x = 3.9 * x * ( 1 - x ) 0.6 x The right side is an expression. Once the expression is evaluated, the result is placed in (assigned to) x. 0.6 0.6 0.4 0.936 A variable is a memory location used to store a value (0.6)
  • 12. x = 3.9 * x * ( 1 - x ) 0.6 0.936 x 0.4 0.936 The right side is an expression. Once the expression is evaluated, the result is placed in (assigned to) the variable on the left side (i.e., x). A variable is a memory location used to store a value. The value stored in a variable can be updated by replacing the old value (0.6) with a new value (0.936). 0.6 0.6
  • 13. Numeric Expressions • Because of the lack of mathematical symbols on computer keyboards - we use “computer-speak” to express the classic math operations • Asterisk is multiplication • Exponentiation (raise to a power) looks different than in math Operator Operation + Addition - Subtraction * Multiplication / Division ** Power % Remainder
  • 14. >>> xx = 2 >>> xx = xx + 2 >>> print(xx) 4 >>> yy = 440 * 12 >>> print(yy) 5280 >>> zz = yy / 1000 >>> print(zz) 5.28 >>> jj = 23 >>> kk = jj % 5 >>> print(kk) 3 >>> print(4 ** 3) 64 Operator Operation + Addition - Subtraction * Multiplication / Division ** Power % Remainder 5 23 4 R 3 20 3 Numeric Expressions
  • 15. Order of Evaluation • When we string operators together - Python must know which one to do first • This is called “operator precedence” • Which operator “takes precedence” over the others? x = 1 + 2 * 3 - 4 / 5 ** 6
  • 16. Operator Precedence Rules Highest precedence rule to lowest precedence rule: Parentheses are always respected Exponentiation (raise to a power) Multiplication, Division, and Remainder Addition and Subtraction Left to right Parenthesis Power Multiplication Addition Left to Right
  • 17. 1 + 2 ** 3 / 4 * 5 1 + 8 / 4 * 5 1 + 2 * 5 1 + 10 11 >>> x = 1 + 2 ** 3 / 4 * 5 >>> print(x) 11.0 >>> Parenthesis Power Multiplication Addition Left to Right
  • 18. Operator Precedence • Remember the rules top to bottom • When writing code - use parentheses • When writing code - keep mathematical expressions simple enough that they are easy to understand • Break long series of mathematical operations up to make them more clear Parenthesis Power Multiplication Addition Left to Right
  • 19. What Does “Type” Mean? • In Python variables, literals, and constants have a “type” • Python knows the difference between an integer number and a string • For example “+” means “addition” if something is a number and “concatenate” if something is a string >>> ddd = 1 + 4 >>> print(ddd) 5 >>> eee = 'hello ' + 'there' >>> print(eee) hello there concatenate = put together
  • 20. Type Matters • Python knows what “type” everything is • Some operations are prohibited • You cannot “add 1” to a string • We can ask Python what type something is by using the type() function >>> eee = 'hello ' + 'there' >>> eee = eee + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: Can't convert 'int' object to str implicitly >>> type(eee) <class'str'> >>> type('hello') <class'str'> >>> type(1) <class'int'> >>>
  • 21. Several Types of Numbers • Numbers have two main types - Integers are whole numbers: -14, -2, 0, 1, 100, 401233 - Floating Point Numbers have decimal parts: -2.5 , 0.0, 98.6, 14.0 • There are other number types - they are variations on float and integer >>> xx = 1 >>> type (xx) <class 'int'> >>> temp = 98.6 >>> type(temp) <class'float'> >>> type(1) <class 'int'> >>> type(1.0) <class'float'> >>>
  • 22. Type Conversions • When you put an integer and floating point in an expression, the integer is implicitly converted to a float • You can control this with the built-in functions int() and float() >>> print(float(99) + 100) 199.0 >>> i = 42 >>> type(i) <class'int'> >>> f = float(i) >>> print(f) 42.0 >>> type(f) <class'float'> >>>
  • 23. Integer Division Integer division produces a floating point result >>> print(10 / 2) 5.0 >>> print(9 / 2) 4.5 >>> print(99 / 100) 0.99 >>> print(10.0 / 2.0) 5.0 >>> print(99.0 / 100.0) 0.99 This was different in Python 2.x
  • 24. String Conversions • You can also use int() and float() to convert between strings and integers • You will get an error if the string does not contain numeric characters >>> sval = '123' >>> type(sval) <class 'str'> >>> print(sval + 1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't convert 'int' object to str implicitly >>> ival = int(sval) >>> type(ival) <class 'int'> >>> print(ival + 1) 124 >>> nsv = 'hello bob' >>> niv = int(nsv) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'x'
  • 25. User Input • We can instruct Python to pause and read data from the user using the input() function • The input() function returns a string nam = input('Who are you? ') print('Welcome', nam) Who are you? Chuck Welcome Chuck
  • 26. Converting User Input • If we want to read a number from the user, we must convert it from a string to a number using a type conversion function • Later we will deal with bad input data inp = input('Europe floor?') usf = int(inp) + 1 print('US floor', usf) Europe floor? 0 US floor 1
  • 27. Comments in Python • Anything after a # is ignored by Python • Why comment? - Describe what is going to happen in a sequence of code - Document who wrote the code or other ancillary information - Turn off a line of code - perhaps temporarily
  • 28. # Get the name of the file and open it name = input('Enter file:') handle = open(name, 'r') # Count word frequency counts = dict() for line in handle: words = line.split() for word in words: counts[word] = counts.get(word,0) + 1 # Find the most common word bigcount = None bigword = None for word,count in counts.items(): if bigcount is None or count > bigcount: bigword = word bigcount = count # All done print(bigword, bigcount)
  • 29. Summary • Type • Reserved words • Variables (mnemonic) • Operators • Operator precedence • Integer Division • Conversion between types • User input • Comments (#)
  • 30. Exercise Write a program to prompt the user for hours and rate per hour to compute gross pay. Enter Hours: 35 Enter Rate: 2.75 Pay: 96.25
  • 31. Conditional Execution Chapter 3 Python for Everybody www.py4e.com
  • 32. Conditional Steps Output: Smaller Finis Program: x = 5 if x < 10: print('Smaller') if x > 20: print('Bigger') print('Finis') x = 5 x < 10 ? print('Smaller') x > 20 ? print('Bigger') print('Finis') Yes No Yes No
  • 33. Comparison Operators • Boolean expressions ask a question and produce a Yes or No result which we use to control program flow • Boolean expressions using comparison operators evaluate to True / False or Yes / No • Comparison operators look at variables but do not change the variables http://en.wikipedia.org/wiki/George_Boole Remember: “=” is used for assignment. Python Meaning < Less than <= Less than or Equal to == Equal to >= Greater than or Equal to > Greater than != Not equal
  • 34. Comparison Operators x = 5 if x == 5 : print('Equals 5') if x > 4 : print('Greater than 4') if x >= 5 : print('Greater than or Equals 5') if x < 6 : print('Less than 6') if x <= 5 : print('Less than or Equals 5') if x != 6 : print('Not equal 6') Equals 5 Greater than 4 Greater than or Equals 5 Less than 6 Less than or Equals 5 Not equal 6
  • 35. One-Way Decisions x = 5 print('Before 5') if x == 5 : print('Is 5') print('Is Still 5') print('Third 5') print('Afterwards 5') print('Before 6') if x == 6 : print('Is 6') print('Is Still 6') print('Third 6') print('Afterwards 6') Before 5 Is 5 Is Still 5 Third 5 Afterwards 5 Before 6 Afterwards 6 x == 5 ? Yes print('Still 5') print('Third 5') No print('Is 5’)
  • 36. Indentation • Increase indent indent after an if statement or for statement (after : ) • Maintain indent to indicate the scope of the block (which lines are affected by the if/for) • Reduce indent back to the level of the if statement or for statement to indicate the end of the block • Blank lines are ignored - they do not affect indentation • Comments on a line by themselves are ignored with regard to indentation
  • 37. Warning: Turn Off Tabs!! Atom automatically uses spaces for files with ".py" extension (nice!) • Most text editors can turn tabs into spaces - make sure to enable this feature - NotePad++: Settings -> Preferences -> Language Menu/Tab Settings - TextWrangler: TextWrangler -> Preferences -> Editor Defaults • Python cares a *lot* about how far a line is indented. If you mix tabs and spaces, you may get “indentation errors” even if everything looks fine
  • 38. This will save you much unnecessary pain.
  • 39. x = 5 if x > 2 : print('Bigger than 2') print('Still bigger') print('Done with 2') for i in range(5) : print(i) if i > 2 : print('Bigger than 2') print('Done with i', i) print('All Done') increase / maintain after if or for decrease to indicate end of block
  • 40. x = 5 if x > 2 : print('Bigger than 2') print('Still bigger') print('Done with 2') for i in range(5) : print(i) if i > 2 : print('Bigger than 2') print('Done with i', i) print('All Done') Think About begin/end Blocks
  • 41. x = 42 if x > 1 : print('More than one') if x < 100 : print('Less than 100') print('All done') Nested Decisions x > 1 print('More than one’) x < 100 print('Less than 100') print('All Done') yes yes no no
  • 42. Two-way Decisions • Sometimes we want to do one thing if a logical expression is true and something else if the expression is false • It is like a fork in the road - we must choose one or the other path but not both x > 2 print('Bigger') yes no x = 4 print('Not bigger') print('All Done')
  • 43. Two-way Decisions with else: x > 2 print('Bigger') yes no x = 4 print('All Done') x = 4 if x > 2 : print('Bigger') else : print('Smaller') print('All done') print('Not bigger')
  • 44. Visualize Blocks x = 4 if x > 2 : print('Bigger') else : print('Smaller') print('All done') x > 2 print('Bigger') yes no x = 4 print('All Done') print('Not bigger')
  • 46. Multi-way if x < 2 : print('small') elif x < 10 : print('Medium') else : print('LARGE') print('All done') x < 2 print('small') yes no print('All Done') x < 10 print('Medium') yes print('LARGE') no
  • 47. Multi-way x = 0 if x < 2 : print('small') elif x < 10 : print('Medium') else : print('LARGE') print('All done') x < 2 print('small') yes no print('All Done') x < 10 print('Medium') yes print('LARGE') no x = 0
  • 48. Multi-way x = 5 if x < 2 : print('small') elif x < 10 : print('Medium') else : print('LARGE') print('All done') x < 2 print('small') yes no print('All Done') x < 10 print('Medium') yes print('LARGE') no x = 5
  • 49. Multi-way x = 20 if x < 2 : print('small') elif x < 10 : print('Medium') else : print('LARGE') print('All done') x < 2 print('small') yes no print('All Done') x < 10 print('Medium') yes print('LARGE') no x = 20
  • 50. Multi-way # No Else x = 5 if x < 2 : print('Small') elif x < 10 : print('Medium') print('All done') if x < 2 : print('Small') elif x < 10 : print('Medium') elif x < 20 : print('Big') elif x < 40 : print('Large') elif x < 100: print('Huge') else : print('Ginormous')
  • 51. Multi-way Puzzles if x < 2 : print('Below 2') elif x < 20 : print('Below 20') elif x < 10 : print('Below 10') else : print('Something else') if x < 2 : print('Below 2') elif x >= 2 : print('Two or more') else : print('Something else') Which will never print regardless of the value for x?
  • 52. Summary • Comparison operators == <= >= > < != • Indentation • One-way Decisions • Two-way decisions: if: and else: • Nested Decisions • Multi-way decisions using elif
  • 53. Exercise Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours. Enter Hours: 45 Enter Rate: 10 Pay: 475.0 475 = 40 * 10 + 5 * 15
  • 54. Exercise Rewrite your pay program using try and except so that your program handles non-numeric input gracefully. Enter Hours: 20 Enter Rate: nine Error, please enter numeric input Enter Hours: forty Error, please enter numeric input

Editor's Notes

  • #31: Note from Chuck. If you are using these materials, you can remove the UM logo and replace it with your own, but please retain the CC-BY logo on the first page as well as retain the acknowledgement page(s).