INDEX
Chapter
TOPIC PAGE NO
No
1 Introduction to python 1
2 Python Fundamentals 6
3 Functions 12
4 Turtle 21
5 Draw moving object using Python Turtle 25
CHAPTER - I
INTRODUCTION TO PYTHON
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software
development.
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional
way.
The most recent major version of Python is Python 3, which we shall be using in this
tutorial. However, Python 2, although not being updated with anything other than
security updates, is still quite popular.
In this tutorial Python will be written in a text editor. It is possible to write Python in
an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or
Eclipse which are particularly useful when managing larger collections of Python
files.
3
Python Syntax compared to other programming languages
• Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets
for this purpose.
Example
print("Hello, World!")
Installation:
There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software
from [Link]
Steps to be followed and remembered:
Step 1: Select Version of Python to Install.
Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional)
4
Working with Python
There are two modes for using the Python interpreter:
• Interactive Mode
• Script Mode
Script Mode
Script mode is where you write your code in a .py file and then run it with the python
command. This is the most common way that people use Python because it lets you write and
save your code so that you can use it again later.
Interactive Mode
Interactive mode is where you type your code into the Python interpreter directly. This is
useful for trying out small snippets of code, or for testing things out as you’re writing them.
Advantages and Disadvantages of Script Mode
Script mode is a great way to automate tasks and run commands on a remote server. Script
mode can also be used to create files that will execute certain commands when they are run.
This can be very helpful in automating tasks or setting up a development environment.
There are some disadvantages to using script mode, however. First, if something goes wrong
with the script, it can be difficult to troubleshoot. Second, if you are not familiar with scripting
languages, it can be difficult to write a script that does what you want it to do. Finally, scripts
can be slow because they have to execute all of their commands serially.
Advantages and Disadvantages of Interactive Mode
The interactive mode is great for testing out commands and getting immediate feedback. It can
also be used to quickly execute commands on a remote server. The main disadvantage of
interactive mode is that it can be difficult to automate tasks. For larger programs, the
interactive mode is not suitable. Moreover, editing the program in interactive mode is a
tedious task.
Differences between Scripts mode and Interactive Mode
Script mode and Interactive mode can be differentiated on the basis of definition, suitability,
edit, output, save, and examples.
Definition: Script mode is a defined set of steps that need to be followed in order for the
computer to understand and carry out the instructions. Interactive mode, on the other hand, is
where the user can type in commands and see the results straight away.
5
Suitability: Script
ipt mode is more suitable when there is a need to automate tasks or when the
same task needs to be carried out several times. The interactive mode is more suitable for one-
one
time tasks or for exploring data.
Edit: Script mode is usually edited in a text edit
editor
or and then run as a batch process. Interactive
mode can be edited in the same way as commands are typed in, which makes it more user- user
friendly.
Output: Script mode produces output that can be saved and reused. Interactive mode produces
output that is displayed
ayed on the screen and then disappears.
Save: Script mode can be saved in a text file. Interactive mode cannot be saved, but the user
can type commands in an editor and save it as a script file.
Examples: Script mode examples can be found on the internet. Interactive mode examples can
be found by typing “interactive mode” in the Google search bar.
6
CHAPTER - II
PYTHON FUNDAMENTALS
Python Data Types are used to define the type of a variable. It defines what type of
data we are going to store in a variable. The data stored in memory can be of many types.
For example, a person's age is stored as a numeric value and his or her address is stored
as alphanumeric characters.
Python has various built-in data types which we will discuss with in this tutorial:
• Numeric - int, float, complex
• String - str
• Sequence - list, tuple, range
• Binary - bytes, bytearray, memoryview
• Mapping - dict
• Boolean - bool
• Set - set, frozenset
• None - NoneType
Python Numeric Data Type
Python numeric data types store numeric values. Number objects are created when
you assign a value to them. For example −
var1 = 1
var2 = 10
var3 = 10.023
Python supports four different numerical types −
• int (signed integers)
• long (long integers, they can also be represented in octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)
Python String Data Type
Python Strings are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
7
repetition operator in Python. For example −
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
This will produce the following result −
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python String Data Type
Python Strings are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator in Python. For example −
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
This will produce the following result −
Hello World!
H
llo
8
llo World!
Hello World!Hello World!
Hello World!TEST
Python Dictionary
Python dictionaries are kind of hash table type. They work like associative arrays
or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost
any Python type, but are usually numbers or strings. Values, on the other hand, can be
any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]). For example −
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print ([Link]()) # Prints all the keys
print ([Link]()) # Prints all the values
This produce the following result −
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
9
CHAPTER - III
FUNCTIONS
A function is a block of code which only runs when it is called. You can pass data,
known as parameters, into a function. A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Function Arguments
You can call a function by using the following types of formal arguments −
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function
definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a
syntax error as follows −
Example:-
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
10
return;
# Now you can call printme function
printme()
Output:-
Traceback (most recent call last):
File "[Link]", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in
a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters. You
can also make keyword calls to the printme() function in the following ways −
Example:-
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme( str = "My string")
Output:-
My string
Default arguments
A default argument is an argument that assumes a default value if a value is not provided
in the function call for that argument. The following example gives an idea on default
arguments, it prints default age if it is not passed −
Example:-
#!/usr/bin/python
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
11
return;
printinfo( age=50, name="miki" )
printinfo( name="miki" )
Output:-
Name: miki
Age 50
Name: miki
Age 35
Variable-length arguments
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified
during the function call. Following is a simple example −
Example:-
#!/usr/bin/python
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
printinfo( 10 )
printinfo( 70, 60, 50 )
Output is:
10
Output is:
70
60
50
12
CHAPTER - IV
TURTLE
“Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all
over it! We can use functions like [Link](…) and [Link](…) which can move the
turtle around. Commonly used turtle methods are :
Method Parameter Description
Turtle() None Creates and returns a new turtle object
forward() amount Moves the turtle forward by the specified
amount
backward() amount Moves the turtle backward by the specified
amount
right() angle Turns the turtle clockwise
left() angle Turns the turtle counterclockwise
penup() None Picks up the turtle’s Pen
pendown() None Puts down the turtle’s Pen
up() None Picks up the turtle’s Pen
down() None Puts down the turtle’s Pen
13
Method Parameter Description
color() Color Changes the color of the turtle’s pen
name
fillcolor() Color Changes the color of the turtle will use to fill
name a polygon
heading() None Returns the current heading
position() None Returns the current position
goto() x, y Move the turtle to position x,y
begin_fill() None Remember the starting point for a filled
polygon
end_fill() None Close the polygon and fill with the current
fill color
dot() None Leave the dot at the current position
stamp() None Leaves an impression of a turtle shape at the
current location
shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or
‘circle’
Plotting using Turtle
To make use of the turtle methods and functionalities, we need to import turtle.”turtle”
14
comes packed with the standard Python package and need not be installed externally. The
roadmap for executing a turtle program follows 4 steps:
Import the turtle module
Create a turtle to control.
Draw around using the turtle methods.
Run [Link]().
So as stated above, before we can use turtle, we need to import it. We import it as :
from turtle import *
# or
import turtle
After importing the turtle library and making all the turtle functionalities available to us,
we need to create a new drawing board(window) and a turtle. Let’s call the window as wn
and the turtle as skk. So we code as:
wn = [Link]()
[Link]("light green")
[Link]("Turtle")
skk = [Link]()
Now that we have created the window and the turtle, we need to move the turtle. To move
forward 100 pixels in the direction skk is facing, we code:
[Link](100)
We have moved skk 100 pixels forward, Awesome! Now we complete the program with the
done() function and We’re done!
[Link]()
So, we have created a program that draws a line 100 pixels long. We can draw various
shapes and fill different colors using turtle methods. There’s plethora of functions and
programs to be coded using the turtle library in python. Let’s learn to draw some of the basic
shapes.
15
DRAW MOVING OBJECT USING PYTHON TURTLE
# import turtle package
import turtle
# function for movement of an object
def moving_object(move):
# to fill the color in ball
[Link]('orange')
# start color filling
move.begin_fill()
# draw circle
[Link](20)
# end color filling
move.end_fill()
# Driver Code
if __name__ == "__main__" :
# create a screen object
screen = [Link]()
# set screen size
[Link](600,600)
# screen background color
[Link]('green')
# screen updaion
[Link](0)
# create a turtle object object
move = [Link]()
# set a turtle object color
[Link]('orange')
# set turtle object speed
[Link](0)
# set turtle object width
[Link](2)
# hide turtle object
[Link]()
16
# turtle object in air
[Link]()
# set initial position
[Link](-250, 0)
# move turtle object to surface
[Link]()
# infinite loop
while True :
# clear turtle work
[Link]()
# call function to draw ball
moving_object(move)
# update screen
[Link]()
# forward motion by turtle object
[Link](0.5)
Output
17