Python Notes FINAL
Python Notes FINAL
Python interpreter and interactive mode; values and types: int, float, boolean, string, and list;
variables, expressions, statements, tuple assignment, precedence of operators, comments; Modules and
functions, function definition and use, flow of execution, parameters and arguments; Illustrative
programs: exchange the values of two variables, circulate the values of n variables, distance between
two points.
INTRODUCTION TO PYTHON:
Python is a general-purpose interpreted, interactive, object-oriented, and high- level programming
language.
It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was released in the
year 2000.
Python is interpreted: Python is processed at runtime by the interpreter. You
do not need to compile your program before executing it.
Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or technique
of programming that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for the beginner-
level programmers and supports the development of a wide range of applications.
Easy-to-learn:Python is clearly defined and easily readable. The structure of the program is very simple.
It uses few keywords.
Python interpreter:
Interpreter: To execute a program in a high-level language by translating it one line at a time.
Compiler: To translate a program written in a high-level language into a low-level language all at once, in
preparation for later execution.
This is an example of a print statement. It displays a result on the screen. In this case, the result is the
words.
Script mode:
In script mode, we type python program in a file and then use interpreter to
execute the content of the file.
Scripts can be saved to disk for future use. Python scripts have the extension
.py, meaning that the filename ends with .py
Save the code with filename.py and run the interpreter in script mode to execute
the script.
Value:
Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:
Numbers:
Number data type stores Numerical Values.
This data type is immutable [i.e. values/items cannot be changed].
Python supports integers, floating point numbers and complex numbers. They
are defined as,
Sequence:
A sequence is an ordered collection of items, indexed by positive integers.
It is a combination of mutable (value can be changed) and immutable (values
cannot be changed) data types.
There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
Tuple:
A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
A tuple is an immutable list. i.e. once a tuple has been created, you can't add
elements to a tuple or remove elements from the tuple.
Benefit of Tuple:
Tuples are faster than lists.
If the user wants to protect the data from accidental changes, tuple can be used.
Tuples can be used as keys in dictionaries, while lists can't.
Altering the tuple data type leads to error. Following error occurs when user tries to do.
>>> t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module> Type Err
assignment
Mapping
VARIABLES:
A variable allows us to store a value by assigning it to a name, which can be used later.
Named memory locations to store values.
Programmers generally choose names for their variables that are meaningful.
It can be of any length. No space is allowed.
We don't need to declare a variable before using it. In Python, we simply assign a
value to a variable and it will exist.
>>> a=b=c=100
Assigning multiple values to multiple variables:
>>> a,b,c=2,4,"ram"
KEYWORDS:
Keywords are the reserved words in Python.
We cannot use a keyword as variable name, function name or any other
identifier.
They are used to define the syntax and structure of the Python language.
Keywords are case sensitive.
IDENTIFIERS:
Identifier is the name given to entities like class, functions, variables etc. in
Python.
Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A
to Z) or digits (0 to 9) or an underscore (_).
all are valid example.
An identifier cannot start with a digit.
Keywords cannot be used as identifiers.
Cannot use special symbols like !, @, #, $, % etc. in our identifier.
Identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable
INPUT: Input is data entered by user (end user) in the program. In python, input () function is available for
input.
Syntax for input() is:
variable = input (“data”)
Example:
>>> x=input("enter the name:")
enter the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. conversion is required for type.
COMMENTS:
A hash sign (#) is the beginning of a comment.
Anything written after # in a line is ignored by interpreter.
Eg:percentage = (minute * 100) / 60 # calculating percentage of an hour
Python does not have multiple-line commenting feature. You have to
comment each line individually as follows :
Example:
# This is a comment.
# This is a comment, too.
# I said that already.
DOCSTRING:
Docstring is short for documentation string.
It is a string that occurs as the first statement in a module, function, class, or
method definition. We must write what a function/class does in the docstring.
Triple quotes are used while writing docstrings.
Syntax:
functionname__doc.__
Example:
def double(num):
"""Function to double the value"""
return 2*num
>>> print(double. doc ) Function to double the value
a=3 b=1
if a>b:
print("a is greater")
else:
print("b is greater")
QUOTATION IN PYTHON:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals. Anything that is
represented using quotations are considered as string.
TUPLE ASSIGNMENT
Example:
-It is useful to swap the values of two variables. With conventional assignment statements, we have to use
a temporary variable. For example, to swap a and b:
-In tuple unpacking, th e va lues in a tuple on the right are ‘un pa cked’ into the variables/names on
the right:
OPERATORS:
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator
Types of Operators:
-Python language supports the following types of operators
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction, multiplication etc. Assume,
a=10 and b=5
- Subtraction Subtracts right hand operand from left hand a – b = -10 operand.
% Modulus Divides left hand operand by right hand operand b % a = 0 and returns remainder
** Exponent Performs exponential (power) calculation on a**b =10 to the operators
power 20
// Floor Division - The division of operands where the 5//2=2 result is the quotient in
which the digits after the
decimal point are removed
> If the value of left operand is greater than the value of right (a > b) is operand,
then condition becomes true. not true.
< If the value of left operand is less than the value of right (a < b)
is operand, then condition becomes true. true.
>= If the value of left operand is greater than or equal to the (a >= b)
is value of right operand, then condition becomes true. not true.
<= If the value of left operand is less than or equal to the value (a <= b)
is of right operand, then condition becomes true. true.
Example
a=10 Output:
b=5 a>b=> True
print("a>b=>",a>b) a>b=> False print("a>b=>",a<b) a==b=> False
print("a==b=>",a==b) a!=b=> True print("a!=b=>",a!=b) a>=b=> False
print("a>=b=>",a<=b) a>=b=> True print("a>=b=>",a>=b)
Assignment Operators:
-Assignment operators are used in Python to assign values to variables.
+= Add AND It adds right operand to the left operand and assign c += a is the result to left
operand equivalent to c = c + a
Example
a = 21 b = 10 c = 0
c=a+b
print("Line 1 - Value of c is ", c)
c += a
print("Line 2 - Value of c is ", c)
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c =2
c %= a
print("Line 5 - Value of c is ", c) c **= a
print("Line 6 - Value of c is ", c) c //= a
print("Line 7 - Value of c is ", c)
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
Logical Operators:
-Logical operators are the and, or, not operators.
Example Output
a = True x and y is False b = False x or y is True
print('a and b is',a and b) not x is False print('a or b is',a or b)
print('not a is',not a)
Bitwise Operators:
A bitwise operation operates on one or more bit patterns at the level of individual
bits
Example: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Example Output
a = 60 # 60 = 0011 1100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61 c = 0
Line 3 - Value of c is 49
c = a & b; # 12 = 0000 1100 Line 4 - Value of c is -61
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240 c = a | b; # 61 = 0011 1101
Line 6 - Value of c is 15 print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001 print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
Membership Operators:
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Identity Operators:
They are used to check if two values (or variables) are located on the same part
of the
memory.
Example
x=5 Output
y=5 False x2 = 'Hello' True
y2 = 'Hello' print(x1 is not y1) print(x2 is y2)
OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
~+- Complement, unary plus and minus (method names for the last two are +@
and -@)
Example:
a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
a=? A=6+4%5-3/2+6 find m=?
a=9-4+3*2-1 A=6+4-3/2+6 m=-43||8&&0||-2
a=9-4+6-1 A=6+4-1+6 m=-43||0||-2 a=5+6-1
A=10-1+6 m=1||-2
a=11-1 A=9+6 m=1
a=10 A=15
PYTHON – CONDITIONALS
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as
outcome. You need to determine which action to take and which statements to execute if outcome is TRUE
or FALSE otherwise
Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or
null, then it is assumed as FALSE value
Statement Description
if statements if statement consists of a boolean expression followed by one or more
statements
if...else statements if statement can be followed by an optional else statement, which executes
when the boolean expression is FALSE
nested if statements You can use one if or else if statement inside another if or else if
statement(s)
conditional (if)
It is similar to that of other languages. The if statement contains a logical expression using which data is
compared and a decision is made based on the result of the comparison.
Syntax
if(test-expression):
statement-block(s)
statement-x
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement
is executed. If boolean expression evaluates to FALSE, then the first set of code
after the end of the if statement(s) is executed.
The boolean expression after if is called the condition. If it is true, the indented statement runs. If
not, nothing happens.
if statements have the same structure as function definitions: a header followed by an indented
body. Statements like this are called compound statements.
alternative (if…else)
A second form of the if statement is “alternative execution”, in which there are two
possibilities and the condition determines which one runs.
An else statement can be combined with an if statement. An else statement contains the block of code that
executes if the conditional expression in the if statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else statement
following if.
Syntax
if(test-expression):
true-block-statement(s) else:
false-block-statement(s) statement-x
For example:
if x % 2 == 0:
print('x is even') else:
print('x is odd')
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays an
appropriate message. If the condition is false, the second set of statements runs. Since the condition must
be true or false, exactly one of the alternatives will run. The alternatives are called branches, because
they are branches in the flow of execution
Sometimes there are more than two possibilities and we need more than two branches.
One way to express a computation like that is a chained conditional.
The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon
as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there
can be at most one statement, there can be an arbitrary number of elif statements following an if.
Core Python does not provide switch or case statements as in other languages, but we can use
if..elif...statements to simulate switch case
Syntax
if(test-condition-1):
statement-1 elif(test-condition-2):
statement-2
. . .
. . . elif(test-condition-n):
else:
statement-n
default-statement statement-x
For example:
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y') else:
elif is an abbreviation of “else if”. Again, exactly one branch will run. There is no limit on the number of elif
statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.
if choice == 'a':
draw_a() elif choice == 'b': draw_b()
elif choice == 'c':
draw_c()
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true,
the corresponding branch runs and the statement ends. Even if more than one condition is true, only the
first true branch runs.
else:
else:
PYTHON ITERATION
REASSIGNMENT
As you may have discovered, it is legal to make more than one assignment to the same variable. A
new assignment makes an existing variable refer to a new value (and stop referring to the old value).
>>> x=5
>>> x
5
>>> x=7
>>> x
7
The first time we display x, its value is 5; the second time, its value is 7.
Python uses the equal sign (=) for assignment, it is tempting to interpret a statement like a = b as a
mathematical proposition of equality; that is, the claim that a and b are equal. But this interpretation is
wrong.
First, equality is a symmetric relationship and assignment is not. For example, in mathematics,
if a=7 then 7=a. But in Python, the statement a = 7 is legal and 7 = a is not.
Also, in mathematics, a proposition of equality is either true or false for all time. If a=b now, then a will
always equal b. In Python, an assignment statement can make two variables equal, but they don’t
have to stay that way:
>>> a=5
>>> b = a # a and b are now equal
>>> a = 3 # a and b are no longer equal
>>> b
5
The third line changes the value of a but does not change the value of b, so they are no longer equal.
Reassigning variables is often useful, but you should use it with caution. If the values of variables
change frequently, it can make the code difficult to read and debug.
UPDATING VARIABLES
A common kind of reassignment is an update, where the new value of the variable depends on the old.
>>> x = x + 1
This means “get the current value of x, add one, and then update x with the new value.”
If you try to update a variable that doesn’t exist, you get an error, because Python evaluates
the right side before it assigns a value to x:
>>> x = x + 1
NameError: name 'x' is not defined
Before you can update a variable, you have to initialize it, usually with a simple assignment:
>>> x=0
>>> x=x+1
In general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on. There may be a situation when you need to execute a block of code
several number of times.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
Python programming language provides following types of loops to handle looping requirements
While Loop
A while loop statement in Python programming language repeatedly executes a target statement as
long as a given condition is true.
Syntax
while(test-condition):
body of the loop statement-x
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value. The loop iterates while the
condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.
In Python, all the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its method
of grouping statement.
You can almost read the while statement as if it were English. It means, “While n is greater than 0, display
the value of n and then decrement n. When you get to 0, display the word Blastoff!”
This type of flow is called a loop because the third step loops back around to the top.
The body of the loop should change the value of one or more variables so that the condition becomes false
eventually and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite
loop.
In the case of countdown, we can prove that the loop terminates: if n is zero or negative, the loop never
runs. Otherwise, n gets smaller each time through the loop, so eventually we have to get to 0.
while n != 1:
print(n)
if n % 2 == 0: # n is even n = n / 2
else: # n is odd
n = n*3 + 1
The condition for this loop is n != 1, so the loop will continue until n is 1, which makes the condition false.
Each time through the loop, the program outputs the value of n and then checks whether it is even or odd.
If it is even, n is divided by 2. If it is odd, the value of n is replaced with n*3 + 1. For example, if the
argument passed to n is 3, the resulting values of n are 3, 10, 5, 16, 8, 4, 2,1.
Since n sometimes increases and sometimes decreases, there is no obvious proof that n will ever reach 1, or
that the program terminates. For some particular values of n, we can prove termination. For example, if the
starting value is a power of two, n will be even every time through the loop until it reaches 1. The previous
example ends with such a sequence, starting
with 16.
A for statement is also called a loop because the flow of execution runs through the body and then loops
back to the top.
Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making
errors is something that computers do well and people do poorly. In a computer program, repetition
is also called iteration.
The syntax of a for statement has a header that ends with a colon and an indented body. The body can
contain any number of statements.
Syntax
for i in range(4):
print('Hello!')
You should see something like this: Hello!
Hello!
Hello! Hello!
This is the simplest use of the for statement. In this case, it runs the body four times.
break STATEMENT
Sometimes you don’t know it’s time to end a loop until you get halfway through the body. In that case you
can use the break statement to jump out of the loop. break is used to break out of the innermost loop.
For example, suppose you want to take input from the user until they type done. You could write:
while True:
line = input('> ')
if line == 'done':
break print(line)
print('Done!')
The loop condition is True, which is always true, so the loop runs until it hits the break statement.
Each time through, it prompts the user with an angle bracket. If the user types done, the break
statement exits the loop. Otherwise the program echoes whatever the user types and goes back to the top
of the loop. Here’s a sample run:
>not done not done
>done
Done!
This way of writing while loops is common because you can check the condition anywhere in the loop (not
just at the top) and you can express the stop condition affirmatively (“stop when this happens”)
rather than negatively (“keep going until that happens”).
The while loop to print the squares of all the odd numbers below 10, can be modified using the break
statement, as follows
i=1
while True:
print (i * i)
i = i + 2 if(i > 10):
break
continue STATEMENT
continue is used to skip execution of the rest of the loop on this iteration and continue to the end of this
iteration.
For example we wish to print the squares of all the odd numbers below 10, which are not multiples of 3,
we would modify the for loop as follows.
There is no limit on the number of statements that can appear in the body, but there has to be at least one.
Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t
written yet). In that case, you can use the pass statement, which does nothing.
if x < 0:
pass # TODO: need to handle negative values!
“pass” statement acts as a place holder for the block of code. It is equivalent to a null
operation. It literally does nothing. It can used as a place holder when the actual code
implementation for a particular block of code is not known yet but has to be filled up later.
FUNCTIONS:
Function is a sub program which consists of set of instructions used to perform a specific task. A
large program is divided into basic building blocks called function.
Need For Function:
When the program is too complex and large they are divided into parts. Each part is separately coded and
combined into single program. Each subprogram is called
as function.
Debugging, Testing and maintenance becomes easy when the program is divided
into subprograms.
Functions are used to avoid rewriting same code again and again in a program.
Function provides code re-usability
The length of the program is reduced.
Types of function:
Functions can be classified into two categories:
i) user defined function ii) Built in function
i) Built in functions
Built in functions are the functions that are already created and stored in python.
These built in functions are always available for usage and accessed by a
programmer. It cannot be modified.
Built in function Description
Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1 statement2… statement n
return[expression]
Example:
def my_add(a,b): c=a+b return c
Flow of Execution:
The order in which statements are executed is called the flow of execution
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order, from top to bottom.
Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the function
is called.
Function calls are like a bypass in the flow of execution. Instead of going to the
next statement, the flow jumps to the first line of the called function, executes all the statements there, and
then comes back to pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of
execution. This means that you will read the def statements as you are scanning from top to bottom, but
you should skip the statements of the function definition until you reach a point where that function is
called.
Function Prototypes:
i. Function without arguments and without return type ii. Function with arguments and without return
type
iii. Function without arguments and with return type
iv. Function with arguments and with return type
Example:
def my_add(a,b):
c=a+b return c
x=5 y=4 print(my_add(x,y))
Output:
9
ARGUMENTS TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
Required Arguments: The number of arguments in the function call should
match exactly with the function definition. def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return my_details("george",56)
Output:
Name: george
Age 56
Keyword Arguments:
Python interpreter is able to use the keywords provided to match the values with parameters even though
if they are arranged in out of order.
def my_details( name, age ): print("Name: ", name) print("Age ", age)
return my_details(age=56,name="george") Output:
Name: george
Age 56
Default Arguments:
Assumes a default value if a value is not provided in the function call for that argument.
def my_details( name, age=40 ): print("Name: ", name) print("Age ", age)
return
my_details(name="george")
Output:
Name: george
Age 40
MODULES:
A module is a file containing Python definitions ,functions, statements and
instructions.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the
module.
else:
else:
print(i)
13579
print(i)
2468
Print squares of numbers Output
for i in range(1,5,1): 1 4 9 16
print(i*i)
for i in range(1,5,1): 1 8 27 64
print(i*i*i)
Arrays
There is not much we can do with lists and tuples, except print them. Even when you print them,
the statements can become cumbersome. Also, there is no way to manipulate directly a list: if we
wanted to create a new list from an existing list by removing its last element, we could not. The
solution offered by Python is to store lists and tuples into arrays.
Assigning arrays
Names for arrays follow the same rules as those defined for scalar variables. We store a list into
an array the same way we store a scalar into a scalar variable, by assigning it with =:
for a tuple, or for a list.
>>> range(10)
[0,1,2,3,4,5,6,7,8,9]
>>> range(10,21)
[10,11,12,13,14,15,16,17,18,19,20]
>>> range(1,10,2)
[1,3,5,7,9]
>>> days=(‘Monday’,’Tuesday’,’Wednesday’,’Thursday’,’Friday’,’Saturday’,’Sunday’)
>>> days=[‘Monday’,’Tuesday’,’Wednesday’,’Thursday’,’Friday’,’Saturday’,’Sunday’]
Once we have assigned a list to an array, we can use it where we would use a list. For example,
will print:
[‘Monday’,’Tuesday’,’Wednesday’,’Thursday’,’Friday’,’Saturday’,’Sunday’]
Accessing one element in an array
We can access one element in an array by using the index of the drawers it has been assigned to.
Remember how we access an element in a list:
[‘Monday’,’Tuesday’,’Wednesday’,’Thursday’,’Friday’,’Saturday’,’Sunday’][0]
gives us the first element in the list, i.e. ‘Monday’. We could do:
days[0];
to access the first element of the array days.
Accessing an element in an array works both ways: we can either retrieve the value contained in
the position considered, or assign a value to that position. For example,
Scalar variables and arrays.
A scalar variable is like a single box, while an array behaves like a chest of drawers. Each of the drawers is
assigned a number, or index, which starts at 0.
>>> print days
Creates an array names numbers that contains the list [0,1,5]. This list can then be modified:
The array numbers now contains the list [3,4,5].
Important: you can change elements in a list, but you will get an error message if you try the
same thing in a tuple.
Array manipulation
Python provides a list of functions that manipulates list. Let A be a list:
Type Notation Function
Adding values A.append(obj) Adds obj at the end of list A
A.extend(list) Adds list at the end of list A
A.insert(index,item) Adds item at position index in A, and move the
remaining items to the right
Remove values del A[i] Removes element at position i in the list A
Item=A.pop(index) Removes object at position index in A, and
stores it in variable item
A.remove(item) Search for item in A, and remove first instance
Reverse A.reverse() Reverses list A
Sorting A.sort() Sorts list A in place, in increasing order
Searching I=A.index(item) Search for item in list A, and puts index of first
occurrence in i
Counting N=A.count(item) Counts the number of occurrence of item in A
Length N=len(A) Finds number of items in A, and stores in N
Important again: you can manipulate elements in a list, but you will get an error message if you
try the same thing in a tuple.
numbers = [0,1,5];
numbers[0]=3;
numbers[1]=4;
numbers[2]=5;
From arrays to string and back.
join: from array to string:
You can concatenate all elements of a list into a single string using the operator join. The syntax
is:
It concatenates all elements of LIST and stores them in the string A. Not the presence of ‘’
before join.
Split and list: from string to array
We have seen in chapter 1 that the function split will break down a string into a list, using a
specified delimiter to mark the different elements. If the delimiter is omitted, split separates each
word in the string. For example, if A=”This is a test”, A.split() will generate the list
[“This”,”is”,”a”,”test”]. Split however cannot break down a word into characters: to do that, we
use the function list.
For example, if we want to break a paragraph into sentences, a sentence into words, and a word
into characters, we use:
In all three cases, the result is a list and the input was a string
Create an Array
We can create a Python array with comma separated elements between square
brackets[].
Example 1: How to create an array in Python?
We can make an integer array and store it to arr.
arr = [10, 20, 30, 40, 50]
Access elements of an Array
We can access individual elements of an array using index inside square
brackets [].
Array Index
Index is the position of element in an array. In Python, arrays are zero-indexed. This
means, the element's position starts with 0 instead of 1.
Example 2: Accessing elements of array using indexing
arr = [10, 20, 30, 40, 50]
print(arr[0])
print(arr[1])
print(arr[2])
When we run the above program, the output will be:
10
20
30
Here, the first element of arr is arr[0], second is arr[1], third is arr[2], and so on.
Negative Indexing
Python programming supports negative indexing of arrays, something that is not
available in arrays in most programming languages.
This means the index value of -1 gives the last element, and -2 gives the second to
last element of an array.
Example 3: Accessing elements of array using negative
indexing
arr = [10, 20, 30, 40, 50]
print(arr[-1])
print(arr[-2])
When we run the above program, the output will be:
50
40
Find length of an Array
Python arrays are just lists, so finding the length of an array is equivalent to finding
length of a list in Python.
Example 4: Find length of an array using len()
brands = ["Coke", "Apple", "Google", "Microsoft", "Toyota"]
num_brands = len(brands)
print(num_brands)
When we run the above program, the output will be:
As seen from the above example, the len function gives the length of
array brands which is 5.
Add an element to an Array
To add a new element to an array, we use append() method in Python.
Example 5: Adding an element in an array using append()
add = ['a', 'b', 'c']
add.append('d')
print(add)
When we run the above program, the output will be
['a', 'b', 'c', 'd']
Here, we used append() method to add 'd'.
Remove elements from an Array
Python's list implementation of array allows us to delete any elements from an
array using del operator.
Similarly, we can also use remove() and pop() methods to remove elements in
an array.
Example 6: Removing elements of an array using del,
remove() and pop()
colors = ["violet", "indigo", "blue", "green", "yellow", "orange", "red"]
del color[4]
colors.remove("blue")
colors.pop(3)
print(color)
When we run the above program, the output will be
['violet', 'indigo', 'green', 'red']
Modify elements of an Array
We can change values of elements within an array using indexing and assignment
operator (=). We select the position of any element using indexing and use
assignment operator to provide a new value for the element.
Example 7: Modifying elements of an array using Indexing
fruits = ["Apple", "Banana", "Mango", "Grapes", "Orange"]
fruits[1] = "Pineapple"
fruits[-1] = "Guava"
print(fruits)
When we run the above program, the output will be:
['Apple', 'Pineapple', 'Mango', 'Grapes', 'Guava']
Python operators to modify elements in an Array
In Python arrays, operators like + , * can also be used to modify elements.
We can use + operator to concatenate (combine) two arrays.
Example 8: Concatenating two arrays using + operator
concat = [1, 2, 3]
concat + [4,5,6]
print(concat)
When we run the above program. the output will be:
[1, 2, 3, 4, 5, 6]
Similarly, we can use * operator to repeat the elements multiple times.
Example 8: Repeating elements in array using * operator
repeat = ["a"]
repeat = repeat * 5
print(repeat)
When we run the above program, the output will be
['a', 'a', 'a', 'a', 'a'
Slicing an Array
Python has a slicing feature which allows to access pieces of an array. We, basically,
slice an array using a given range (eg. 2nd to 5th position), giving us elements we
require. This is done by using indexes separated by a colon [x : y].
We can use negative indexing with slicing too.
Example 9: Slicing an array using Indexing
fruits = ["Apple", "Banana", "Mango", "Grapes", "Orange"]
print(fruits[1:4])
print(fruits[ : 3])
print(fruits[-4:])
print(fruits[-3:-1])
When we run the above program, the output will be:
['Banana', 'Mango', 'Grapes']
['Apple', 'Banana', 'Mango']
['Banana', 'Mango', 'Grapes', 'Orange']
['Mango', 'Grapes']
Python Array Methods
Other array operations are also available in Python using list/array methods given
as:
Methods Functions
append() to add element to the end of the list
extend() to extend all elements of a list to the another list
insert() to insert an element at the another index
remove() to remove an element from the list
pop() to remove elements return element at the given index
clear() to remove all elements from the list
index() to return the index of the first matched element
count() to count of number of elements passed as an argument
sort() to sort the elements in ascending order by default
reverse() to reverse order element in a list
copy() to return a copy of elements in a list
Multidimensional arrays
All arrays created above are single dimensional. We can also create a
multidimensional array in Python.
A multidimensional array is an array within an array. This means an array holds
different arrays inside it.
Example 10: Create a two-dimensional array using lists
multd = [[1,2], [3,4], [5,6], [7,8]]
print(multd[0])
print(multd[3])
print(multd[2][1])
print(multd[3][0])
When we run the above program, the output will be
[1, 2]
[7, 8]
6
7
Here, we have 4 elements and each elements hold another 2 sub-elements.
Basic array operations
So far so good, and it looks as if using a list is as easy as using an array.
The first thing that we tend to need to do is to scan through an array and
examine values. For example, to find the maximum value (forgetting for a
moment that there is a built-in max function) you could use:
m=0
for e in myList:
if m<e:
m=e
This uses the for..in construct to scan through each item in the list. This is a
very useful way to access the elements of an array but it isn't the one that most
programmers will be familiar with. In most cases arrays are accessed by index
and you can do this in Python:
m=0
for i in range(len(myList)):
if m<myList[i]:
m=myList[i]
or you could use the non-indexed loop and the index method:
m=0
for e in myList:
if m<e:
m=e
mi=myList.index(m)
print mi
LIST,SET,TUPLE AND DICTIONARY
A sequence is a datatype that represents a group of elements. The purpose of any sequence is to
store and process group elements. In python, strings, lists, tuples and dictionaries are very important
sequence datatypes.
LIST:
A list is similar to an array that consists of a group of elements or items. Just like an array, a list can store
elements. But, there is one major difference between an array and a list. An array can store only one
type of elements whereas a list can store different types of elements. Hence lists are more versatile
and useful than an array.
Creating a List:
Creating a list is as simple as putting different comma-separated values between square brackets.
student = [556, “Mothi”, 84, 96, 84, 75, 84 ]
We can create empty list without any elements by simply writing empty square brackets as:
student=[ ]
We can create a list by embedding the elements inside a pair of square braces []. The elements in the list
should be separated by a comma (,).
Accessing Values in list:
To access values in lists, use the square brackets for slicing along with the index or indices to obtain value
available at that index. To view the elements of a list as a whole, we can simply pass the list name to print
function.
Ex:
Ex-1:
numbers = [1,2,3,4,5]
for i in numbers:
print i,
Output:
12345
Deleting an element from the list can be done using ‘del’ statement. The del statement takes the position
number of the element to be deleted.
Example:
lst=[5,7,1,8,9,6]
del lst[3] # delete 3rd element from the list i.e., 8 print lst # [5,7,1,9,6]
If we want to delete entire list, we can give statement like del lst.
Concatenation of Two lists:
We can simply use „+‟ operator on two lists to join them. For example, „x‟ and „y‟ are two lists. If we wrte
x+y, the list „y‟ is joined at the end of the list „x‟.
Example: x=[10,20,32,15,16] y=[45,18,78,14,86]
print x+y # [10,20,32,15,16,45,18,78,14,86]
Repetition of Lists:
We can repeat the elements of a list „n‟ number of times using „*‟
operator. x=[10,54,87,96,45]
print x*2 # [10,54,87,96,45,10,54,87,96,45]
Membership in Lists:
We can check if an element is a member of a list by using „in‟ and „not in‟ operator. If the element is a
member of the list, then „in‟ operator returns True otherwise returns False. If the element is not in the list,
then „not in‟ operator returns True otherwise returns False.
Example: x=[10,20,30,45,55,65] a=20
print a in x # True a=25
print a in x # False a=45
print a not in x # False a=40
print a not in x # True
Aliasing and Cloning Lists:
Giving a new name to an existing list is called ‘aliasing’. The new name is called
‘alias name’. To provide a new name to this list, we can simply use assignment operator (=).
Example:
x = [10, 20, 30, 40, 50, 60]
y=x # x is aliased as y print x # [10,20,30,40,50,60] print y # [10,20,30,40,50,60]
x[1]=90 # modify 1st element in x print x # [10,90,30,40,50,60] print y #
[10,90,30,40,50,60]
In this case we are having only one list of elements but with two different names „x‟ and „y‟. Here, „x‟ is the
original name and „y‟ is the alias name for the same list. Hence, any modifications done to x‟ will also modify
„y‟ and vice versa.
Obtaining exact copy of an existing object (or list) is called „cloning‟. To Clone a list, we can take help of the
slicing operation [:].
Example:
x = [10, 20, 30, 40, 50, 60]
y=x[:] # x is cloned as y
print x # [10,20,30,40,50,60] print y # [10,20,30,40,50,60] x[1]=90 # modify 1 st element
in x print x # [10,90,30,40,50,60] print y # [10,20,30,40,50,60]
When we clone a list like this, a separate copy of all the elements is stored into „y‟. The lists „x‟ and „y‟ are
independent lists. Hence, any modifications to „x‟ will not affect „y‟and vice versa.
Methods in Lists:
Nested Lists:
A list within another list is called a nested list. We know that a list contains several elements. When we take
a list as an element in another list, then that list is called a nested list.
Example: a=[10,20,30] b=[45,65,a]
print b # display [ 45, 65, [ 10, 20, 30 ] ]
print b[1] # display 65
print b[2] # display [ 10, 20, 30 ]
print b[2][0] # display 10 print b[2][1] # display 20 print b[2][2] # display 30 for x in b[2]:
print x, # display 10 20 30
mat=[[1,2,3],[4,5,6],[7,8,9]]
for r in mat:
print r print "" m=len(mat) n=len(mat[0])
for i in range(0,m):
for j in range(0,n):
print mat[i][j], print ""
print ""
One of the main use of nested lists is that they can be used to represent matrices. A matrix represents a
group of elements arranged in several rows and columns. In python, matrices are created as 2D
arrays or using matrix object in numpy. We can also create a matrix using nested lists.
List Comprehensions:
List comprehensions represent creation of new lists from an iterable object (like a list, set, tuple, dictionary
or range) that satisfy a given condition. List comprehensions contain very compact code usually a single
statement that performs the task.
We want to create a list with squares of integers from 1 to 100. We can write code as:
squares=[ ]
for i in range(1,11):
squares.append(i**2)
The preceding code will create „squares‟ list with the elements as shown below:
[ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ] The previous code can rewritten in a
compact way as:
squares=[x**2 for x in range(1,11)]
This is called list comprehension. From this, we can understand that a list comprehension
consists of square braces containing an expression (i.e., x**2). After the expression, a fro loop and
then zero or more if statements can be written.
[ expression for item1 in iterable if statement1 for item1 in iterable if statement2
for item1 in iterable if statement3 …..]
Example:
Even_squares = [ x**2 for x
in range(1,11) if x%2==0 ] It will display the list even
squares as list.
[ 4, 16, 36, 64, 100 ]
TUPLE:
A Tuple is a python sequence which stores a group of elements or items. Tuples are similar to lists but the
main difference is tuples are immutable whereas lists are mutable. Once we create a tuple we cannot
modify its elements. Hence, we cannot perform operations like append(), extend(), insert(), remove(), pop()
and clear() on tuples. Tuples are generally used to store data which should not be modified and retrieve
that data on demand.
Creating Tuples:
We can create a tuple by writing elements separated by commas inside parentheses( ). The elements can be
same datatype or different types.
To create an empty tuple, we can simply write empty parenthesis, as:
tup=( )
To create a tuple with only one element, we can, mention that element in parenthesis and after that a
comma is needed. In the absence of comma, python treats the element assign ordinary data type.
tup = (10) tup = (10,)
print tup # display 10 print tup # display 10
print type(tup) # display <type „int‟> print type(tup) # display<type„tuple‟>
To create a tuple with different types of elements:
tup=(10, 20, 31.5, „Gudivada‟)
If we do not mention any brackets and write the elements separating them by comma, then they are taken
by default as a tuple.
tup= 10, 20, 34, 47
It is possible to create a tuple from a list. This is done by converting a list into a tuple using tuple function.
n=[1,2,3,4]
tp=tuple(n)
print tp # display (1,2,3,4)
Another way to create a tuple by using range( ) function that returns a sequence. t=tuple(range(2,11,2))
print t # display (2,4,6,8,10)
Accessing the tuple elements:
Accessing the elements from a tuple can be done using indexing or slicing. This is same as that of a list.
Indexing represents the position number of the element in the tuple. The position starts from 0.
tup=(50,60,70,80,90)
print tup[0] # display 50
print tup[1:4] # display (60,70,80)
print tup[-1] # display 90
print tup[-1:-4:-1] # display (90,80,70)
print tup[-4:-1] # display (60,70,80)
However, you can always delete the entire tuple by using the statement.
Note that this exception is raised because you are trying print the deleted element.
Operations on tuple:
Operation Description len(t) Return the length of tuple. tup1+tup2
Concatenation of two tuples.
Tup*n Repetition of tuple values in n number of times.
x in tup Return True if x is found in tuple otherwise returns False. cmp(tup1,tup2) Compare
elements of both tuples
max(tup) Returns the maximum value in tuple. min(tup) Returns the minimum value in
tuple. tuple(list) Convert list into tuple.
Returns how many times the element „x‟ is found in tuple.
tup.count(x)
Returns the first occurrence of the element „x‟ in tuple.
tup.index(x)
Raises ValueError if „x‟ is not found in the tuple.
Sorts the elements of tuple into ascending order. sorted(tup,reverse=True) will sort in
sorted(tup)
reverse order.
cmp(tuple1, tuple2)
The method cmp() compares elements of two tuples.
Syntax
cmp(tuple1, tuple2)
Parameters
tuple1 -- This is the first tuple to be compared
tuple2 -- This is the second tuple to be compared
Return Value
If elements are of the same type, perform the compare and return the result. If elements are different
types, check to see if they are numbers.
➢ If numbers, perform numeric coercion if necessary and compare.
➢ If either element is a number, then the other element is "larger" (numbers are
"smallest").
➢ Otherwise, types are sorted alphabetically by name.
If we reached the end of one of the tuples, the longer tuple is "larger." If we exhaust both tuples and share
the same data, the result is a tie, meaning that 0 is returned.
Example:
tuple1 = (123, 'xyz')
tuple2 = (456, 'abc') print cmp(tuple1, tuple2)
print cmp(tuple2, tuple1)
Nested Tuples:
#display -1
#display 1 Python allows you to define a tuple inside another tuple. This is called a nested tuple.
students=((“RAVI”, “CSE”, 92.00), (“RAMU”, “ECE”, 93.00), (“RAJA”, “EEE”, 87.00))
for i in students:
print i
Output: (“RAVI”, “CSE”, 92.00) (“RAMU”, “ECE”, 93.00) (“RAJA”, “EEE”, 87.00)
SET:
Set is another data structure supported by python. Basically, sets are same as lists but with a difference
that sets are lists with no duplicate entries. Technically a set is a mutable and an unordered collection of
items. This means that we can easily add or remove items from it.
Creating a Set:
A set is created by placing all the elements inside curly brackets {}. Separated by comma or by using the
built-in function set( ).
Syntax:
Set_variable_name={var1, var2, var3, var4, …….}
Example:
s={1, 2.5, “abc” }
print s # display set( [ 1, 2.5, “abc” ] )
Converting a list into set:
A set can have any number of items and they may be of different data types. set()
function is used to converting list into set.
s=set( [ 1, 2.5, “abc” ] )
print s # display set( [ 1, 2.5, “abc” ] ) We can also convert tuple or string into set.
tup= ( 1, 2, 3, 4, 5 )
print set(tup) # set( [ 1, 2, 3, 4, 5 ] )
str= “MOTHILAL”
print str # set( [ 'i', 'h', 'm', 't', 'o' ] )
Operations on set:
Sno Operation Result
1 len(s) number of elements in set s (cardinality)
2 x in s test x for membership in s
3 x not in s test x for non-membership in s
s.issubset(t) 4 (or)
s <= t s.issuperset(t)
5 (or)
s >= t
6 s==t
7 s ! = t s.union(t)
8 (or)
s|t s.intersection(t)
9 (or)
s&t
test whether every element in s is in t
new set with elements in either s or t but not both 12 s.copy() new set with a shallow copy of s
13 s.update(t) return set s with elements added from t
14 s.intersection_update(t) return set s keeping only elements also found in t
15 s.difference_update(t) return set s after removing elements found in t
s.symmetric_difference_up
16 return set s with elements from s or t but not both
date(t)
17 s.add(x) add element x to set s
18 s.remove(x) remove x from set s; raises KeyError if not present
19 s.discard(x) removes x from set s if present
remove and return an arbitrary element from s; 20 s.pop()
raises KeyError if empty 21 s.clear() remove all elements from set s
22 max(s) Returns Maximum value in a set
23 min(s) Returns Minimum value in a set
Return a new sorted list from the elements in the 24 sorted(s)
set.
To create an empty set you cannot write s={}, because python will make this as a directory. Therefore, to
create an empty set use set( ) function. s=set( ) s={}
print type(s) #display<type„set‟> print type(s) # display <type„dict‟>
Updating a set:
Since sets are unordered, indexing has no meaning. Set operations do not allow users to access or change
an element using indexing or slicing.
Dictionary:
A dictionary represents a group of elements arranged in the form of key-value pairs. The first element is
considered as „key‟ and the immediate next element is taken as its
„value‟. The key and its value are separated by a colon (:). All the key-value pairs in a dictionary are inserted
in curly braces { }.
d= { „Regd.No‟: 556, „Name‟:‟Mothi‟, „Branch‟: „CSE‟ }
Here, the name of dictionary is „dict‟. The first element in the dictionary is a string
„Regd.No‟. So, this is called „key‟. The second element is 556 which is taken as its „value‟.
Example:
d={„Regd.No‟:556,„Name‟:‟Mothi‟,„Branch‟:„CSE‟}print
d[„Regd.No‟] # 556 print d[„Name‟] # Mothi print d[„Branch‟] # CSE
To access the elements of a dictionary, we should not use indexing or slicing. For example,
dict[0] or dict[1:3] etc. expressions will give error. To access the value associated with a key,
we can mention the key name inside the square braces, as: dict[„Name‟].
If we want to know how many key-value pairs are there in a dictionary, we can use the len( )
function, as shown
d={„Regd.No‟:556,„Name‟:‟Mothi‟,„Branch‟:„CSE‟ } print len(d) #3
We can also insert a new key-value pair into an existing dictionary. This is done by mentioning the key and
assigning a value to it.
d={'Regd.No':556,'Name':'Mothi','Branch':'CSE'}
print d #{'Branch': 'CSE', 'Name': 'Mothi', 'Regd.No': 556}
d['Gender']="Male"
print d # {'Gender': 'Male', 'Branch': 'CSE', 'Name': 'Mothi', 'Regd.No': 556} Suppose, we want to delete a
key-value pair from the dictionary, we can use del statement as:
del dict[„Regd.No‟] #{'Gender': 'Male', 'Branch': 'CSE', 'Name': 'Mothi'}
To Test whether a „key‟ is available in a dictionary or not, we can use „in‟ and „not in‟
operators. These operators return either True or False.
„Name‟ in d # check if „Name‟ is a key in d and returns True / False
We can use any datatypes for value. For example, a value can be a number, string, list, tuple or another
dictionary. But keys should obey the rules:
➢ Keys should be unique. It means, duplicate keys are not allowd. If we enter same key again, the old key
will be overwritten and only the new key will be available.
emp={'nag':10,'vishnu':20,'nag':20}
print emp # {'nag': 20, 'vishnu': 20}
➢ Keys should be immutable type. For example, we can use a number, string or tuples as keys since they
are immutable. We cannot use lists or dictionaries as keys. If they are used as keys, we will get „TypeError‟.
emp={['nag']:10,'vishnu':20,'nag':20} Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
emp={['nag']:10,'vishnu':20,'nag':20} TypeError: unhashable type: 'list'
Dictionary Methods:
Method Description
d.clear() Removes all key-value pairs from dictionary„d‟.
d2=d.copy() Copies all elements from„d‟ into a new dictionary d2.
Created.fromkeys(s
a new dictionary with
[,v]keys)from sequence„s‟ and values all set to „v‟.
Returns the value associated
d.get(k [,v] ) with key „k‟. If key is not found, it returns „v‟.
Returns an object that contains key-value pairs of„d‟. The
pairs are stored as tuples in the object.
d.items()
d.keys() Returns a sequence of keys from the dictionary„d‟. d.values() Returns a sequence of
values from the dictionary„d‟. d.update(x) Adds all elements from dictionary „x‟ to„d‟.
Removes the key „k‟ and its value from„d‟ and returns the
d.pop(k [,v] )
value. If key is not found, then the value „v‟ is returned. If key is not found and „v‟ is not mentioned then
„KeyError‟ is raised. If key „k‟ is found, its value is returned. If key is not found, then the k, v pair is stored into
d.setdefault(k [,v] )
the dictionary„d‟.
Using for loop with Dictionaries:
for loop is very convenient to retrieve the elements of a dictionary. Let‟s take a simple dictionary that
contains color code and its name as:
colors = { 'r':"RED", 'g':"GREEN", 'b':"BLUE", 'w':"WHITE" }
Here, „r‟, „g‟, „b‟ represents keys and „RED‟, „GREEN‟, „BLUE‟ and „WHITE‟
indicate values.
colors = { 'r':"RED", 'g':"GREEN", 'b':"BLUE", 'w':"WHITE" }
for k in colors:
print k # displays only keys for k in colors:
print colors[k] # keys to to dictionary and display the values
When we have two lists, it is possible to convert them into a dictionary. For example, we have two lists
containing names of countries and names of their capital cities.
There are two steps involved to convert the lists into a dictionary. The first step is to create a „zip‟ class
object by passing the two lists to zip( ) function. The zip( ) function is useful to convert the sequences into a
zip class object. The second step is to convert the zip object into a dictionary by using dict( ) function.
Example:
countries = [ 'USA', 'INDIA', 'GERMANY', 'FRANCE' ] cities = [ 'Washington', 'New Delhi', 'Berlin', 'Paris' ]
z=zip(countries, cities)
d=dict(z)
print d
Output:
{'GERMANY': 'Berlin', 'INDIA': 'New Delhi', 'USA': 'Washington', 'FRANCE': 'Paris'}
Q) A Python program to create a dictionary with cricket player’s names and scores in a match. Also we are
retrieving runs by entering the player’s name.
n=input("Enter How many players? ")
d={}
for i in range(0,n):
k=input("Enter Player name: ")
v=input("Enter score: ")
d[k]=v print d
name=input("Enter name of player for score: ")
print "The Score is",d[name]
Python Turtle
Turtle Drawing
We can create cool images and graphics in Python using a module called turtle - a set of
ready-made functions designed for drawing shapes and lines.
A turtle is like a cursor that moves around your screen, leaving a line behind it. Turtles can draw
all kinds of shapes and pictures - you just need to give them the right commands.
Drawing a Circle
Firstly, we are going to draw a simple shape (a circle) using the turtle module.
● Import the turtle module.
import turtle
● Make a turtle and load it into a variable.
tina = turtle.Turtle()
We have named the turtle Tina, however, you can give the turtle any name you want.
● Set the colour that the turtle will use to draw the shape.
tina.color(‘blue’)
● Set the style of the turtle with a function called shape.
tina.shape(‘turtle’)
● Set the turtle’s speed, choosing a number between 1 and 100 (100 is the fastest).
tina.speed(10)
● Set the thickness of the line your turtle will draw.
tina.pensize(4)
● Now, tell your turtle to draw a circle.
tina.circle(60) # draws circle with radius of 60 pixels
Tasks:
1. Run the code above.
2. Fill the inside of the circle with a colour (same colour as the outline).
tina.fillcolor('blue')
tina.begin_fill()
tina.circle(60)
tina.end_fill()
3. Fill the inside of the circle with a different colour (different colour as the outline).
Drawing Location
Sometimes we may wish to move the turtle before we start drawing something so we can draw
shapes in different locations on the screen.
● Set up Tina the Turtle.
● Take the pen up off the page so Tina does not draw lines while moving to a different
location.
tina.penup()
● Tell Tina to go to a particular point on the screen by telling her the x-coordinate and the
y-coordinate.
tina.goto(30,-150) # x, y
Note: The screen has coordinates that go from -150 to 150 in the x (horizontal) and y
(vertical) directions.
Python Turtle
● Put the pen back down on the screen so Tina can start drawing.
tina.pendown()
● Start drawing your shape!
tina.circle(50)
Drawing a Square
We can also draw shapes other than circles. Although, they are a little bit more complicated to
draw. In order to draw other shapes, Tina must draw straight lines and then turn a certain
number of degrees and then repeat.
We are now going to draw a square using Tina the Turtle.
● Set up Tina like we did in the last lesson (import module, make turtle, set color, set
speed etc.).
● Now, tell Tina where to draw.
tina.forward(50) # go right 50 pixels
tina.right(90) # turn right 90 degrees
tina.forward(50) # go down 50 pixels
tina.right(90) # turn right 90 degrees
tina.forward(50) # go left 50 pixels
tina.right(90) # turn right 90 degrees
tina.forward(50) # go up 50 pixels
Tasks:
1. Run the code above.
2. Fill the square with a colour.
● Next, we need to name our turtle, and turtle will respond to whatever name you give it.
We are just going to name it “alfred”.
● After that, we can make alfred move forward, and we can do this by using the forward
command in turtle. Whatever number you put in the parentheses is how many pixels alfred
will move forward.
>> alfred.forward(40)
● Similarly, we can have alfred move backwards.
>> alfred.backward(40)
● We can also increase the speed of alfred by using the following command:
>> alfred.speed(100)
screen
>> = turtle.Screen()
● Next, we need to create functions that are going to be in charge of alfred moving up, down,
left, and right.
● Now we need to make alfred move in each direction when the corresponding key is
pressed, we can do this by using the following commands that call the functions we made
earlier:
>>screen.onkey(moveUp ,”Up”)
>>screen.onkey(moveDown, ”Down”)
>>screen.onkey(moveRight ,”Right”)
>>screen.onkey(moveLeft, ”Left”)
● Next, we need to make the Screen listen to the commands we are giving it
>>screen.listen()
Turtle Functions
- turtle.Turtle()
- Makes a Turtle
- turtle.Screen()
- Makes a Screen
- .forward(int)
- Moves Turtle Forward
- .backward(int)
- Moves Turtle Backward
- .left(int)
- Turns Turtle Left
- .right(int)
- Turns Turtle Right
- .color(string or int,int,int).
- Changes Turtle Color
- .penup().
- Enables the turtle to move around without drawing
- .pendown().
- Enables drawing
- .pensize(int)
- Changes Turtle Size
- .speed(int)
- Changes Turtle Speed
- .shape(string).
- Changes Turtle Shape
- .fillcolor(string)
- Sets to fill in something drawn by the turtle with a color
- .begin_fill().
- Starting spot for filling color
- .end_fill().
- Ending spot for filling color
- .xcor()
- Find X coordinate of Turtle
- .ycor()
- Find Y coordinate of Turtle
- .goto(int, int).
- Moves Turtle to a specific Spot
- .circle(int)
- Draws a Circle
- .setheading(int)
- Set orientation of the
Turtle
- .home().
- Send Turtle to 0, 0 and makes it go back to its starting orientation
- .undo().
- Undo the Turtle last actions
- .position()
- Returns Turtle’s position
- .towards(int, int)
- Returns the angle from the Turtle’s position to the position given
- .heading()
- Returns Turtle’s current heading
- .distance(int, int or turtle).
- Returns distance between turtle and given point or anothers turtle
- .degrees(int)
- Set Number of Degrees for a Full Circle
- .radians()
- Set Angle Measurement Units to Radians
- .isdown()
- Check to see if Pen is
Down or Up
- .reset().
- Delete All of Turtle’s Drawings, re-center Turtle, put everything back to default