INTRODUCTION TO PYTHON PROGRAMMING, Study notes of Introduction to Robotics

• Python is an object-oriented, high level language, interpreted, dynamic and multipurpose programming language. • Python is not intended to work on special area such as web programming. That is why it is known as multipurpose because it can be used with web, enterprise, 3D CAD etc. • We don’t need to use data types to declare variable because it is dynamically typed so we can write a=10 to declare an integer value in a variable. • Python makes the development and debugging fast because there is no compilation step included in python development

Typology: Study notes

2024/2025

Available from 04/21/2025

reagan-kinoti
reagan-kinoti 🇰🇪

14 documents

1 / 232

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
INTRODUCTION TO
PYTHON PROGRAMMING
2025
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download INTRODUCTION TO PYTHON PROGRAMMING and more Study notes Introduction to Robotics in PDF only on Docsity!

INTRODUCTION TO

PYTHON PROGRAMMING

CONTENTS

Chapter No. Title Page No

UNIT I

1. Introduction 01

2. Variables And Expression 13

3. Conditional Statements, Looping, Control Statements 26

UNIT II

4 Functions 42

5. Strings 59

UNIT III

6. List 75

7. Tuples And Dictionaries 88

8. Files And Exceptions 112

UNIT IV

9. Regular Expression 125

10. Classes And Objects 134

11. Multithreaded Programming 147

12. Module 157

UNIT V

13. Creating The GUI Form And Adding Widgets 169

14. Layout Management & Look & Feel Customization 192

15. Storing Data In Our Mysql Database Via Our GUI 213

Dictionary, Deleting Elements from Dictionary,

Properties of Dictionary keys, Operations in Dictionary,

Built-In Dictionary Functions, Built- in Dictionary

Methods

Files: Text Files, The File Object Attributes,

Directories

Exceptions: Built- in Exceptions, Handling Exceptions,

Exception with Arguments, User-defined Exceptions

IV Regular Expressions^ –^ Concept of regular expression,

various types of regular expressions, using match

function.

Classes and Objects: Overview of OOP (Object

Oriented Programming), Class Definition, Creating

Objects, Instances as Arguments, Instances as return

values, Built-in Class Attributes, Inheritance, Method

Overriding, Data Encapsulation, Data Hiding

Multithreaded Programming: Thread Module,

creating a thread, synchronizing threads, multithreaded

priority queue

Modules: Importing module, Creating and exploring

modules, Math module, Random module, Time module

V Creating the GUI Form and Adding Widgets:

Widgets: Button, Canvas, Checkbutton, Entry, Frame,

Label, Listbox, Menubutton, Menu, Message,

Radiobutton, Scale, Scrollbar, text, Toplevel, Spinbox,

PanedWindow, LabelFrame, tkMessagebox. Handling

Standard attributes and Properties of Widgets.

Layout Management: Designing GUI applications

with proper Layout Management features.

Look and Feel Customization : Enhancing Look and

Feel of GUI using different appearances of widgets.

Storing Data in Our MySQL Database via Our GUI

: Connecting to a MySQL database from Python,

Configuring the MySQL connection, Designing the

Python GUI database, Using the INSERT command,

Using the UPDATE command, Using the DELETE

command, Storing and retrieving data from MySQL

database.

UNIT I

1

INTRODUCTION

Unit Structure 1.0 Objectives

1.1 Introduction: The Python Programming Language

1.2 History

1.3 Features

1.4 Installing Python

1.5 Running Python program

1.6 Debugging

1.6.1 Syntax Errors 1.6.2 Runtime Errors 1.6.3 Semantic Errors 1.6.4 Experimental Debugging

1.7 Formal and Natural Languages

1.8 The Difference Between Brackets, Braces, and Parentheses

1.9 Summary

1.10 References

1.11 Unit End Exercise

1.0 OBJECTIVES

After reading through this chapter, you will be able to –

 To understand and use the basic of python.

 To understand the history and features of python programming.

 To understand the installation of python.

 To handle the basis errors in python.

 To understand the difference between brackets, braces and parenthesis.

1.1 INTRODUCTION: THE PYTHON

PROGRAMMING LANGUAGE

 Python is an object-oriented, high level language, interpreted, dynamic and multipurpose programming language.

 Python is not intended to work on special area such as web programming. That is why it is known as multipurpose because it can be used with web, enterprise, 3D CAD etc.

3. Support for GUI:

 GUI or Graphical User Interface is one of the key aspects of any programming language because it has the ability to add flair to code and make the results more visual.

 Python has support for a wide array of GUIs which can easily be imported to the interpreter, thus making this one of the most favorite languages for developers.

4. Object-Oriented Approach:

 One of the key aspects of Python is its object-oriented approach. This basically means that Python recognizes the concept of class and object encapsulation thus allowing programs to be efficient in the long run.

