0% found this document useful (0 votes)
2 views20 pages

Python

This document serves as a comprehensive reference for Python programming, covering data types, operators, input/output, selection statements, looping, data structures, strings, file handling, and subroutines. It provides examples of syntax and usage for each concept, making it a useful guide for both beginners and experienced programmers. Key topics include arithmetic and relational operators, array manipulation, string operations, and the definition of functions and procedures.

Uploaded by

winhtikeaung43
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views20 pages

Python

This document serves as a comprehensive reference for Python programming, covering data types, operators, input/output, selection statements, looping, data structures, strings, file handling, and subroutines. It provides examples of syntax and usage for each concept, making it a useful guide for both beginners and experienced programmers. Key topics include arithmetic and relational operators, array manipulation, string operations, and the definition of functions and procedures.

Uploaded by

winhtikeaung43
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 20

Python Reference

Data Type
Date Type Description Data Type Python Example
(pseudocode) (Python)
Integer Whole number, either positive or int num = 3
negative num = int (3)
Real Positive or negative fractional values float num = 3. 12
num = float (3.12)
Character A single character or symbol ( A,$) str var = ‘A’
var = “A”
String More than one character str var = ‘Hello’
Used to hold words, names or var = “Hello”
sentences.
Boolean One of two values, either True or False bool var = False
Used to indicate the result of a
condition
NUM =0

Operator
Arithmetic Operator ( integer , float)
Operator Operation Example of use in python
+ Addition result = num1 + num2
result = 5 +5
- Subraction result = num1 - num2
* Multiplication result = num1*num2
/ Division result = num1 / num2
result = 5 /2 # result = 2.5

// Integer division (DIV) result = num1 // num2


result= 5//2 =2

% Modulus result = num1 % num2


result= 5 % 2 # 1
** Power num**2
+= Total+= num
-= Total= Total+num
*= Total *= num
Toal = Toal *num

