Python Data Types Data Type Python Abbreviation Explanation Example

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Python data types

Data type Python Explanation Example


Abbreviation
integer int A whole number. 45
string str A sequence of characters that can include “Have a nice day!”
letters, spaces and other characters.
float float A number with a fractional part. Also known as 16.76
a real number.
Boolean bool Boolean or logical data that can only have one True
of two values: True or False. False

Built-in functions
Syntax Description Example
len() Calculates the length of a string. >>> ans=len("my string")
>>> ans
9
print() Displays information on the screen. >>> print(“Hello world”)
type() Displays the type (int, bool, str or float) of a >>> ans=7.8
variable or value. >>> type(ans)
<class 'float'>
int() Converts a string or float value into an integer >>> ans=7.8
number. >>> int(ans)
Often used in conjunction with the input 7
function, e.g.
number = int(input(“Please enter the number of
T-shirts you require:”))
input(“prompt”) Prompts for input from the user. The data >>> reply=input("Enter your name: ")
entered is assigned to a variable. Enter your name: Fred
>>> reply
'Fred'
range() Creates a list of numbers. >>> for next in range(1,4):
Often used with the for loop, e.g. print(next)
range(start number, end number, in steps of). 1
End number is the number after the last 2
number required. 3
max() Returns the largest of a set of numbers. >>>max(12,16, 33)
33

Variables and lists (arrays)


Syntax Description Example
variableName = <value> Assigns a value to a variable. myString=”hello world”
myNumber= 89
myAnswer=True
variableName = <expression> Computes the value of an expression and number= 7 * 8
assigns it to a variable. answer= len(“this is the age”)
listName = [value,value,value] Assigns a set of values to a list. myList= [“apple”,”oranges”,8]
listName[index] Identifies an element of a list by reference myList[2]
to its position in the list, where index is an
integer value starting at 0.
listName[row][column] Identifies an element of a nested list myList[0][6]
(equivalent to a two dimensional array).

1
Nested lists in Python (two-dimensional arrays)
How to… Example
initialise a two-dimensional array rowLength=4
columnLength=6
myArray=[[0 for row in range(rowLength)]
for column in range(columnLength)]
address an element in a two- [row][column]
dimensional array

assign a value to an element in a two-dimensional array myArray[0][4] = 99


myArray[2][3] = 74
print the contents of a two-dimensional array, a row at a time for row in range(rowLength):
print(myArray[row])