5. Highly Portable:

 Suppose you are running Python on Windows and you need to shift the same to either a Mac or a Linux system, then you can easily achieve the same in Python without having to worry about changing the code.

 This is not possible in other programming languages, thus making Python one of the most portable languages available in the industry.

6. Highly Dynamic

 Python is one of the most dynamic languages available in the industry today. What this basically means is that the type of a variable is decided at the run time and not in advance.

 Due to the presence of this feature, we do not need to specify the type of the variable during coding, thus saving time and increasing efficiency.

7. Large Standard Library:

 Out of the box, Python comes inbuilt with a large number of libraries that can be imported at any instance and be used in a specific program.

 The presence of libraries also makes sure that you don‘t need to write all the code yourself and can import the same from those that already exist in the libraries.

1.4 INSTALLING PYTHON

 To install Python, firstly download the Python distribution from official website of python (www.python.org/ download).

 Having downloaded the Python distribution now execute it.

 Setting Path in Python:

Before starting working with Python, a specific path is to set to set path follow the steps:

Right click on My Computer--> Properties -->Advanced System setting -->Environment Variable -->New

In Variable name write path and in Variable value copy path up to C:// Python (i.e., path where Python is installed). Click Ok ->Ok.

1.5 RUNNING PYTHON PROGRAM:

There are different ways of working in Python:

  1. How to Execute Python Program Using Command Prompt: If you want to create a Python file in .py extension and run. You can use the Windows command prompt to execute the Python code.

Example:

 Here is the simple code of Python given in the Python file demo.py. It contains only single line code of Python which prints the text ―Hello World!‖ on execution.

 So, how you can execute the Python program using the command prompt. To see this, you have to first open the command prompt using the ‗window+r‘ keyboard shortcut. Now, type the word ‗cmd‘ to open the command prompt.

 This opens the command prompt with the screen as given below. Change the directory location to the location where you have just saved your Python .py extension file.

 We can use the cmd command ‗cd‘ to change the directory location. Use ‗cd..‘ to come out of directory and ―cd‖ to come inside of the directory. Get the file location where you saved your Python file.

 To execute the Python file, you have to use the keyword ‗Python‘ followed by the file name with extension.py See the example given in the screen above with the output of the file.

3) Using IDLE (Python GUI) to Execute Python Program:

 Another useful method of executing the Python code. Use the Python IDLE GUI Shell to execute the Python program on Windows system.

 Open the Python IDLE shell by pressing the window button of the keyboard. Type ―Python‖ and click the ―IDLE (Python 3.7 32 bit)‖ to open the Python shell.

 Create a Python file with .py extension and open it with the Python shell. The file looks like the image given below.

 It contains the simple Python code which prints the text ―Hello World!‖. In order to execute the Python code, you have to open the ‗run‘ menu and press the ‗Run Module‘ option.

 A new shell window will open which contains the output of the Python code. Create your own file and execute the Python code using this simple method using Python IDLE.

1.6 DEBUGGING

 Debugging means the complete control over the program execution. Developers use debugging to overcome program from any bad issues.

 debugging is a healthier process for the program and keeps the diseases bugs far away.

 Python also allows developers to debug the programs using pdb module that comes with standard Python by default.

 We just need to import pdb module in the Python script. Using pdb module, we can set breakpoints in the program to check the current status

1.6.4 Experimental Debugging:

 One of the most important skills you will acquire is debugging. Although it can be frustrating, debugging is one of the most intellectually rich, challenging, and interesting parts of programming.

 Debugging is also like an experimental science. Once you have an idea about what is going wrong, you modify your program and try again.

 For some people, programming and debugging are the same thing. That is, programming is the process of gradually debugging a program until it does what you want.

 The idea is that you should start with a program that does something and make small modifications, debugging them as you go, so that you always have a working program.

1.7 FORMAL AND NATURAL LANGUAGES

 Natural languages are the languages people speak, such as English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally.

 Formal languages are languages that are designed by people for specific applications.

 For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules.

 Programming languages are formal languages that have been designed to express computations.

 Formal languages tend to have strict rules about syntax. For example, 3 + 3 = 6 is a syntactically correct mathematical statement.

 Syntax rules come in two flavors, pertaining to tokens and structure. Tokens are the basic elements of the language, such as words, numbers, and chemical elements.

 The second type of syntax rule pertains to the structure of a statement; that is, the way the tokens are arranged. The statement 3+ = 3 is illegal because even though + and = are legal tokens, you can‘t have one right after the other.

1.8 THE DIFFERENCE BETWEEN BRACKETS,

BRACES, AND PARENTHESES :

Brackets [ ]:

Brackets are used to define mutable data types such as list or list comprehensions.

Example:

To define a list with name as L1 with three elements 10,20 and 30

L1 = [10,20,30]

L

[10,20,30]

 Brackets can be used for indexing and lookup of elements

Example:

L1[1] = 40

L

[10,40,30]

