Intro Notes

advertisement
Intro. to Python Programming
Programming - The process




Understand the problem and requirements
Design or select an algorithm to solve it
Express (code) the algorithm in a programming language (e.g., C, Python)
Test and debug the program until it works and meets the requirements
Hats I will wear this semester
You
Me/TAs
Python as an Interpreted Programming
 Was developed by Guido van Rossum in 1990
 Is specifically designed for programmers
o readability and ease of use are more important than efficiency
o why it's used first in intro programming courses
 Readability and ease of use are more important than efficiency
 command line interface
Example Command Line interface
1
 Python is interpreted
o the code is saved in the same format that you entered but interpreted
programs must be reduced to machine instructions at runtime.
How Python is Converted into a running program
I know, it's Java, but same thing!!
Compare that to C/C++
2
Learning the setup of a program
 the setup is the same for many of your programs
 the setup must be in the SAME order as shown as below
Setup Example
Name of File
Place your name here
Date
Section
Email
Description of
program
Code from here down
Place all imports here
(none)
**Where most of your
code goes!! (here
down) and your
program really
begins!!**
calls the main!!
Important!!
Import
Description of Setup
Some commands and features require other "packages or
libraries"
3
Data types in General
Type
int
float
double
char
Boolean
String
Examples/Definitions
yards = 202
a WHOLE number, ranging from -2147483647 to 2147483647
GPA = 3.99
a real number in a floating point representation
mole = 1.2336483
a double-precision real number in a floating point representation
choice = 'x'
ONE character, or a small INTEGER in the range from -128 to 127
found = True
a Boolean value can either AND ONLY be true(1) or false(0)
name = "Mr. Lupoli"
Holds a number of character together
4
Input and Output
I/O stream
ke
y
b
oa
rd

stream

score = int(input("Enter score"))
name = input("Enter name")
Computer
print(score)
Printing a Line of Text
Print Example
#
#
#
#
#
#
#
File:
printing.py
Author: Mr. Lupoli
Date:
9/22/09
Section: all
E-mail: slupoli@cs.umbc.edu
Description:
This file shows different examples of printing
def main():
print("Hello Class, ")
print("I am Mr. Lupoli" , end = ' ')
# what is the difference between a line that ends with a ' '
print("We will learn PYTHON!!")
# , == Java's "+" in Python
main()
Draw a sizeable square on your paper. If it was a monitor what would the code
above look like on it.
Use the code above to display YOUR name on line ONE, and your town and state on
line TWO
5
Using print with variables
x=0
# MUST DECLARE ALL VARIABLE BEFORE USING
y=8
sum = x + y
print("X is: " , x , " and Y is: " , y ) # ‘,’ will put a space BEFORE and AFTER it
print("sum = ", sum)
literal escape constants/command constants
Python Escape Sequences
Escape
Sequence
\t
\r
\\
\"
\'
\n
\b
\f
Description
tab
carriage return, go to beginning of next line
backslash
double quote
single quote
new line
back space
form feed
What will these statements below display??
print("Hi Class!")
print("Good Luck!!! \n")
print("\t \t You'll need it!!!")
6
Introduction to the Input from a Keyboard
 Two different "commands" to retrieve depending on the data from the user
o numeric
o characters and strings
 characters = 1 letter
 strings = 2 or more letters together, can have spaces as well
 just remember Python does not have chars (but Java does)
 commands must place the value entered into a variable
 whatever is placed inside the " " is displayed to the screen
Code for reading in data from the Keyboard
Numeric
String
value = int(input("Please enter your score"))
valueFloat = float(input("Please enter…"))
value = input("Please enter your name")
3
2
1
Any code with an "=" (equals sign) is completed right to left!!!
Which method would you use to get input?
Lupoli
98
Prof. Lupoli
123.012
Lupoli needs a vacation
123-234-2344
String/Numeric
String/Numeric
String/Numeric
String/Numeric
String/Numeric
String/Numeric
REMEMBER WE HAVE NO IDEA WHAT VALUE THE USER WILL
ENTER!!!
7
First Input Example
#
#
#
#
#
#
#
File:
input.py
Author: Mr. Lupoli
Date:
8/10/11
Section: all
E-mail: slupoli@cs.umbc.edu
Description:
This file accepts values for dog years
def main():
# set a DEFAULT value, personal preference
age = -1
print("How old are you?")
#get input from keyboard (user)
age = int(input("Enter the number here: ") )
# calculate value
dogAge = age * 7
#
print results
print("You are " , dogAge, " years old in DOG YEARS")
main ()
1.
2.
3.
4.
Identify where the comments are located
Identify where the input command is located
Identify type of data (String, Numeric) is being read in
Identify where the output is taking place
Inputting Number
Inputting Decimal
Inputting String
hitting enter
Breaks the program!!
Why did entering a String and Double/Float break the program??
8
Input/Output Exercise
#
#
#
#
#
#
#
#
File:
inputOutputHW.py
Author: your name here
Date:
the date here
Section: all
E-mail: your email here
Description:
This program is used to show printing, file setup
and input from the keyboard
def main():
#default value set to blank
#use these variables below for your code
name = ""
address = ""
# 1.) Create the CODE to say hello and say what the program
# is doing(called a greeting) (No variables yet.)
# 2.) Create the CODE to LITERALLY display YOUR name, and
# address (No variables yet.)
# 3.) Create the CODE to ask for user's name and address,
USE # THE VARIABLES DECLARED FOR # YOU ALREADY!! Hint: Which
# input functions will you need?
# 4.) Create the code to display their name and address that
# THEY type in. NOT yours!!
main()
Submit your code using BB. Check under "Exercises" in this week's notes.
9
Use of Comments
#
#
#
#
#
#
#
#
#
File:
comment.py
Author: Mr. Lupoli
Date:
9/22/09
Section: all
E-mail: slupoli@cs.umbc.edu
Description:
This file shows different examples
of commenting
""" … code … """
"""
File:
comment.py
Author: Mr. Lupoli
Date:
9/22/09
Section: all
E-mail: slupoli@cs.umbc.edu
Description:
This file shows different examples
of commenting
"""
#  "#" reserves REST of line for
a # comment
"""
# used for ONE line comments
" """ " reserves whole block until
you end it with a " """ "
used for MULTIPLE lined comments
"""
counterValue # sentinel value
 """ has issues!!
