You are on page 1of 41

Lecture 3

 Becoming Familiar with Python Programming


Environment
 Python Interpreter
 Comments
 Variables
 Assignment Statements

 Data Types
 Constants
 Input and Output Variables

2
 There are different ways to run Python codes
 E.g., if we want to display greeting message “Hello

World !”, we can either:


A. Simple text editor as Notepad
B. Python Shell
C. IDLE, comes with official python installation
D. Any of integrated development environment, as Pycharm
or Spyder or … etc

3
When displaying a greeting message “Hello World !”
through:
A. Simple text editor as Notepad
Open Notepad or any text editor
Write down the following statement
print("Hello World !")
Save file as "greeting.py“
Open cmd and goto the directory that contains the file
Then type python greeting.py then press Enter

4
When displaying a greeting message “Hello World !”
through: Python prompt >>> indicating that Python is
B. Python Shell ready for us to give it a command. These
commands are called statements.
Open cmd and type python

>>> Python prompt

Write down the following statement


print("Hello World !")
Press Enter
Note: to close python shell, type exit( )

5
When displaying a greeting message “Hello World !”
through:
C. IDLE, (writing codes directly through python shell)
Open IDLE (type IDLE in Run)
Write the following statement
print("Hello World !")
Press Enter

6
When displaying a greeting message “Hello World !”
through:
C. IDLE, (write down py files & run it through IDLE)
Open IDLE (type IDLE in Run)
Click on File then New File (or Ctrl + N)
Write the following statement
print("Hello World !")
Click on Run then Run Module (or press F5)

7
When displaying a greeting message “Hello World !”
through:
D. Any of integrated development environment, as Pycharm

8
When displaying a greeting message “Hello World !”
through:
D. Any of integrated development environment, as Spyder

9
 Python program contains one or more lines of
instructions or statements that will be translated and
executed by the Python interpreter.
 The compiler reads the file containing source code
(Python instructions), and translates instructions into byte
code.
 Byte codes are very simple instructions understood by the
virtual machine, a separate program that is similar to the
CPU of a computer.
 After the compiler has translated your program into
virtual machine instructions, they are executed by the
virtual machine.

10
Source code doesn’t contain all the information that the virtual machine
needs. E.g. it does not contain the implementation of the print function.
The virtual machine locates functions such as print in library modules.

Python Interpreter
11
 Comments begin with # and are not statements. They
provide descriptive information to the programmer.
# My first Python program.
 It is a good practice to provide comments. This helps
programmers who read your code understand your
intent.
 Comments are helpful when you review your own
programs. Providing a comment at the top of your source
file is essential to explains the purpose of the program.
##
# This program computes the area of a circle
#

12
 A function is a collection of programming instructions
that carry out a particular task.
print("Hello, World!")
 This is build-in function, part of Python. It calls function

named print and pass it the information Hello, World


to be displayed on the screen.
 To use / call, a function in Python, we need to specify:

 The name of the function (in this case, print).


 Any values the function needs to carry out its task (in
this case, "Hello, World!").

13
 It in a Python program, variables are used to store values.
 A variable is a storage location in a computer program.
Each variable has a name and holds a value
 A variable is similar to a parking space in a parking
garage. The parking space has an identifier (as “J 053”),
and it can hold a vehicle. A variable has a name (such as
cansPerPack), and it can hold a value (such as 6).

14
Variable Names
 A variable is defined when you give it a name that

explains its purpose.


 Variable Name must follow a few simple rules:

 Names must start with a letter or the underscore (_) character, and
the remaining characters must be letters, numbers, or underscores
 Cannot use other symbols such as ? or %.
 Spaces are not permitted inside names either.
 Names are case sensitive, that is, canVolume and
canvolume are different names.
 You cannot use reserved words such as if or class as
names; these words are reserved exclusively for their
special Python meanings

15
16
 Can use uppercase letters to denote word boundaries,
as in cansPerPack. This naming convention is called
camel case because the uppercase letters in the middle
of the name look like the humps of a camel.
You should also respect.
 It is better to use a descriptive name, such as cansPerPack, than a

clipped (or short name), such as cpp.


 Most Python programmers use names for variables that start with a

lowercase letter (such as cansPerPack).


 In contrast, names that are all uppercase (such as CAN_VOLUME)

indicate constants.
 Names that start with an uppercase letter are commonly used for

user-defined data types (such as GraphicsWindow).

17
 The left-hand side of an assignment statement consists
of a variable.
 The right-hand side is an expression that has a value.
That value is stored in the variable.
 Example: cansPerPack = 6 here a variable name
canPerPack will be equal to 6 after running this
assignment statement
 The first time a variable is assigned a value, the variable
is created and initialized with that value.
 The = sign does not mean that left-hand side is equal to
the right-hand side. Instead, the value on the right-hand
side is placed into the variable on the left.

18
 After a variable has been defined, it can be used in other
statements. E.g., print(cansPerPack)
 It will print the value stored in the variable cansPerPack
 If an existing variable is assigned a new value, that value
replaces the previous contents of the variable. Example:
cansPerPack = 8

19
 Consider this example:
cansPerPack = cansPerPack + 2
 This statement means to look up the value stored in the
