0% found this document useful (0 votes)
6 views8 pages

From Book For Python

Uploaded by

azharisma341
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views8 pages

From Book For Python

Uploaded by

azharisma341
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

IF x < 0

THEN
OUTPUT "Negative"
ENDIF

if x < 0:
print("Negative")
-----------------
IF x < 0
THEN
OUTPUT "Negative"
ELSE
IF x = 0
THEN
OUTPUT "Zero"
ELSE
OUTPUT "Positive"
ENDIF
ENDIF

if x < 0:
print("Negative")
elif x == 0:
print("Zero")
else:
print("Positive")
------------
CASE OF Grade
"A" : OUTPUT "Top grade"
"F", "U" : OUTPUT "Fail"
"B".."E" : OUTPUT "Pass"
OTHERWISE OUTPUT "Invalid grade"
ENDCASE

if Grade == "A":
print("Top grade")
elif Grade == "F" or Grade == "U":
print("Fail")
elif Grade in ("B", "C", "D", "E"):
print("Pass")
else:
print("Invalid grade")
-----------------------
FOR x ← 1 TO 5
OUTPUT x
NEXT x

for x in range(5):
print(x, end=' ')
---------------------
FOR x = 2 TO 14 STEP 3
OUTPUT x
NEXT x

for x in range(2, 14, 3):


print(x, end=' ')
-------------------------------
FOR x = 5 TO 1 STEP -1
OUTPUT x
NEXT x

for x in range(5, 1, -1):


print(x, end=' ')
-----------------------------
for x in ["a", "b", "c"]:
print(x, end='')
The control variable takes the value of each
of the group elements in turn.
Output: abc
------------------------------------
Answer ← ""
WHILE Answer <> "Y" DO
INPUT "Enter Y or N: " Answer
ENDWHILE

Answer = ''
while Answer != 'Y':
Answer = input("Enter Y or N: ")
-----------------------------------------
Returns the character whose
ASCII value is i
CHR(i : INTEGER)
RETURNS CHAR

chr(i)
_________________
eturns the ASCII value of
character ch
ASC(ch) RETURNS
INTEGER

ord(ch)
__________________________
Returns the integer value
representing the length of
string S
LENGTH(S : STRING)
RETURNS INTEGER

len(S)
----------------------------
Returns leftmost L characters
from S
S[0:L]
-----------------------
Returns rightmost L characters
from S
S[-L:]
-----------------------------
Returns a string of length L
starting at position P from S
S[P : P + L]
---------------------------
Returns the character value
representing the lower case
equivalent of Ch
LCASE(Ch : CHAR)
RETURNS CHAR

[Link]()
-----------------------------
UCASE(Ch : CHAR)
RETURNS CHAR

[Link]()
-------------------------
TO _ UPPER(S :
STRING) RETURNS
STRING

[Link]()
-----------------------------
TO _ LOWER(S :
STRING) RETURNS
STRING
[Link]()
-----------------------------
Concatenate (join) two strings
S1 & S2

s = S1 + S2
------------------------------
INT(x : REAL) RETURNS INTEGER
Returns the integer part of

int(x)
_________________________________
string to a number
int(S)
-----------------
STRING _ TO _ NUM(x :STRING) RETURNS REAL
Returns a numeric representation of a string

float(x)
--------------------------
Random number generator

randint(1, 6)

This code produces a random


number between 1 and 6 inclusive
--------------------------
PROCEDURE InputOddNumber()
REPEAT
INPUT "Enter an odd number: " Number
UNTIL Number MOD 2 = 1
OUTPUT "Valid number entered"
ENDPROCEDURE

def InputOddNumber():
Number = 0
while Number %2==1:
Number=int(input("Enter an odd number"))
print("valid number")
------------------------------------------
def InputOddNumber():
Number = 0
while Number %2==1:
Number=int(input("Enter an odd number"))
return Number
_______________________________________
FUNCTION SumRange(FirstValue : INTEGER, LastValue : INTEGER) RETURNS INTEGER
DECLARE Sum, ThisValue : INTEGER
Sum ← 0
FOR ThisValue ← FirstValue TO LastValue
Sum ← Sum + ThisValue
NEXT ThisValue
RETURN Sum
ENDFUNCTION

def SumRange(FirstValue, LastValue):


Sum = 0
FOR ThisValue in range (FirstValue, LastValue +1):
Sum = Sum + ThisValue
RETURN Sum

In any other program call:-

-----------------------------------------------------------------
Passing parameters by value

PROCEDURE OutputSymbols(BYVALUE NumberOfSymbols : INTEGER, Symbol : CHAR)


DECLARE Count : INTEGER
FOR Count ← 1 TO NumberOfSymbols
OUTPUT Symbol // without moving to next line
NEXT Count
OUTPUT NewLine
ENDPROCEDURE