Relational or Comparison Operator ( integer, float, string – result Boolean( T or F)


Description Pseudocode Python
is equal to = ==
Is greater than > >
Is less than < <
Is greater than or equal >= >=
Is less than or equal <= <=
Is not equal to <> !=

Logic operator ( Boolean (T or F) – result (Boolean (T or F)


Operator Description Example in Python
And Both If mark >-1 and mark < 101 : range check
Or Either or If smoke = Ture or temperature > 70 :
Not If not (num == 6 ):

Input and Output

How to take Input from user


input ( ) : used to send a message to the user and take keyboard input as
string by default
To convert it to any other data type we have to cast the string into
the desired data type
Example
num =input ( “ Enter a number”)

Casting : The process of changing the data type into another data type
by using the following function
int (value or variable)
float ( value or variable)
str ( value or variable)

Example
num = int (input ( “ Enter a number”))

How to display output/result


print ( ) : used to display output to the standard output devices.

Example
print ( “ Hello Python”)
result = 3 +4
print (result)
print (“The result is “ ,result)

Selection Statement
Selection used to determine a different set of steps to execute based on a
decision (condition).
Code branches and follows a different sequence based on decision made by
program.
if statement
Syntax Code :
if condition/decision : num= int (input(“Enter Number”))
code if num > 0 :
code print(“positive”)

if…else statement
Syntax Code :
if condition/decision : num= int (input(“Enter Number”))
code if num > 0 :
code print(“positive”)
else : else :
code print (“negative”)
if..elif..else statement

Syntax Code:

if condition : first= int(input(“Enter first number”)


Code second= int(input(“Enter first number”)
elif condition:
Code if first = second :
.
print (“same”)
.
else : elif first > second :
Code
print (‘First’)
else :
print(‘second’)
Looping/Iteration Statement
for loop
A for loop can only be used where the number of iteration is known at the time of
programming.
Syntax
for variable in range ( start value, end value, step value) :
code
Code
for i in range ( 5) : # i start from 0 and incremented by 1 and stop when i =5
for i in range(1,6) : # i start from 1 and incremented by 1 and stop when i =6
for i in range (1,6,2) : # i start from 1 and incremented by 2 and stop when i = 6

for i in range (start value, stop value)

for i in range ( 2, 7) :# I = 1 to 5 (before 6)


print(i) # 2 to 6

num = int(input(“Enter a number “)) # 5


res = 1
for i in range (1, num+1) :
res = res * i
print (“Factorial “, res)

While loop in Python

while loop is known as a pretest loop, which means it tests its condition before
performing an iteration
If a condition is true, do some task.
Syntax

while condition :
code # notice the indent from of this line relative to the for

Code
num = int (input(“Enter a number”))
While num !=-1
num= int (input(“Enter a number”))

Data Structure
Array
An array is a variable that can hold a set/list of data items, of the same data type,
under a single identifier (name).
When array is declared, its size is defined. In Python indexes start from zero.
There are two type of array:
1. One dimensional array
2. Multi-dimensional array

One-dimensional array
• A one-dimensional array (or single dimension array) is a type of linear array
that can be accessed individual by a index
Create blank array
studentName = [ ] or
myList = [None] * 5

Indexes 0 1 2 3 4

myList None None Non None None


e
Initializing Arrays
studentName =[ “Aung Aung ”, “Mya Mya”, ”Mg Mg”, “Kyaw Kyaw”]

indexes 0 1 2 3

StudentName Aung Aung Mya Mya Mg Mg Kyaw Kyaw

Element
First index = 0, Last index= 3, array length or size=4
Using Array
The index can be used to read or write values in an array.
num_arr [0]

0 1 2 3 4
num_arr

Loop for array traversal

for i in range ( start value = 0, end value= the number of item in array) :
code
len(array/list name) return the number of item in array. This function is used as the
end value of for loop for array traversal

How to retrieve data/element in array


nameList = [“Aye”, “Kyaw”, “Mya”]
for i in range (0,len(nameList)):
print( nameList [i] )

Another method
nameList = [“Aye”, “Kyaw”, “Mya”]
for a in nameList :
print( a)

How to store data in array


nameList = []
for i in range (0, 5 ) :
nameList.append(int(input(“Enter a number:”)))

nameList=[“None]*5
for i in range(0,5):
nameList[i] = int(input(“Enter a number:”))

Two-dimensional Array
Two-dimensional Array is array of array. It has row and column.

0 1 2 3 4
0 5 6 7 8 4
1 7 10 3 2 1
2 4 8 9 10 2

How to create two-dimensional Array


mylist = [ [ 5,6,7,8,4 ] , [ 7,10,3,2,1 ], [ 4,8,9,10,2 ] ]
mylist [ 1 ] [2] # use row index and col index to retrieve data in two-di array

How to retrieve data in two-di array


mylist = [ [ 5,6,7,8,4 ] , [ 7,10,3,2,1 ], [ 4,8,9,10,2 ] ]
for i in range(0,len(mylist)
for j in range(0, len(mylist[i])
print (mylist[i][j])

String
String is a sequence of characters that can be letters, numbers, symbols,
punctuation marks of spaces
String must be enclosed with quotation marks to distinguish them from variable
names
str = “Computer Science”
Each character in a string has an index number, with the first character at position
0.
Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
String C O M p U t e r S c i e N c E

String Traversal
A loop is used to traverse (retrieve) a string, character by character.
len(String) function find the length of a string.
str = “ computer science”
for i in range (0, len(str))
print(str[i])
Another way
str = “computer science”
for a in str :
print (a)
Other way to manipulate String
Finding a character with a particular index
str = “ computer science”
print ( str[0] ) # output the start char of string

Extracting Characters from a string


str = “ Computer science”
substring = str [3:6] # 3 is inclusive and 6 is exclusive
print(str)

Changing all character to lower case or upper case


lower(): Converts all uppercase characters in a string into lowercase
upper(): Converts all lowercase characters in a string into uppercase

str = “ Computer science”


str =str.lower() # computer science
print (str)
str = str.upper()
print(str)
Checking a phrase in the string
Check to see if the string “Computer science” contains the strings “put” and “Put”

str = “ Computer science”


presence = ‘put’ in str
print (presence)
presence = ‘Put’ in str
print(presence)
Concatenation
Concatenation join two or more items of information together.
“ + ” is used for string concatenation
greet =”hello”
str = greet + “John”
In python, you cannot concatenate strings with numbers
length = 13
print ( “ The length is “ + length)
To overcome this, the number must be converted to a string
length = 13
print ( “ The length is “ + str(length))
Other Function
Function Description
Name
isdigit() Returns True if all characters
in the string are digits
isalpha() Returns True if all characters
in the string are in the alphabet
islower() Returns True if all characters
in the string are lower case
isupper() Returns True if all characters
in the string are upper case
index() Searches the string for a
specified value and returns the
position of where it was found
split() Splits the string at the specified
separator, and returns a list
replace() Returns a string where a
specified value is replaced with
a specified value

Working with text file


To access a text file, you must first give it a file handler, e.g myFile
File can be opened to read from, to write to them or to append data them

Myfile = open(‘names.txt’, ‘r’)


# open a file named names.txt so that the data can be read
Myfile=open(‘names.txt’, ‘w’)
# open a file name names.txt to be written to and create a new file if it does
not exist
Myfile = open(‘names.txt’, ‘a’)
#open a file named names.txt to add data to it.
The data is write to a file
- Open the specified file
- Write the data to a file
- Close the file
Code
myFile = open(‘names.txt’, ‘w’)
myFile.write (“STZA”)
myFile.write (“LHA”)
myFile.write (“YTE”)
myFile.close()

Write the content of an array into a text file.


- Open the specified file
- Retrieve each data in the array using loop
- Write each data to a file
- Close file

Code (write value of array in the text file)


alist = [‘BMW’, ’Toyota’, ’Audi’, ’Rover’)
myFile =open(“cars.txt” ,”w”)
for a in alist:
myFile.write( a + “,”)
myFile.close()

This file can be read back into an array in the following way
- Create the blank array or variables to assign the data from the txt file
- Open the file to read data
- Read the data and assign to the array using read and split function
Code
myList = []
myFile = open(“cars.txt”, “r”)
myList = myFile.read().split(“, “)
myFile.close()

Subroutines/Subprogram (Function)

Subprogram is a block of code that preforms a specific task but does not represent
the entire program.
When a subroutines/subprogram is called, the calling program is halted and control
is transferred to the subroutine.
After a subprogram has completed execution, the control is passed back to the
calling program.

Predefined subprogram/ library or built in subprogram


A() # subprogram
A[i] # array
Many programming languages include built-in, ready-made functions, such as:
int(value) eg. int( 3.5)
input( String) eg. input(“Enter a number”)
print( String) eg. Print(“hello”)
len( mylist)
Additionally, some languages allow functions to be added in from external files
called libraries.
Libraries contain pre-written, tested functions.

User defined subroutines/subprogram


Two main type of subroutine exist:
Procedure
Procedure are small section of code that can be reused.
Do not return a value.
A parameter allows a value to be passed in to the procedure.

Syntax
def identifier ( parameter) : # parameter is optional
code
Code
def add ( num1, num2) : num1 and num2 parameter
result = num1 + num2
return result

# Main
a =3
b =5
add ( a , b) argument – a,b

Function
Function are similar to procedure
The difference is that the functions have one or more values passed to them
and one or more values are returned to the main program.
A parameter allows a value to be passed in to the procedure.
Syntax
def identifier ( parameter) : # parameter is optional
code
return value

Code
def add ( num1, num2) :
result = num1 + num2
return result
# Main
a =3
b =5
res = add ( a , b)
print(“The result is “ , res)

Advantages of Using Subprogram/Subroutines


The subroutine can be called when needed:
 A single block of code can be used many times in the entire program,
avoiding the need for repeating identical code.
 This improves the modularity of the code, make is easier to understand
and helps in the identification of errors
There is only one sections of code to be debug:
 If an error is located in a subroutine, only the individual subroutine needs
to be debugged.
There is only one section of code to update:
 Improvements and extensions of the code are available everywhere the
subroutine is called
Term
Local variable : a variable that is accessed only from within the subprogram in
which it is created
Global variable: a variable that can be accessed from anywhere in the program,
including inside subprogram
Parameter: the names of the variable that are used in the subprogram to the data
passed from the main program as argument.
Scope of variable : the region of code within which a variable is visible.
def add(num1,num2): # num1 and num2
res= num1+ num2
return res
# main
a=1
b=2
result = add(a,b) #argument-
Argument : data for function and procedure to work on can be passed from the
main program as argument
Function accept argument as parameter

Techniques for program clarity


The following techniques are used to make program easy to read and
understand.
Techniques Description
Comments Comment should be used to explain what each part of the
program does
Descriptive Using descriptive identifier for variable , constants and
names or subprogram helps to make their purpose clear
meaningful
names
Indentation Indentation makes it easier to see where each block of code
starts and finishes.
Getting indentation wrong in python will result in program
not running or not producing the expected outcomes
White space Adding blank lines between different blocks of code makes
them stand out.

Type of Error
Type of Description Exmple
Error
Logic The program seems to run normally; however, Write a + b
there is an error in the logic of the program, instead of a-b
which means it does not produce the result you
expect.
Syntax Syntax refers to the rules of the programming Write prnt
language. instead of
A syntax error means that breaks the rules of print
the language , which stops it running Missing a
closing
bracket
Missing out
quotations
marks
Write x
instead of *
Runtime An error that occurs when the computer tries to Array out of
run code that it cannot execute index
Divided by 0

Test Data Categories


Test data is sample data that is used to check the validity of
program or algorithm.
Test Data Description
Normal Data that is well written the limits of what should be accepted
by the program
Boundary Data that is at upper limit or lower limit of what should be
accepted by the program
Erroneous Data that should not be accepted by the program

Example
The programmer accepts the number that is greater than 0 and less than
10.
Normal Test data : 1,6
Boundary: 1 and 9

Normal : 2,7
Erroneous : -1, 14
Boundary :1, 9

Evaluating program
 Usability
 Validation-
 Code readability
 Requirement
 The efficiency of program- have loop and subprogram to avoid
duplicate code

You might also like