Selection constructs
Syntax Description Example
if <expression>: If <expression> is true then if colour == "green":
<commands> commands are executed. print("It is safe for you to cross.")
if <expression>: If<expression> is true if colour == "green":
<commands1> then<commands1> are executed print("It is safe for your to cross.")
else: otherwise <commands2> are else:
<commands2> executed print("STOP! It is not safe to cross.")
if <expressionA>: If <expressionA> is true then if answer == 1:
<commands1> <commands1>are executed, else print("You will make a new friend this week.")
elif <expressionB>: if <expressionB> is true then elif answer == 2:
<commands2> <commands2>are executed, etc. print("You will do well in your GCSEs.")
elif <expressionC>: elif answer == 3:
<commands3> print("You will find something you thought
you’d lost.")
try: If <commands1> cause an error, try:
<commands1> then <commands2> are ans=numOne/numTwo
except: executed. If <commands1> except ZeroDivisionError:
<commands2> execute successfully, then print("Second number
else: <commands3>are executed. cannot be zero!")
<commands3> else:
print("The answer is: ", ans)

Iteration constructs

Syntax Description Example


for variable in Executes <commands> for a fixed myList=["cat","dog","cow","donkey","rabbit","canary"]
<expression>: number of times, given by for next in myList:
<commands> <expression>. print(next)
while Executes <commands whilst answer="N"
<condition>: <condition> is true. This is a pre- counter=0
<commands> condition loop. while answer != "Y":
print("Are you hungry? You have been asked {0}
times.".format(counter))
answer = input("Please respond Y or N:")
counter = counter + 1
print("Please get something to eat!")

2
File handling
Syntax Description Example
<file identifier variable> = Opens a file. The flag is: reading (r), myFile=open(“file.txt”,“r”)
open(<filename>, “flag”) writing (w) appending (a). This opens myFile=open(“file.txt”,“w”)
the file and creates a file object.
<file identifier variable>.close() Closes the file. myFile.close()

<file identifier Writes string to a file. Use “\n” at the myFile.write(“this is a


variable>.write(<string>) end of each record. record \n”)

Variable = <file identifier Reads a line from a file and assigns to record = myFile.readline()
variable>.readline() a variable.
How to… Explanation
start the debugger In IDLE shell choose Debug/Debugger
save a file File > Save
Hint: file type is always.py
run a program Run > Run module
or F5
display the last command entered in the shell alt p
repeat the last command entered in the shell alt n
indent and dedent blocks of code Select and use Format > Indent and Format > Dedent
interrupt a program that is running control z or control c

Escape sequence Effect


\t Tab
\n New line
\\ Displays \
\’ Displays ’
\” Displays ”

Precedence
Parentheses control the order in which expressions are calculated. Anything in parentheses
is evaluated first. The precedence order is: parenthesis (round brackets), exponential,
division and multiplication, add and subtract. B E D M A S

Python errors Description

TypeError When an operation is attempted that is invalid for that type of data.
RuntimeError An error that occurs when the program is running.
NameError When a name is used that is not known about (often a misspelt variable name).
ZeroDivisionError Dividing a number by zero.
KeyBoardInterrupt When a program is interrupted from the keyboard by pressing control+c

Rules for variable names


Must begin with a letter (upper or lower case) followed by zero or more other letters
or numbers. Cannot have spaces in the name. Can include “_”, e.g. My_variable.
Cannot use reserved Python command words.

Reserved Python command words: and, assert, break, class, continue, def,
del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or,

3
pass, print, raise, return, try, while, with, yield

Mathematical operator symbol Operation


/ divide

** exponential
// integer division

% modulus (remainder after the division)

Operator meaning Operator Sample condition Evaluates to


Equal to == “fred” == “sid” False
Not equal to != 8 != 8 False
Greater than > 10 > 2 True
Greater than or equal to >= 5 >= 5 True
Less than < 40 < 34 False
Less than or equal to <= 2 <= 109 True

Symbol Description
AND Returns true if both conditions are true.
OR Returns true if one of the conditions is true.
NOT Reverses the outcome of the expression; true becomes false, false
becomes true.

Keyboard shortcut Explanation


Control a select all

Control x cut selected text


Control f find

Control n open a new window


Control z undo

Examples of modules
math module
Function name Function explanation Example
math.pi Displays the pi constant. >>>math.pi
3.141592653589793
math.pow() Displays the first number raised to the >>> ans=math.pow(2,3)
power of the second number. >>>ans
8.0
math.sqrt() Displays the square root of a number. >>> ans=math.sqrt(1024)
>>>ans
32.0
random module

4
Function name Function explanation Example
random() Returns a random number. >>> import random
>>> ans = random.randint(1,6)
>>>ans
3
winsound module
Function name Function explanation Example
winsound.Beep(frequency, Makes a sound in the range frequency import winsound
duration) (hertz) for the duration (milliseconds). frequency = 100
for i in range (40):
winsound.Beep(frequency,200)
frequency = frequency + 50
winsound.PlaySound(filen Plays the sound file identified by file winsound.PlaySound("SystemExit",
ame, flags) name using the flags to indicate type. winsound.SND_ALIAS)
webbrowser module
Function name Function explanation Example
webbrowser.open("URL") Open the URL given as a string in the webbrowser.open("http://www.bbc.c
default web o.uk")
Turtle graphics (using x,y cartesian co-ordinates)
Turtle command Explanation Example
import turtle Imports module for turtle graphics. import turtle
t = turtle.Pen() Makes a turtle. t = turtle.Pen()
turtle.shape(“shape”) Sets shape of turtle (“arrow”, “turtle”, “circle”, t = turtle.shape(“turtle”)
“square”).
turtle.color(colour) Changes turtle colour. t = turtle.color(“red”)
turtle.forward(distance) Moves turtle forward/backward by distance t = turtle.forward(“100”)
turtle.backward(distance) given in direction it is heading.
turtle.right(angle) Turtle turns right or left by angle given. t = turtle.right(“90”)
turtle.left(angle)
turtle.goto() Turtle goes to x,y position. t = turtle.goto(200,-200)
turtle.setheading() Sets the direction the turtle will move (in t = setheading(180)
degrees) 0=north, 90 = east, 180=south,
270=west.
turtle.speed() Sets turtle speed (1 to 10). t = turtle.speed(10)
turtle.position() Reports current position as x,y co-ordinates. t.position()
turtle.heading() Reports current heading. t.heading()
turtle.circle(radius) Draws a circle of a given radius. t = turtle.circle(15)
turtle.stamp() Draws a picture of itself on the canvas. t = turtle.stamp()
turtle.penup() Puts the pen up or down. t = turtle.penup()
turtle.pendown()
turtle.pensize(width) Changes pen size. t = turtle.pensize(5)
turtle.pencolor(colour) Changes pen colour. t = turtle.pencolor(“orange”)
turtle.hideturtle() Hides and shows turtle. t = turtle.hideturtle()
turtle.showturtle()
turtle.clear() Deletes all turtle drawings. t = turtle.clear()
turtle.reset() Deletes drawing, re-centres turtle and sets t = turtle.reset()
variables to default values. (To reset everything
close Python and start again.)
turtle.undo(number) Undoes the last command. t = turtle.undo()
turtle.delay(number) Inserts a delay before next command. t = turtle.delay(50)

5
Glossary
Term Definition
Algorithm A sequence of steps to perform a task.
Flowchart A graphical representation of an algorithm that uses flow lines and shapes to
represent the operations.
Pseudocode Pseudocode looks a bit like a programming language but, unlike a real progr
language, it does not require a strict syntax. This makes it particularly useful for
designing programs. Because it is not an actual programming language,
pseudocode cannot be compiled into executable code.
Structured English Similar to pseudocode, structured English is a way of describing an algorithm
using English words to describe each step of the process.
Program code The set of instructions that form a program written in a particular programming
language.
Data type The classification of data as being a string, integer, float or Boolean (logical).
Boolean Boolean or logical data that can only have one of two values, i.e. True or False (1
= True and 0 = False).
Float A number with a fractional part, e.g. 34.67. Also known as a real number.
Integer A whole number, e.g. 45.
String A sequence of characters that can include letters, spaces, symbols, e.g. “This is a
name £££46 “
Variable A named location in a computer’s memory where data is stored.
Global variable A variable assignment that is available throughout the whole program.
Local variable A variable assignment that is only available within a subprogram.
Type declaration When a variable is allocated a particular data type (integer, string, Boolean, float).
Variable declaration When a value is assigned to a variable.
Constant A variable assignment that stays the same throughout a program.
Data structure A group of related data items. Examples include strings, arrays and lists.
Command sequence A block of program commands that are executed sequentially, i.e. one after the
other.
Loop A piece of code that keeps repeating until a certain condition is reached.
Output Data that is sent out from a program to a screen, a file or a printer.
Indentation Positioning a block of code, e.g. a for loop or an if statement, further from the
margin than the main program.
The use of indentation makes programs easier to read.
In Python correct indentation is very important, since indenting starts a block and
unindenting ends it.
Comment Text included in code that is for the human reader and is ignored by the program.
In Python, comments are indicated by the # symbol at the start of a line.
Structural components The parts of a program such as variable declarations,data structures or subprogr.
Subprogram A small computer program that runs within another computer program.
Subprograms are used to split up a program into a number of smaller programs,
with each subprogram performing a specific function. Subprograms can be called
in any order any number of times.
Function A subprogram that returns a value.
Procedure A subprogram that does not return a value.
Return value The value returned by a subprogram.
Parameter The names that appear in a function definition when passing data to a function.

6
Argument A piece of information/value that is required by a function to perform a task, e.g.
function(argument1, argument2)
Built-in subprograms Pre-existing libraries of subprograms that are built into the programming
language.
Library subprograms Pre-existing libraries of sub-programs that can be imported and used in the
programming language.
Mathematical operators Mathematical operators take two operands and perform a calculation on them.
Examples of mathematical operators are: ‘+’ (addition), ‘-‘ (subtraction), ‘*’
(multiplication), ‘/’ (division).
Precedence The order in which values are calculated.
Integer division Division in which the remainder is discarded, e.g. 10//3 = 3.
Modulus The absolute (non-negative) value of a number. The modulus of -3 is 3.
Relational operators Relational operators take two operands and compare them. Examples of
relational operators are: < (less than) < (greater than), == (equal to), != (not equal
to). Relational operators are used in conditional statements, especially in loops,
where the result of the comparison decides whether execution should proceed.
Logical operators Logical operators take two operands and compare them, returning True or False
depending on the outcome. Examples of logical operators are: AND, OR, NOT.
Logic error An error in the design of a program, such as the use of a wrong programming
control structure or the wrong logic in a condition statement.
This type of error may not produce an error message, just the wrong outcome.
Runtime error An error detected during program execution, often due to a mistake in the
algorithm or in the type of data used.
Syntax error An error that occurs when a program statement cannot be understood because it
does not follow the rules of the programming language.
Trace table A technique used to test for logical errors in a program. Each column of the table
is used to represent a variable and each row to show the values of the variables
at different stages of the program.
Break point A point in the code when a program is halted so that the programmer can
investigate the values of variables to help locate errors.
Bug An error in the code that prevents a program from running properly, or from
running at all.
Debugger A tool that helps to detect, locate and correct faults (or bugs) in programs.
Single step When a program is executed one statement at a time under user control.
Watchers Allow the programmer to watch for certain events, such as variables changing as
the program is running.
Test plan A list of tests to be carried out, designed to test a program in the widest possible
range of situations to make sure it is working.
Test data Data used in a test plan to test what happens when the input data is valid, invalid
or extreme.
Valid test data Test data that is within the normal range and should be accepted by the program.
Invalid test data Test data that is outside the normal range and should be rejected by the program.
Extreme test data Test data that is still valid, but is on the absolute limits of the normal range and
should be accepted by the program.
Textual user interface A type of interface in which the user interacts with the computer program by using
a keyboard to enter commands and make selections.
Graphical User A type of user interface that uses windows, icons, buttons and menus. A pointer is
Interface (GUI) used to make selections.
Validation Validation is designed to ensure that a program only operates on appropriate
data, e.g. that it has an appropriate format or value. It involves checking the data
that a user enters or that is read in from a file and rejecting data that does not
meet specified requirements. However, validation can only prove that the data
entered is appropriate, not that it is correct.
Integrated development A text editor with useful built in tools to help programmers develop programs, e.g.

7
environment (IDE) IDLE.
Cartesian co-ordinates A co-ordinate system that specifies a point uniquely using (x,y) co-ordinates.

You might also like