Python - Basic Python Program
Python - Basic Python Program
Pn Marhainis Jamaludin
Faculty of Computer and Mathematical Sciences
Python Data Types
• Variable Names
• can take any forms : numbers, letters, and underscore.
• Must begin with a letter or underscore
• Case sensitive
• Cannot use Python reserve words
• Native data types
• Floating point (float)
• Complex number - using j or the function complex()
• Integers (int and long)
• Boolean (bool)
• Strings (str)
• Lists (list)
• Tuples (tuple) - list but contain multiple pieces of data and mix data
types.
• Xrange (xrange) - useful during for loop
• Dictionary (dict) – used to pass options within functions
• Sets (set, frozenset) - collections which contains all unique
elements of a collection
Comment line
• Python will ignore all the lines which starts with # symbol
• # symbol is used for comment.
Printing Command
• Python 3.x uses function named print() to print or
display on screen.
Input from keyboard
• Python uses function named input() to get the
input from the keyboard.
Typecasting
• Python provides built-in function to typecast a
variable into another data type.
• The built-in function such as int(), str(), float()
/ Division print (7 / 5)
Will yield float result
** Exponentiation print (2 ** 3)
% Modulus Print (9 % 4)
Boolean Data Type
• Boolean data type (bool) in Python either True or
False (the first character must be capitalized)
Comparison Operators
Type Operator Description
Relational Operators < Less than
<= Less than and equal to
> Greater than
>= Greater than and equal to
== Equal
!= Not equal
Logical Operators and Both must be true than the result
will be true
or Either one must be true than the
result will be true
not The opposite
Special operator is Do two references refer to the same
object?
Immutability
• Everything in Python is an object.
• Python represents all its data as objects.
• Those mutable objects can be changed after it is created, however,
immutable objects cannot be changed.
• Mutable objects – container data types
• You can change the content without changing their identity
• Build-in types such as: list, set, dict
• For example lists → you can change the content of a lists, represent by square
brackets []
Example:
subject = “DCS55
credhr = 3
cgpa = 3.25
print ( “This semester %s has %d credit hours and cgpa must be above %4.2f”
%(subject,credhr,cgpa)
Exercise 1:
• Write a python program to input two numbers,
sum those numbers and display the output. The
example is shown below:
Enter the first number: 45
Enter the second number : 60
The sum of two numbers is 105
Exercise 2:
• Given unitprice = 22.50, qty = 20, item = “Academic
Book”
• Calculate the total price to be paid where totalprice = unitprice
* qty
• Use the appropriate formatting to display as given below:
Academic Book price is RM22.50, Amran bought 20 books, the total price is
RM450.00