o must be indented, and follow the indention of the code it covers
o also, if you want to comment out a block already using """, it will
"uncover" those already inside
Issues With Triple Quotes
def getInput():
flag = True
'''
while(flag):
#try:
line = input("Please enter in the equation: ")
print(line
'''
1. Check for words (e.g. hello) or expressions that are not
this input."
'''
10
Why use comments?
 For notes
o to yourself
o to me!!
 For commenting out unfinished lines of code
o skipping unfinished functions
 To understand what the code is doing!!
 watch where you put them!!
Reserved Words
 case sensitive
 can not be used as variable or function names
 many we will cover
Some reserved words/commands
11
"Codewriting" (kinda like Handwriting)
 indentation counts!!!
 must be in a straight line
 there will be some examples that indent farther
o if/elses (covered later)
Style example
# header comments here
def main():
#greeting
print("This program tests if statements")
print("By:
YOU")
print("Will I do my work in Mr. Lupoli's Class??")
# have user press "Y") or "N")
user = input("…")) # reads what user typed
# will pass
if(user == 'Y')
print("Then I will pass PYTHON, and take Java next
semester!")
# ONE LINE
# will fail
if(user == 'N')
print("Then I will not pass Mr. Lupoli's class.")
print("And my parents will be upset!")
# TWO LINES OR MORE
main()
12
Examples of Codewriting #1
Will work
#
#
#
#
#
#
#
#
File:
printing.py
Author: Mr. Lupoli
Date:
8/1/10
Section: all
E-mail: slupoli@cs.umbc.edu
Description:
This file shows how code must be
positioned correctly
def main():
print("Hello Class, ")
print("I am Mr. Lupoli", )
print("We will learn PYTHON!!")
print("****************************")
main()
Will not work
#
#
#
#
#
#
#
#
File:
printing.py
Author: Mr. Lupoli
Date:
8/1/10
Section: all
E-mail: slupoli@cs.umbc.edu
Description:
This file shows how code must be
positioned correctly
def main():
print("Hello Class, ")
print("I am Mr. Lupoli", )
print("We will learn PYTHON!!")
print("**************************")
main()
13
Examples of Codewriting #2
#
#
#
#
#
#
#
File:
ifElseExample.py
Author: Mr. Lupoli
Date:
8/1/10
Section: all
E-mail: slupoli@cs.umbc.edu
Description:
This file shows how code must be positioned correctly with indenting
def main():
#gather user input
speed = input("So how bad is it to live in Florida?? ")
if (speed < 0):
print("Invalid!! Try again")
#1 . Minimum
74 - 95 mph
elif (speed < 96):
print("Minimum")
#2 . Moderate 96 - 110 mph
elif (speed < 111):
print("Moderate")
#3 . Extensive 111 - 130 mph
elif (speed < 131):
print("Extensive")
#4 . Extreme
131 - 155 mph
elif (speed < 156):
print("Extreme")
#5 - Catastrophic
greater than 155 mph
else:
print("just forget about it!! It's gone!!!")
main()
Python Tutorials
 I encourage you to find other resources out there for help!!
o tell me about them and I can put them up!
 since 75% of us are visual learners, a colleague found this:
o http://www.pythontutor.com/visualize.html
o http://www.codecademy.com/learn
14
Answers
Input/Output exercise
#
#
#
#
#
#
#
File:
printing.py
Author: Mr. Lupoli
Date:
9/22/09
Section: all
E-mail: slupoli@cs.umbc.edu
Description:
This file shows different examples of printing
def main():
#default value set to blank
#use these variables below for your code
name = ""
address = ""
#1
print("Hello. This is our first input/output exercise")
#2
print("Shawn Lupoli, 8823 Expresso Way, Baltimore, MD 12383")
#3
name = input("Please enter your name: ")
address = input("Please enter your address: ")
#4
print(name)
print(address)
print(name, " ", address)
main()
Sources:
http://www.csee.umbc.edu/courses/201/spring12/lectures/intro_1.html#%281%29
Patti Ordonez, Sue Evans (UMBC) and Lisa Meeden (Swarthmore)
15
Download