Example: To lookup the element of list L

L1[0]

10

 Brackets can be used to access the individual characters of a string or to make string slicing

Example:

Lookup the first characters of string

str>>>‘mumbai‘

str [0]

‗m‘

Example: To slice a string

str [1:4]

‗umb‘

Braces {}

 Curly braces are used in python to define set or dictionary.

Example:

Create a set with three elements 10,20,30.

s1 = {10,20,30}

type(s1)

<class ‗set‘>

Example:

Create a dictionary with two elements with keys, ‗rollno‘ and ‗name‘

d1= {‗rollno‘:101, ‗name‘:‘ Vivek‘}

type(d1)

<class ‗dict‘>

 Brackets can be used to access the value of dictionary element by specifying the key.

d1[‗rollno‘]

101

For example, if you enter print in the search window, the first link that appears is the documentation of the print statement. At this point, not all of it will make sense to you, but it is good to know where it is.

  1. Start the Python interpreter and type help () to start the online help utility. Or you can type help ('print') to get information about the print statement.

2

VARIABLES AND EXPRESSION

Unit Structure

2. 0 Objectives

2. 1 Introduction

2. 2 Values and Types

2.2. 1 Variables

2.2. 2 Variable Names and Keywords

2. 3 Type conversion

2.3. 1 Implicit Type Conversion

2.3. 2 Explicit Type Conversion

2. 4 Operators and Operands

2. 5 Expressions

2. 6 Interactive Mode and Script Mode

2. 7 Order of Operations

2. 8 Summary

2. 9 References

2. 10 Unit End Exercise

2.0 OBJECTIVES

After reading through this chapter, you will be able to –

 To understand and use the basic datatypes of python.

 To understand the type conversion of variables in python

programming.

 To understand the operators and operands in python.

 To understand the interactive mode and script mode in python.

 To understand the order of operations in python.

2.1 INTRODUCTION

 Variables in a computer program are not quite like mathematical

variables. They are placeholders for locations in memory.

 Memory values consists of a sequence of binary digits (bits) that can

be 0 or 1, so all numbers are represented internally in base 2.

 Names of variables are chosen by the programmer.

 A common way to represent variables on paper is to write the name

with an arrow pointing to the variable‘s value.

>>> type(message)

<type ‗str‘>

>>> type(n)

<type ‗int‘>

>>> type(pi)

<type ‗float‘>

2.2.2 Variable Names and Keywords:

 Programmers generally choose names for their variables that are

meaningful they document what the variable is used for.

 Variable names can be arbitrarily long. They can contain both letters

and numbers, but they have to begin with a letter. It is legal to use

uppercase letters, but it is a good idea to begin variable names with a

lowercase letter.

 The underscore character, _, can appear in a name. It is often used in

names with multiple words, such as my_name or

airspeed_of_unladen_swallow.

 If you give a variable an illegal name, you get a syntax error:

>>> 76mumbai= 'big city'

SyntaxError: invalid syntax

>>> more@ = 1000000

SyntaxError: invalid syntax

>>> class = 'Advanced python'

SyntaxError: invalid syntax

 76mumbai is illegal because it does not begin with a letter. more@ is

illegal because it contains an illegal character, @. But what‘s wrong

with class?

 It turns out that class is one of Python‘s keywords. The interpreter uses

keywords to recognize the structure of the program, and they cannot be

used as variable names.

 Python has a lot of keywords. The number keeps on growing with the

new features coming in python.

 Python 3.7.3 is the current version as of writing this book. There are

35 keywords in Python 3.7.3 release.

 We can get the complete list of keywords using python interpreter help

utility.

 $ python3.7

>>> help ()

help> keywords

Here is a list of the Python keywords. Enter any keyword to get more

help.

False class from or

None continue global pass

True def if raise

and del import return

as elif in try

assert else is while

async except lambda with

await finally nonlocal yield

break for not

 You might want to keep this list handy. If the interpreter complains

about one of your variable names and you don‘t know why, see if it is

on this list.

2.3 TYPE CONVERSION

The process of converting the value of one data type (integer, string, float,

etc.) to another data type is called type conversion. Python has two types

of type conversion.

2.3.1 Implicit Type Conversion:

 In Implicit type conversion, Python automatically converts one data

type to another data type. This process doesn't need any user

involvement.

 example where Python promotes the conversion of the lower data type

(integer) to the higher data type (float) to avoid data loss.

Example 1: Converting integer to float

num_int = 123

num_flo = 1.

num_new = num_int + num_flo

print ("datatype of num_int:‖, type(num_int))

print ("datatype of num_flo:‖, type(num_flo))

print ("Value of num_new:‖, num_new)

print ("datatype of num_new:‖, type(num_new))

When we run the above program, the output will be:

datatype of num_int: <class 'int'>

datatype of num_flo: <class 'float'>

Value of num_new: 124.

datatype of num_new: <class 'float'>