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

CH 2

The document discusses Python programming concepts including basic input/output, data types, arithmetic operators, decision making statements, functions, and memory concepts. It provides examples of Python code and explanations.

Uploaded by

Yousef Al-Ashqar
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

CH 2

The document discusses Python programming concepts including basic input/output, data types, arithmetic operators, decision making statements, functions, and memory concepts. It provides examples of Python code and explanations.

Uploaded by

Yousef Al-Ashqar
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 35

CSCI/CMPE 4341 Topic:

Programming in Python
Chapter 2: Basic Concepts in Python
Programming
Xiang Lian
The University of Texas – Pan American
Edinburg, TX 78539
[email protected]
Objectives
• In this chapter, you will
– Understand a typical Python program-development
environment
– Write simple input and output computer programs
in Python
– Become familiar with fundamental data types
– Use arithmetic operators and their precedence in
Python
– Write simple decision-making statements
2
Last Chapter: Python IDE

Python 3.4 Command Line

3
Python 3.4 GUI
Visual Programming
# Fig. 10.4: fig10_04.py
# Label demonstration.

from Tkinter import *

class LabelDemo( Frame ):


"""Demonstrate Labels"""

def __init__( self ):


"""Create three Labels and pack them"""

Frame.__init__( self ) # initializes Frame instance

# frame fills all available space


self.pack( expand = YES, fill = BOTH )
self.master.title( "Labels" )

self.Label1 = Label( self, text = "Label with text" )

# resize frame to accommodate Label


self.Label1.pack()

self.Label2 = Label( self,


text = "Labels with text and a bitmap" )

# insert Label against left side of frame


self.Label2.pack( side = LEFT )

# using default bitmap image as label


self.Label3 = Label( self, bitmap = "warning" )
self.Label3.pack( side = LEFT )

def main():
LabelDemo().mainloop() # starts event loop

if __name__ == "__main__":
main()

4
Introduction
• Introduction to Python programming
• Introduction to programming techniques
– Structured programming
– Object-oriented programming

5
Hello Program
# Fig. 2.1: fig02_01.py
# Printing a line of text in Python.

print ("Welcome to Python Programming Class!")

Note: parentheses are


needed for Python 3.4.X, but
not necessary for Python
2.2.X (used in Textbook)
# Results:
# Welcome to Python Programming Class!

6
First Program in Python: Printing a
Line of Text
• Python "//" or "/* … */" is used in C/C++/Java
– The # symbol
• Used to denote a single line comment
• "printf" or "cout" is used in C/C++
– The print function • "System.out.println(...)" in Java
• Used to send a stream of text to be output to the user
• Executing
– Saving as a file
• Type code into a .py file and save it
• To run it type python fileName.py
– Executing code
• Type python in the command line
• Runs the python interpreter
7
Print a Line with Multiple
Statements
# Fig. 2.2: fig02_02.py
# Printing a line with multiple statements.
comma
print ("Welcome",
"to Python Programming Class!")

# Results:
# Welcome to Python Programming Class!
8
Special Characters in the String
• Escape characters
– Used to perform a different task that normally
intended
– \n – insert a new line
– \" – insert double quotes
– \' – insert a single quote
– \\ – inserts a backslash

9
Examples of Escape Characters
Escape Description
Sequence
\n Newline. Move the screen cursor to the beginning of
the next line.
\t Horizontal tab. Move the screen cursor to the next tab
stop.
\r Carriage return. Move the screen cursor to the
beginning of the current line; do not advance to the
next line.
\b Backspace. Move the screen cursor back one space.
\a Alert. Sound the system bell.
\\ Backslash. Print a backslash character.
\" Double quote. Print a double quote character.
\' Single quote. Print a single quote character.

10
Another Program: Adding Integers
"cin" is used in C++
• Functions Note: raw_input() is used
in the Textbook for version
– The input function 2.2.X, but not for 3.4.X
• Used to retrieve data from the user
– The int function Different from int in C/C++/Java
• Used to convert strings to integers

