CSIT110
Python
Input & Output
OBJECTIVES:
● Data types
● Convert between data types
● Input and Output
○ print function
○ input function
2
Our first Python programs
# My first Python
print("PPP
program Y Y TTTTT H H OO N N")
print("P P Y Y T H H O O NN N")
print("PPP Y T HHHH O O N N N")
print("P Y T H O O N NN")
H
print("P Y T H OO N N")
# print blank lines H
print()
print()
#
print
greetin
gs
print(
"WelcoWhat do you think this program will
me todo?
Write
Python! this python code and run it.
")
See what the code produces. 3
Our first Python programs
# print hello and greeting
print("Hello World!")
print('Welcome to
Python!')
# print hello and greeting and silly
stuff :-) print("Hello World!", end="frog")
print("Welcome to Python!", end="cat")
print("How are you?")
What is the purpose of
print("...")
print('...')
print("...",
end="...") print()
What is wrong with this
code? 4
print(Hello World!)
Variables & Data types
Variables are reserved memory locations to store values
memory
first_name age
last_name
John 20
Smith
ALWAYS use variables with meaningful names and correct data types
first_name = "John"
last_name = "Smith"
age = 20
NEVER use variable like a, b, c, x, y, z, or blah...
5
Variables & Data types
Variables store values in certain data types. Common data
types:
●
str: a string represents a sequence of characters.
We use double quotes or single quotes to create a string.
first_name = "John"
state = 'New South Wales'
●
int integer, a whole number
: an
age = 20 6
●
float: a decimal number
interest_rate = 5.2
●
bool: a boolean value is either True or
False.
scan_completed =
True virus_found =
False
Variables & Data types
Each variable has a data type.
Checking data type: type(...variable_name...)
String: using either double quote or single quote
first_name = "John"
last_name = 'Smith'
print(type(first_name)) <class 'str'>
print(type(last_name))
7
Variables & Data types
Integer: whole numbers
age = 20
temperature = -5
credit_point = 6
print(type(age))
print(type(temperature))
<class 'int'>
print(type(credit_point))
8
Variables & Data types
Float: decimal numbers
price = 30.5
interest_rate =
3.18
print(type(price))
print(type(interest_rate)) <class 'float'>
Some important math constants
import math
pi = math.pi
e = math.e
tau = math.tau
3.141592653589793
print(pi) 2.718281828459045
print(e) 6.283185307179586
print(tau) 9
Variables & Data types
Boolean: True or False
virus_scan_completed =
True
virus_found = False
print(type(virus_scan_completed))
print(type(virus_found)) <class 'bool'>
Example:
temperature = -5
temperature_negative = (temperature < 0)
print(temperature_negative) True
temperature_positive = (temperature > 0)
print(temperature_positive) False
10
Important programming rules
Variable contains data information
only
Bad example:
subject = "MATH111: Abstract Algebra"
The colon (:) is not part of the information and should not be stored in
variable. What if we want to display like this:
MATH111 - Abstract Algebra
or this:
Abstract Algebra (MATH111)
Good example:
subject_code = "MATH111"
subject_title = "Abstract
Algebra"
11
Important programming rules
Variable must be in correct data type
Bad example:
unit_price = "$10.50"
Unit price should be a number, not a string.
Good example:
unit_price = 10.50
quantity = 12
cost = unit_price * quantity
12
Important programming rules
Variable must be in correct data type
Bad example:
mobile_number = 1231231234
student_number = 1234567
Mobile number should be a string, not a number.
Student number should be a string, not a number.
Good example:
mobile_number = "0980980987"
student_number = "0043210"
13
String addition (concatenation)
# name details
first_name =
"John" last_name =
"Smith"
# use string addition to formulate the full
name full_name = first_name + " " + last_name
# display the full name
print("My name is " + full_name + ".")
My name is John Smith.
14
String addition (concatenation)
# name details
first_name =
"John" last_name =
"Smith"
full_name = first_name + " " +
# use string
last_name
this is called
addition to
# display the full name
formulate string addition
print("My
name name is " + full_name + (concatenation)
".")
memory
first_name full_name
last_name
John John Smith
Smith
15
String multiplication (with number)!
# display some silly strings
silly1 = "frog" * 7
silly2 = 5 * "I am Sam "
print(silly1)
print(silly2)
frogfrogfrogfrogfrogfrogfrog
I am Sam I am Sam I am Sam I am Sam I am Sam
16
Get input from the user
# ask the user to enter first name and last
name
last_name
first_name==input("Enter
input("Enteryour
yourlast name:
first ") ")
name:
# use string addition to formulate the full name
full_name = first_name + " " + last_name
# display the full name
print("My name is " + full_name + ".")
Enter your first name: Mary
Enter your last name:
Wilson My name is Mary
Wilson.
17
Get input from the user
# ask the user to enter some information
variable_here = input("Put the prompt here: ")
When we want to ask the user some information,
use the input function.
In the input function, we can specify the prompt.
The information that the user has entered will
be stored in the variable as a string.
18
Get input from the user
# Ask the user to enter 3 subjects
print("You must choose 3
subjects.") print()
subject1 = input("Enter the 1st subject: ")
subject2 = input("Enter the 2nd subject: ")
subject3 = input("Enter the 3rd subject: ")
# Display subjects
print()
print("You have chosen: " + subject1 + ", " + subject2 + ", " + subject3 +
"." )
You must choose 3 subjects.
Enter the 1st subject: ISIT111
Enter the 2nd subject: MATH101
Enter the 3rd subject: ACCY113
You have chosen: ISIT111, MATH101,
ACCY113. 19
Get input from the user
# Ask the user to enter 3 subjects
print("You must choose 3
subjects.") print()
subject1 = input("Enter the 1st subject: ")
subject2 = input("Enter the 2nd subject: ")
subject3 = input("Enter the 3rd subject: ")
# Display subjects
print()
print("You have chosen:
" + subject1 + ", "
+ subject2 + ", "
+ subject3 + "."
)
Rewrite the code to make it clearer.
When we have a lot of string additions,
write it this way make the code
20
clearer!
Convert number into string
# A program to display a favorite number
# favorite number
fav_number = 7
# display
favorite number
print("My
favorite number
is " +
fav_number)
Write this python code and run it.
You will see that the code cannot run
because there is an error.
What is wrong with this code? 23
Convert number into string
# A program to display a favorite number
# favorite number
fav_number = 7
# display
favorite number
print("My
favorite number
is " +
fav_number)
this isPython
a cannot add a string to a number
string
(some other programming languages can)
this is a
number
24
Convert number into string
# A program to display the favorite number
convert a number to a string
# favorite number
fav_number = 7
# display favorite number
print("My favorite number is " + str(fav_number))
fav_number 7
str(fav_number) "7"
now we can do string addition
"My favorite number is " +
"7" My favorite number is 25
Convert string into number
# Ask the user to enter 2 integers and display the sum
number1 = input("Enter the 1st integer: ")
number2 = input("Enter the 2nd integer: ")
# calculate the sum
•number_sum = number1 + number2
# display the sum
•print("The sum is " + number_sum)
Enter the 1st integer:
100 Enter the 2nd
integer: 50 The sum is
10050
why the output is like
this
24
Convert string into number
# Ask the user to enter 2 integers and display the sum
number1 = input("Enter the 1st integer: ")
number2 = input("Enter the 2nd integer: ")
# calculate the sum
number_sum = number1 + number2
# display the sum
print("The sum is " + number_sum)
Enter the 1st integer: When we ask the user to
100 Enter the 2nd enter an input, then this
integer: 50 The sum is
10050 input is a string.
number1 is a string "100"
number2 is a string "50"
string addition means
number_sum is a string
"10050" 25
Convert string into number
# Ask the user to enter 2 integers and display the
sum user_input1 = input("Enter the 1st integer: ")
number1 = int(user_input1)
user_input2 = input("Enter the 2nd integer:
") number2 = int(user_input2)
# calculate the sum
number_sum = number1 +
number2
# display the sum
print("The sum is " +
str(number_sum))
Enter the 1st integer: What did we change?
100 Enter the 2nd
integer: 50 The sum is
150
26
Convert string into number
# Ask the user to enter 2 integers and display the
sum user_input1 = input("Enter the 1st integer: ")
number1 = int(user_input1)
user_input2 = input("Enter the 2nd integer:
") number2 = int(user_input2)
# calculate the sum
number_sum = number1 +
number2
# display the sum
print("The sum is " +
str(number_sum)) Enter the 1st integer: 100
Enter the 2nd integer: 50
user_input1 is a string The sum is 150
"100" number1 is an integer
number
number addition means number_sum is a number
user_input2 is a string "50" 29
150
Convert string into number
# As k the user to enter 2 rs and display the
user_ intege input = sum t integer: ")
numbe input("Enter the 1s r1 =
int(user_input)
use d integer: ")
r_ input = input("Enter the
num 2n r2 = int(user_input)
be
culate the sum
# r_sum = number1 + number2
cal
num splay the sum
be ("The sum of "
str(number1)
#
di
pri
nt
+
+ " and "
+ str(number2) Enter the 1st integer: 100
We can use
+ " is "
just one variable user_input to save
Enter the 2nd integer: 50 30
memory
Convert string into decimal number
# Ask the user to enter 2 decimal numbers and display the sum
user_input = input("Enter the 1st number: ")
number1 = float(user_input)
user_input = input("Enter the 2nd number: ")
number2 = float(user_input)
# calculate the sum
number_sum = number1 +
number2
# display the sum
print("The sum of
"
+ str(number1)
+ " and " Enter the 1st number: 2.5
+ str(number2) Enter the 2nd number: 3.1
+ " is " The sum of 2.5 and 3.1 is
) + str(number_sum) 5.6
We use number1 = float(user_input) to convert
the string user_input into a decimal number number1 31
Get input from the user
# ask the user to enter some information
variable_here = input("Put the prompt here: ")
If the information we need from the user is a string, then
we just need one line of code:
# ask the user to enter city name
city = input("Please enter the city name: ")
# ask the user to enter the name of a song
song_name = input("Enter a song title: ")
# ask the user to enter the job title
job = input("Please enter your job title: ")
30
Get input from the user
# ask the user to enter some information
variable_here = input("Put the prompt here: ")
If the information we need from the user is not a string, but
of
other data types, then we need
● one line of code: to get user input string
● another line of code: to convert into correct data type
# ask the user to enter the year of birth
user_input = input("Please enter your year of birth: ")
year = int(user_input)
# ask the user to enter the interest rate
user_input = input("Enter the interest rate:
") rate = float(user_input)
31
Convert between data types
Convert to a string:
str(...variable_name...)
fav_number 7 str() can be used to
str(fav_number) "7" convert other data types
into string, such as
boolean, list, dictionary ect.
Convert to an integer:
int(...variable_name...)
user_input = an integer:
input("Enter ")
number = int(user_input)
user_input "50"
int(user_input) 50
32
Convert between data types
Convert to a decimal number:
float(...variable_name...)
input1 "2.3"
float(input1) 2.3
We can also convert integer to float, float to integer,
etc...
33
Convert between data types
We can transform value from one data type to
another data type. This is called “type casting”.
● Convert to string: str(...)
● Convert to integer:
int(...) float(...)
● Convert to float:
● Convert to boolean:
bool(...)
34
Naming convention
first_name = "John"
last_name =
"Smith"
full_name =
first_name + " " +
last_name
subject1 = "ISIT111"
subject2 = ="MATH101"
fav_number 7
subject3 = "ACCY113"
SECOND_PER_MINUTE = 60
minute = 5
second = minute * SECOND_PER_MINUTE
ALWAYS use variables with meaningful names
lower_case_with_underscores for normal
variables
UPPER_CASE_WITH_UNDERSCORES for 38
constant
Comment
s# print blank lines comment
print()
print()
# print greetings comment
print("Welcome to Python - Class of
2020!")
We can put comments anywhere in the program:
- to make the program clearer for people to read and maintain
- to help people understand our program better, especially, if our program has
a special logic that needs explanation
- comments are not code, so they will NOT be executed
36
Important programming rules
ALWAYS write comments first, then code.
NEVER write code first, then insert
comments.
ALWAYS use variables with meaningful names
NEVER use variable like a, b, c, x, y, z, or
blah...
37
Keywords
and elif if print
as else import raise
The following list shows the
assert except in return
Python keywords. These are
break exec is try
reserved words and we
CANNOT use them as
class finally lambda while
constant or variable any
or continue for not with
other identifier names.
def from or yield
del global pass
38
Thank you!