variable cansPerPack, add 2 to it, and place the result
back into cansPerPack.

20
Assignment Statement for multiple variables:

a, b, c = 5, 3.2, "Hello“
>>> a
5
>>> b
3.2
>>> c
'Hello'
>>>

21
 Computers manipulate data values that represent
information and these values can be of different types.
 Each value in a Python program is of a specific type.
 The data type of a value determines how:
 The data is represented in the computer
 What operations can be performed on that data.

 A data type provided by the language itself is called a


primitive data type.

22
 Python supports quite a few data types:
Numbers
Strings
Files
Containers
and many others.
 Programmers can also define their own user-defined data
types.

23
Integer Data Type (wrote as int in Python)
 Represents an integral value without a fractional part.

 For example, there must be an integer number of cans in

any pack of cans—you cannot have a fraction of a can.

Floating Data Type (wrote as float in Python)


 Represents a fractional part is required.

 For example, number 0.355 is a floating number.

String Data Type (wrote as str in Python)


 A sequence of characters enclosed in quotation marks

“Hello, World!” is called a string. The message has to be


enclosed by either by single (‘…‘) or double (“…”)

24
25
print("Hello") # would print this message Hello
A string can be stored in a variable
greeting = “Hello”
print(greeting) # would print this message Hello
 In interactive Python interpreter always displays
strings with single quotation marks while in source
code, we use double quotation marks around
strings because this is a common.
 string of length 0 is called the empty string. It
contains no characters and is written as “ ” or ‘ ’.

26
 When a value such as 6 or 0.355 occurs in a Python
program, it is called a number literal. If a number literal
has a decimal point, it is a floating-point number;
otherwise, it is an integer.
 A variable in Python can store a value of any type. The

data type is associated with the value, not the variable.


E.g., this variable is initialized with an int value taxRate = 5
The same variable can later hold float value taxRate = 5.5
Or even hold a string: taxRate = "Non-taxable”
 However, that is not a good idea. If you use the variable

and it contains a value of an unexpected type, an error


will occur in your program.

27
 Instead, once you have initialized a variable with a value
of a particular type, you should take care that you keep
storing values of the same type in that variable.
 E.g., because tax rates are not necessarily integers, it is a
good idea to initialize the taxRate variable with floating-
point value, even if it happens to be a whole number
taxRate = 5.0 # Tax rates can have fractional parts
 Remember that taxRate can contain a floating-point
value, even though the initial value has no fractional part.

28
 whose value should not be changed after it has been
assigned an initial value.
 Python leaves it to the programmer to make sure that
constants are not changed
it is common practice to specify a constant variable with
the use of all capital letters for its name.
BOTTLE_VOLUME = 2.0
MAX_SIZE = 100

29
 It is good programming style to use named constants in
your program to explain numeric values, Example:
totalVolume = bottles * 2
totalVolume = bottles * BOTTLE_VOLUME
 A programmer reading the first statement may not
understand the significance of the number 2. The
second statement, with a named constant,
makes the computation much clearer.

30
Input
 When a program asks for user input, it should first print a
message that tells user which input is expected. Such a
message is called a prompt.
 input function can only obtain string of text from user.
 In Python, displaying a prompt and reading the keyboard
input is combined in one operation. For example:
first = input("Enter your first name: ")

 In this case, first (string variable) will contains “Rodolfo”.


This variable can be used later. The program then
continues with the next statement.

31
To read an integer value, first use the input function to
obtain the data as a string, then convert it to an integer
using the int function. For example:
userInput = input("Please enter the number of bottles: ")
bottles = int(userInput)

32
 To read a floating-point value from the user, the same
approach is used, except the input string has to be
converted to a float.
userInput = input("Enter price per bottle: ")
price = float(userInput)

 The previous examples could be written as


bottles = int( input("Please enter the number of bottles: ") )
price = float( input("Enter price per bottle: ") )

33
Output
 Is used to display messages and results to the user.
print("Hello, world“) # display Hello, world
print(2+3) # display 5
print("2+3=", 2+3) #display 2+3= 5
 In order to control results appearance, we use format
specifier. E.g. When printing amount in dollars and cents,
we want it to be rounded to two significant digits for
price per liter that is 1.215962441314554
print("% .2f" % price) # display 1.22

34
 To specify how string is to be formatted: We can specify a
field width (the total number of characters, including
spaces), like this: print("%10.2f" % price)

 Construct %10.2f is called a format specifier: it describes


how a value should be formatted. The Letter (at the end of
the format specifier)
 f indicates that we are formatting a floating-point value.
 d for an integer value
 s for a string
 For example: print("Price per liter:%10.2f" % price)
It would print Price per liter: 1.22
35
 You can format multiple values with a single string
format operation, but you must enclose them in
parentheses and separate them by commas.
 When a field width is specified, the values are right-
justified within the given number of columns
 For example:

36
 Another example:

 When we want to print these titles as left-justified. Then


we add a minus sign before the string field width. The
output in this example is much nicer than the above one.

37
38
Write a Python program that prompt for the price of a six-
pack and the volume of each can, then print out the price
per ounce?

39
Example using an assignment statement for multiple
variables and printing multiple variables

40

You might also like