11
Outline

# Fig. 2.7: fig02_07.py


# Simple addition program.

# prompt user for input


integer1 = input( "Enter first integer:\n" ) # read string
integer1 = int( integer1 ) # convert string to integer
Prompts the user to
Fig02_07.py
enter and integer value
integer2 = input( "Enter second integer:\n" ) # read string
integer2 = int( integer2 ) # convert string to integer

sum = integer1 + integer2 # compute and assign sum


Converts the string value
into an integer value
print ("Sum is", sum) # print sum

Adds up and then prints out


Enter first integer: the sum of the two numbers
45
Enter second integer: Program Output
72

Sum is 117

 2002 Prentice Hall.


All rights reserved.
13

Variant of the Program: Adding Integers


(Output)

# Result:
Enter first integer:
2
Enter second integer:
4
24

 2002 Prentice Hall. All rights reserved.


14

Memory Concepts
• Variable names correspond to Python objects
– E.g., integer1, integer2
– integer1 = input( "Enter first integer:\n" )
• Objects
– Every object has a type, size, value, and location
• Stored in computers memory
• Type and location cannot be changed
– When a variable is made the name is binded to the value
– Values are not modified as a computer performs the
calculation

 2002 Prentice Hall. All rights reserved.


15

Memory Concepts (cont'd)


>>> integer1 = input( "Enter first integer:\n" )
Enter first integer:
45
integer1 "45"

Fig. 2.9 Memory location showing value of a variable and the name bound to the value.

>>> integer1 = int (integer1)


New memory
"45" location
integer1 45

Fig. 2.10 Memory location showing the name and value of a variable.

 2002 Prentice Hall. All rights reserved.


16

Memory Concepts (cont'd)

integer1 45

integer2 72

Fig. 2.11 Memory locations after values for two variables have been input.

>>> sum = integer1 + integer2

integer1 45

integer2 72

sum 117

Fig. 2.12 Memory locations after a calculation.

 2002 Prentice Hall. All rights reserved.


More Functions in Python

• Functions
– The input function
• Used to retrieve data from the user
– The int function
• Used to convert strings to integers
– The id(…) function
• Used to return the interpreter’s representation of the
variable’s location
– The type(…) function
• Used to return the type of the variable
17
# Fig. 2.13: fig02_13.py Outline
# Displaying an object's location, type and value.

# prompt the user for input


integer1 = input( "Enter first integer:\n" ) # read a string Fig02_13.py
print ("integer1: ", id( integer1 ), type( integer1 ), integer1)
integer1 = int( integer1 ) # convert the string to an integer
print ("integer1: ", id( integer1 ), type( integer1 ), integer1)
Prints the id, type and
integer2 = input( "Enter second integer:\n" ) # read a string value before and after
print ("integer2: ", id( integer2 ), type( integer2 ), integer2)
integer2 = int( integer2 ) # convert the string to an integer
the variable is converted
print ("integer2: ", id( integer2 ), type( integer2 ), integer2) into an integer
sum = integer1 + integer2 # assignment of sum
print ("sum: ", id( sum ), type( sum ), sum)
Notice in the output that
Enter first integer:
after the conversion the
Program
value is the Output
same but the
5
type and id have changed
integer1: 7956744 <type 'str'> 5
integer1: 7637688 <type 'int'> 5
Enter second integer:
27
integer2: 7776368 <type 'str'> 27
integer2: 7637352 <type 'int'> 27
sum: 7637436 <type 'int'> 32

 2002 Prentice Hall.


All rights reserved.
Arithmetic Operators
• Symbols
– * # multiply
– / # divide
– % # modulus
– ** # exponential
– // # floor division
• Order
– Operators are done in order of parenthesis, exponents,
multiply and divide (left to right), and lastly add and
subtract (left to right)
19
Arithmetic Operators (cont'd)
Python Arithmetic Algebraic Python
operation operator expression expression
Addition + f+7 f+7
Subtraction – p–c p-c
Multiplication * bm b*m
Exponentiation ** xy x ** y

Division / x / y or x ÷y x/y
// x // y
Modulus % r mod s r%s
Fig. 2.14 Arithmetic operators.

20
Example of Arithmetic
# test arithmetic

x=2
y=3

print("x^y=\b", x**y)

print("x/y=\b", x/y)

print("x//y=\b", x//y)

21
Examples of (Floor) Division
Python 3.4 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 3.0 // 4.0 # floating-point floor division
0.0
>>> 3 / 4 # true division (new behavior)
0.75
>>> 3.0 / 4.0 # true division (same as before)
0.75

22
Precedence of Arithmetic Operators
Operator(s) Operation(s) Order of Evaluation (Precedence)
( ) Parentheses Evaluated first. If the parentheses are
nested, the expression in the innermost
pair is evaluated first. If there are
several pairs of parentheses “on the
same level” (i.e., not nested), they are
evaluated left to right.
** Exponentiatio Evaluated second. If there are several,
n they are evaluated right to left.
* / // % Multiplication Evaluated third. If there are several,
Division they are evaluated left to right. [Note:
Modulus The // operator is new in version 2.2]
+ - Addition Evaluated last. If there are several, they
Subtraction are evaluated left to right.
Fig. 2.16 Precedence of arithmetic operators.

23
An Example of Arithmetic
Step 1.
Expression
y = 2 * 5 ** 2 + 3 * 5 + 7
5 ** 2 = 25 Exponentiation
Step 2.
y = 2 * 25 + 3 * 5 + 7
2 * 25 = 50 Leftmost multiplication
Step 3.
y = 50 + 3 * 5 + 7
3 * 5 = 15 Multiplication before addition
Step 4.
y = 50 + 15 + 7
50 + 15 = 65 Leftmost addition

Step 5.
y = 65 + 7 is 72 Last edition

Step 6.
y = 72 Python assigns 72 to y
24
Fig. 2.17 Order in which a second-degree polynomial is evaluated.
String Formatting
• Strings
– Unlike other languages strings are a built-in data type
• Allows for easy string manipulation
– Double quote strings
• Single quotes need not be escaped
– Single quote strings
• Double quotes need not be escaped
– Triple quoted strings
• Do not need any escape sequence
• Used for large blocks of text
25
# Fig. 2.18: fig02_18.py Strings in single quotes need Outline
# Creating strings and using quote characters innot have double quotes escaped
strings.

print ("This is a string with \"double quotes.\"") Strings with double quotes
Fig02_18
print ('This is another string with "double quotes."')
print ('This is a string with \'single quotes.\'')
need not escape single quotes
print ("This is another string with 'single quotes.'")
print ("""This string has "double quotes" and 'single quotes'.
You can even do multiple lines.""")
print ('''This string also has "double" and 'single' quotes.''')

This is a string with "double quotes."


Program
Strings in triple quotes do Output
This is another string with "double quotes."
not have to escape anything
This is a string with 'single quotes.'
and can span many lines
This is another string with 'single quotes.'
This string has "double quotes" and 'single quotes'.
You can even do multiple lines.
This string also has "double" and 'single' quotes.

 2002 Prentice Hall.


All rights reserved.
String Formatting
Conversion Specifier Meaning
Symbol
c Single character (i.e., a string of length one) or the
integer representation of an ASCII character.

s String or a value to be converted to a string.


d Signed decimal integer.

u Unsigned decimal integer.


o Unsigned octal integer.
x Unsigned hexadecimal integer (with hexadecimal digits
a through f in lowercase letters).
X Unsigned hexadecimal integer (with hexadecimal digits
A through F in uppercase letters).
f Floating-point number.
e, E Floating-point number (using scientific notation).
g, G Floating-point number (using least-significant digits).
Fig. 2.20 String-formatting characters.
27
# Fig. 2.19: fig02_19.py Outline
# String formatting.

integerValue = 4237
print ("Integer ", integerValue) Fig02_19.py
print ("Decimal integer %d" % integerValue)
print ("Hexadecimal integer %x\n" % integerValue)

floatValue = 123456.789 The %e is used to format the string


print ("Float", floatValue) to scientific notation number
print ("Default float %f" % floatValue ) Formats the string to contain exactly
print ("Default exponential %e\n" % floatValue ) a specified amount of letters
print ("Right justify integer (%8d)" % integerValue)
print ("Left justify integer (%-8d)\n" % integerValue )

stringValue = "String formatting"


print ("Force eight digits in integer %.8d" % integerValue )
print ("Five digits after decimal in float %.5f" % floatValue )
print ("Fifteen and five characters allowed in string:" )
print ("(%.15s) (%.5s)" % ( stringValue, stringValue ) )

Formats the string to only


allow so many characters

 2002 Prentice Hall.


All rights reserved.
Decision Making: Equality and
Relational Operators
• The if structure
– Can be formed with equality and relational
operators
• <, >, ==, …

29
Decision Making: Equality and
Relational Operators (cont'd)
Standard algebraic Python equality Example Meaning of
equality operator or or relational of Python Python condition
relational operator operator condition
Relational
operators
> > x>y x is greater than y
< < x<y x is less than y
≥ >= x >= y x is greater than or
equal to y
≤ <= x <= y x is less than or equal
to y
Equality
operators
= == x == y x is equal to y
≠ !=, <> x != y, x is not equal to y
x <> y
Fig. 2.21 Equality and relational operators. 30
Common Syntax Errors
• Spaces between pairs of symbols below
– = =, ! =, < =, > =
• Reversing the order
– =!, ><, =>, =<
• == vs. =

31
32
# Fig. 2.22: fig02_22.py Outline
# Compare integers using if structures, relational operators
# and equality operators.

print ( "Enter two integers, and I will tell you " ) Fig02_22.py
print ( "the relationships they satisfy." )

# read first string and convert to integer


number1 = input( "Please enter first integer: " )
number1 = int( number1 ) Gets two values from the user
# read second string and convert to integer and converts them to strings
number2 = input( "Please enter second integer: " )
number2 = int( number2 )

if number1 == number2:
print ("%d is equal to %d" % ( number1, number2 ))
if number1 != number2:
print ("%d is not equal to %d" % ( number1, number2 ))

if number1 < number2: Checks each of the rational


print ("%d is less than %d" % ( number1, number2 ))
operators or the numbers
if number1 > number2: using if statements
print ("%d is greater than %d" % ( number1, number2 ))

if number1 <= number2:


print ("%d is less than or equal to %d" % (number1, number2 ))

if number1 >= number2:


print ("%d is greater than or equal to %d" % (number1,
number2))

 2002 Prentice Hall.


All rights reserved.
33
Enter two integers, and I will tell you
Outline
the relationships they satisfy.
Please enter first integer: 37
Please enter second integer: 42
Fig02_22.py
Program Output
37 is not equal to 42
37 is less than 42
37 is less than or equal to 42

Enter two integers, and I will tell you


the relationships they satisfy.
Please enter first integer: 7
Please enter second integer: 7
7 is equal to 7
7 is less than or equal to 7
7 is greater than or equal to 7

Enter two integers, and I will tell you


the relationships they satisfy.
Please enter first integer: 54
Please enter second integer: 17
54 is not equal to 17
54 is greater than 17
54 is greater than or equal to 17
 2002 Prentice Hall.
All rights reserved.
if Statement
colon
if number1 == number2:
print ("%d is equal to %d" % ( number1, number2 ))

Indented with tab,


compared with { } in
C/C++/C#/Java

•In Python, if the statement is too long, then it can be spread


over multiple lines using the line continuation character "\"
– print ("Hello \
World")

34
35

You might also like