def OutputSymbols(NumberOfSymbols, Symbol )


FOR Count in range (NumberOfSymbols)
print (Symbol, end='')
print()

In any other program call:-


OutputSymbols(5,'*')
--------------------------------------------------------------------
Python does not have a facility to pass parameters by reference. Instead the
subroutine
behaves as a function and returns multiple values

def Advalue(Spaces,Smybols):
Spaces = Spaces - 1
Smybols = Symbols +2
return Spaces, Symbols

In any other program :-


NumOfSpaces = int(input())
NumOfSmbols= int(input())
NumOfSpaces, NumOfSmbols = Advalue(NumOfSpaces, NumOfSmbols)
print (NumOfSpaces)
print (NumOfSmbols)

-------------------------------------------------

In Python, there are no arrays. The equivalent data structure is called a list. A
list is an
ordered sequence of items that do not have to be of the same data type

List1 = []
[Link]("Fred")
[Link]("Jack")
[Link]("Ali")
As there are no declarations, the only way to
generate a list is to initialise one.
You can append elements to an existing list.

List2 = [0, 0, 0, 0, 0, 0]
List3 = [0 for i in range(100)]
AList = [""] * 26
NList[24] = 0
AList[3] = "D"

print(List)
__________________________________________________________
2D ARRAY
2D lists can be initialised in a similar
way to 1D lists. Remember that
elements are numbered from 0.
These are alternative ways of initialising
a 6 × 7 list. The rows are numbered 0 to
5 and the columns 0 to 6.
The upper value of the range is not
included.
Board = [[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]]
Board = [[0 for i in range(7)]
for j in range(6)]
Board = [[0] * 7] * 6
------------------------------------------------
2D ARRAY
Board[3,4] ← 0 // sets the element in row 3 and column 4 to zero
Board[2][3] = 0 # Elements are numbered from 0 in Python, so [3] gives
# access to the fourth element.
____________________________________________________________________
Text files
OPENFILE <filename> FOR WRITE // open the file for writing
FileHandle = open("[Link]", "w")
WRITEFILE <filename>, <stringValue>
[Link](LineOfText)

CLOSEFILE <filename>
[Link]()
___________________________________________
Reading from a text file

OPENFILE <filename> FOR READ // open file for reading


READFILE <filename>, <stringVariable> // read a line of text from the file
CLOSEFILE <filename> // close file

FileHandle = open("[Link]", "r")


LineOfText = [Link]()
[Link] ()
_________________________________________
Appending to a text file

OPENFILE <filename> FOR APPEND // open file for append


WRITEFILE <filename>, <stringValue> // write a line of text to the file
CLOSEFILE <filename> // close file

FileHandle = open("[Link]", "a")


[Link](LineOfText)
[Link]()
________________________________________________________
The end-of-file (EOF) marker

OPENFILE "[Link]" FOR READ


WHILE NOT EOF("[Link]") DO
READFILE "[Link]", TextString
OUTPUT TextString
ENDWHILE
CLOSEFILE "[Link]"

FileHandle = open("[Link]", "r")


LineOfText = [Link]()
while len(LineOfText) > 0:
LineOfText = [Link]()
print(LineOfText)
[Link]()
______________________________________________________
record type
Python does not have a record type. However, we can use a class definition with
only a constructor to assign initial
values.

class CarRecord:
def __init__(self): # constructor
[Link] = ""
[Link] = ""
[Link] = None
[Link] = 0
[Link] = 0.00

ThisCar = CarRecord()
[Link] = 2500
Car = [CarRecord() for i in range(100)]
Car[1].EngineSize = 2500
-----------------------------------------------------
Exception handling

TRY
<statementsA>
EXCEPT
<statementsB>
ENDTRY

NumberString = input("Enter an integer: ")


try:
n = int(NumberString)
print(n)
except:
print("This was not an integer")
-----------------------------------------------------------------
Declaring a class in Python with methods

class Car:
def __init__(self, n, e):
self.__VehiclelD = n
self.__Registration = “”
self.__Date0fRegistration = None
self.__EngineSize = e
self.__PurchasePrice = 0.00
# constructor
def SetPurchasePrice(self, p):
self.__PurchasePrice = p
def SetRegistration(self, r):
self.__Registration = r
def SetDateOfRegistration(self, d):
self.__Date0fRegistration = d
-----------------------------------------
class Car:
def __init__(self, n, e):
self.__VehiclelD = n

def GetVehicleID ID(self) :


return(self.__VehicleID)

def VehicleID(self): #property


return(self.__VehicleID)
---------------------------------------------

ThisCar = Car("ABC1234", 2500)


--------------------------------------------------------
[Link](12000)
[Link] = 12000 # using properties
-------------------------------------------------------
print([Link]())
print([Link]) # using properties
------------------------------------------------------

You might also like