Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
114 views

Manual of Python

The document provides an introduction to the Python programming language. It discusses Python's history and features, and covers common data types and operators. The document includes 10 chapters that cover topics like data types, operators, control statements, functions, objects and classes, files, and GUI programming. It also introduces the PyCharm IDE for Python development.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views

Manual of Python

The document provides an introduction to the Python programming language. It discusses Python's history and features, and covers common data types and operators. The document includes 10 chapters that cover topics like data types, operators, control statements, functions, objects and classes, files, and GUI programming. It also introduces the PyCharm IDE for Python development.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Introduction to Python Programming

Table of contents
Chapter 1: Introduction to Python
Chapter 2: Data Types
Chapter 3: Operators
Chapter 4: Objects or sequences
Chapter 5: Control and loop Statements
Chapter 6: Functions
Chapter 7: Objects and Classes
Chapter 8: Files
Chapter 9: GUI using TKinter
Chapter 10: Data Analysis

Chapter 1: Introduction to Python


Python Name - Famous Tv Show Monty python's flying circus
Python is
 General-purpose

 interpreted

 interactive

 high-level programming language
The main advantage of python is open source under GNU General Public Licence. It is an
interpreted language means the code is processed at runtime, similar to PERL and PHP.
Python also supports object-oriented similar to other high level programming languages like
c++, java that encapsulate code within the object. For beginners to learn programming,
python is correct choice.

1.1 History:
Python is introduced by Guido Van Rossum during during 1985 to 1990 at National Research
Institute for Mathematics and Computer Science in the Netherlands. It is derived from many
other languages including ABC, modula-3, c, c++, Unix etc.
1.2 Features:
 Easy to learn

 Easy to read

 Easy to maintain

 Broad standard library

 Interactive mode

 Portable

 Extendable

 Databases

 GUI Programming

 Scalable
Python supports functional and Structured programming methods as well as oop. It is also
Used as a Scripting Language or can be compiled to byte code for building large applications.
It provides high level dynamic datatype and supports dynamic type checking. Python
supports automatic garbage collections and easily integrated with other languages like c, c++,
java

1.3 Use Case:


 YouTube Originally it is written in Python and MySQL

 Dropbox web-based file hosting service

 Yahoo maps uses python

 Google Many components of google search engine written in python

 YUM Package management utility in Linux OS

 Zope Corp Blue Bream (a powerful web application server)

1.4 What you can do with python?


 Shell scripting

 Gaming programming

 Windows development

 Testing code

 Web development
1.5 Special Features:
 Interpreter (Learning made easy)

 Supports Object Oriented Programming

 Other libraries can be attached in python

 Python libraries can be attached with other languages

 Extensive Library

 Open Source

1.6 Versions of Python


 CPython (Original)

 Cython (Compatible for c program)

 Jython (JVM based Code)

 IronPython (C# .Net)

1.7 Mode of Python Programming:


1. Interactive mode
2. Script mode

1. Interactive mode:
You can write python code using python command line interpreter
Goto command prompt
c:> python
- Command prompt
>>>print ("Hello World!") - Version 3.5 and above
If you are using python version 2.x, you can specify string without brackets

>>> print "Hello World!" - Version 2.7 and lower


Use Python as a calculator
>>> 25+653+12.5
690.5
To exit from python prompt use exit function
>>> exit() or control+Z

2. Script mode:
Use notepad or notepad++ to write scripts
Open new notepad file and add the below statements
print ("Hello World")
a = 10
b = 20
c = a+b
print ("The result of c is: ", c)
Now save the file as Sample.py
Change the directory to file location
> cd E:\python\example>
> dir : It shows all the files in the current directory
> type sample.py : To display file content
> cls : To clear screen
> python sample.py : To execute the script file

1.8 Pycharm:
PyCharm is a cross-platform editor developed by JetBrains. Pycharm provides all the
tools you need for productive Python development.

Installing Pycharm
To download PyCharm visit the website
https://www.jetbrains.com/pycharm/download/ and Click the "DOWNLOAD" link under the
Community Section.
Features:
Be More Productive
Save time while PyCharm takes care of the routine. Focus on the bigger things and embrace the
keyboard-centric approach to get the most of PyCharm’s many productivity features

Get Smart Assistance


PyCharm knows everything about your code. Rely on it for intelligent code completion, on-
the-fly error checking and quick-fixes, easy project navigation, and much more.
Boost Code Quality
Write neat and maintainable code while the IDE helps you keep control of the quality with
PEP8 checks, testing assistance, smart refactoring, and a host of inspections.
Simply All You Need
PyCharm is designed by programmers, for programmers, to provide all the tools you need
for productive Python development.

Chapter 2: Data Types


2.1 Memory Operations
 No declaration

 Store values in variable name

 Retrieve value

 Delete variable (del)

 Constants / arithmetic operations decide variable types
Example:
>>> 10
>>> a = 10
>>> del(a)

Types:
 Int

 Float

 String

 Boolean

Numbers:
- int (10)
- long (0122L) - in python3 no long datatype
- float (15.20)
- Complex (3.4j) - j might be lower case or upper case
- Type conversion
- int()
- float()
- long()
- complex()
Example:
a = int(10)
print(a)
10
b = float("10.56")
print(b)
10.56 -- automatically converts string into float
a+b
Chapter 3: Operators
Operators are the constructs, which can manipulate the value of operands
Example:
>>> 4 * 5 = 20

2.1 Types of Operators:


• Arithmetic Operators
• Relational/Comparison Operators
• Assignment Operators
• Bitwise Operators
• Logical Operators
• Membership Operators
• Identity Operators

2.1.1 Arithmetic Operators



Addition (+) Add two operands and unary plus

Subtraction (-) Subtract right operand from the left or unary

minus Multiply ( * ) Multiply two operands

Divide ( / ) Divide left operand by the right one (always results into float)

Modulus ( % ) remainder of the division of left operand by the right

Floor Division(//) division that results into whole number adjusted to the left in the
number line

Exponent ( ** ) left operand raised to the power of right operand

Example:
2.1.2 Comparison Operator
These Operators compare the values on either sides of them and decide the relation
among them.
 Equal (==)

 Not equal (!=)

 Greater than (>)

 Less than (<)

 Greater than or equal to (>=)

 Less than or equal to (<=)

Example:

2.1.3 Assignment Operators


An Assignment Operator is the operator used to assign a new value to a variable.
o Assign ( = )
o Add AND ( += )
o Multiply AND ( *= )
o Subtract AND ( -= )
o Divide AND ( /= )
o Modulus AND ( %= )
o Exponent AND ( **= )

Example:

2.1.4 Bitwise Operator:


Bitwise operator works on bits and performs bit-by-bit operation bin() can be used
to obtain binary representation of an integer number
Operator Description Example

& Operator copies a bit, (a & b) (means 0000 1100)


to the result, if it exists
in both operands

| It copies a bit, if it (a | b) = 61 (means 0011 1101)


exists in either operand.

^ It copies the bit, if it is (a ^ b) = 49 (means 0011 0001)


set in one operand but
not both.

~ (~a ) = -61 (means 1100 0011 in 2's


complement form due to a signed
It is unary and has the binary number.
effect of 'flipping' bits.

<< The left operand's value a << 2 = 240 (means 1111 0000)
is moved left by the
number of bits
specified by the right
operand.

>> The left operand's value a >> 2 = 15 (means 0000 1111


is moved right by the
number of bits
specified by the right
operand.

3 Logical Operator:
2.1.5 Membership Operator:
These Operators are used to test whether a value or a variable is found in
a sequence (Lists, Tuples, Sets, Strings, Dictionaries)

OPERATOR DESCRIPTION EXAMPLE

True if value/variable is found in the


in 5 in x
sequence

True if value/variable is not found in


not in 4 not in x
the sequence

Chapter 4: Sequences
4.1 What are sequences?
Sequences are containers with items that are accessible by indexing or slicing
The built-in len() function takes any container as an argument and returns the number of
items in the container.
4.2 Sequence Operations:
 Concatenation - Combine multiple sequences together

 Repetition - To repeat particular sequence multiple times

 Membership Testing - To check the item is belonging to the particular seq

 Slicing - To slice particular range

 Indexing - Index value for each item (Index starting from 0)

4.3 Types of Sequences in Python:


1. Lists
2. Strings
3. Dictionaries
4. Tuples
5. Sets
1. List:
 List is the most versatile data type in python

 It can be written as a list of comma-separated values between square brackets

 Items in a list need not be a same data type

 Similar to arrays in c (but arrays can store similar datatype)
Example: Fruit = ['mango', 'apple', 'orange']
Operations:
 list.append(elem) - To store the new element after the last one

 list.insert(index, elem) - To define where you want to store the value

 list.extend(list2)

 list.index(elem)

 list.remove(elem)

 list.sort()

 list.reverse()

Example:
Subjects = ['physics', 'Chemistry', 'Maths']
Games = ['Football', 'Cricket', 'Tennis']
Subjects.append('History') #append operation
print(Subjects)
Subjects.insert(1, 'History') # TO insert into the second position
print(Subjects)
Subjects.extend(Games)
print(Subjects)
Subjects.remove('Chemistory')
print(Subjects)
Subjects.reverse() # it prints the elements in the reverse order
print(Subjects)
print(Subjects + Games) # Similar to Subjects.extend(Games)

# Repeat the list twice


print(Subject * 2)
Example:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
['abcd', 786, 2.23, 'john', 70.2]
print (list[0]) # Prints first element of the list
abcd
print (list[1:3]) # Prints elements starting from 2nd till 3rd
[786, 2.23]
print (list[2:]) # Prints elements starting from 3rd element
[2.23, 'john', 70.2]
print (tinylist * 2) # Prints list two times
[123, 'john', 123, 'john']
print (list + tinylist) # Prints concatenated lists
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
del list[2]
print(list)
list.append("rahul")
print(list)
2. Strings:
- Single quote 'Hello World'
- Double quote "Hello World"
- Accessing String
- Whole string
- Sub string
- Escape Characters '\r', '\n', '\t' etc.
- Escape Characters - '\xnn' for hexa decimal
Example: Fruit = 'Mango'
Operations:
slicing - string[range]
Updating - string[range] + 'x'
Concatenation - String 1 + String 2
Repetition - String 1 * 2
Membership - In, Not in
Reverse - String[:-1]
stg = 'Keep the blue flag flying high'
print(stg.__len__()) - TO print length of the characters
print(stg.index('b')) - TO print index value of character 'b'
print(stg.count('f')) - TO check number of times character 'f' repeated
print(stg[0:4]) - To print first 4 characters (4 is ignored)
print(stg[::-1]) - To reverse the string
print(stg.upper()) - To print in upper case
print(stg * 2) - To print the statements twice
print(stg + 'XXXX') - To concatenate two strings
Membership testing:
if 'P' in stg:
print('It is an element')
Example:
name = 'My name is XXXX'
print (name)
My name is XXXX
name
'My name is XXXX' -- it represents variable type
a = 10
a
10
b = float(10)
b
10.0
c = 10L
c
10L
type (c) -- to display variable type
substring:
name [0] - it prints 1st character from the string 'M'

name[1] - it prints last character from the string 'i'

name[2] - It prints empty string


''
name[0:2] - 0-inclusive, 2-exclusive
'My'
name[0:3]
'My '
name[3:7]
'name'
name[-4:-1]
'XXX'
name[-4:]
'XXXX'
b = '\x10'
b
'\x10'
print(b)
b = 'Hello World\x11'
b
'Hello World\x11'
3. Dictionaries:
- Unordered collection of key-value pair
- It is generally used when we have huge amount of data
- Denoted by {}
Example:
d = {1:'value','key':2}
print(type(d))
print("d[1]=", d[1])
operations:
Length
del
membership testing
demo:
Student = {'Name':'XXXX', 'Age':33}
print(Student)
print(Student['Name']) - To print value of 'Name' key
Student['Gender'] = 'Male' - To add one more key-value pair to existing dic
print(Student)
Student.pop('Name') - To remove name key value pair

Student.clear() - To clear all key value in a dict or del a dict


Student['Name'] = 'Santhosh' - To change the name value
4. Tuples:
-- A tuple is a sequence of immutable Python objects
-- The tuples cannot be changed
-- Tuples are faster than list
fruits = ('Mango','Apple', 'Grapes')
Operations:
Index - Tuple.index()
Sclicing - Tuple[range]
Concatenation - Tuple1+Tuple2
Repetition - Tuple * 2
Count - Tuple.count(elem)
Example:
Cricket = ('Dhoni', 'Sachin', 'Virot')
Football = ('Hazard', 'Lampard', 'Terry')
Cricket.append('Dravid')
print(Football) -- Error because it is updatable
# indexing

print(Cricket[1])
print(Cricket.index('Virot')) -- To print particular element index
# Slicing
print(Football[0:2]) -- 0 - Starting, 2 - means actually (2-1)
# Concatenation
FoodCric = Football + Cricket
print(FoodCric)
# Repetition
print(Cricket * 2)
# count
print(Football.count('Hazard'))
Question:
Football = [('Dhoni', 'Sachin', 'Virot'),('Hazard', 'Lampard', 'Terry')]
-- In the above example how the indexing will be created
-- Football is a List which contains 2 tuples
-- Football list index is 0 and 1
-- 0 - tuples index ( 0, 1, 2)
-- 1 - tuple index (0,1,2)
Now i want o print 'Lampard'
print(Football[1][1])
Now i want to print 'Virot'
print(Football[0][2])
Example 2:
Points = [(1,2),(3,4),(6,7)]
Points.append((5,6))
print(Points)
Points.remove((1,2))
print(Points)
5. Sets:
-- A set contains an unordered collection of unique and immutable objects(unchanged).
-- Sets are denoted by '{}'

Add element
clear
copy
Difference
Discard
Remove
Intersection

print(Set1)
Set1 = {1,2,3,4,5,6}
Set1.discard(4) - To discard element 4
print(Set1)
print(Set1 | Set2) - Union Operation(Adding)
print(Set1 & Set2) - Intersection (prints common elements
print(Set1 - Set2) - Difference
print(Set1 ^ Set2) - Symmetric difference (Except common elements in both
sets)
Can we convert list into set?
list1 = [1,2,3,4,5,6,5,6,7,8]
print(list1)
Set3 = set(list1)
print(Set3)
If you want to convert list into tuple:
list1 = [1,2,3,4,5,6,5,6,7,8]
tup = tuple(list1)
print(tup)

Chapter 5: Control and loop Statements


Why to use loop?
If a software developer develops a software module for payroll processing that needs
to compute the salaries and the bonus of all the employees.
Example:
salary + bonus = Total salary -> emp1
salary + bonus = Total salary -> emp2
salary + bonus = Total salary -> emp3 write
logic to calculate total salary of all employees
What are loops?
 loops allow the execution of the statement or a group of statement multiple times.

 In order to enter the loop certain conditions are defined in the beginning

 Once the condition becomes false the loop stops and the control moves out of the
loop.

 pre-test & Post-test loops

 If the condition is checked before the loop enters

 Condition is checked after the loops ends

 In python, there is no post-test loops

Types of Loops in Python


1. While
2. For
3. Nested
1. While:
 Indefinite or conditional loops.

 It will keep iterating until certain conditions are met

 There is no guarantee ahead of time regarding how many times the loop will iterate.
Syntax:
while expression:
statements
Example:
count = 0
while conunt < 9:
print("Number: ", count)
count = count + 1;
print ("Print the Numbers")
- When you don't know how many iterations oare required, use while loop

2. For Loop:
 Repeats the group of statements a specific number of times

 For loops provides the syntax where the following information is
provided: o Boolean condition

o Initialization of the counting variable
o Incrementation of counting variable
Syntax:
for <variable> in <range>:
statement 1;
statement 2;
statement n;
Example 1:
Fruits = ["Mango", "Apple", "Orangle"]
for fruit in Fruits:
print ("Current fruit is: ", fruit)
print("Good bye")
Example 2:
num = int(input("Number: "))
factorial = 1
if num < 0:
print("must be positive")
elif num == 0:
print("factorial = 1")
else:
for i in range(1, num+1):
factorial = factorial * i
print(factorial)

3. Nested Loop:
 Allows use of loop inside another loop

 Use for loop inside a for loop

 Use while loop inside a while loop
Example: Simulate bank ATM
- ENter 4 digit pin -> check a balance
-> Make a Withdrawl
-> Pay In
-> Return Card
print("Welcome to ATM")
restart = ('Y')
chances = 3
balance = 67.14
while chances >= 0:
pin = int(input('Please enter your 4 digit pin:'))
if pin == (1234):
print('You entered your Pin Correctly \n')
while restart not in ('n', 'no', 'No','N'):
print("Please press 1 for your Balance \n")
print("Please press 2 for your Withdrawl \n")
print("Please press 3 for your Pay in \n")
print("Please press 4 for your Return Card \n") option
= int (input ('What would you like to choose?')) if
option == 1:
print('Your balance is Rs.', balance,'\n')
restart = input('Would you like to go back?')
if restart in ('n', 'no', 'No','N'):
print('Thank you')
break
elif option == 2:
option2 = ('Y')
Withdrawl = float(input('How much would you like to withdraw? \n
Rs.10/Rs.20/Rs.40/Rs.60/Rs.80/Rs.100')
if Withdrawl in [10,20,40,60,80,100]:
balance = balance - Withdrawl
print("\n your balance is now Rs.", balance)
if restart in ('n', 'no', 'No','N'):
print('Thank you')
break
elif Withdrawl != [10,20,40,60,80,100]:
print("Invalid Amount, please Re-try\n")
restart = ('Y')
elif Withdrawl == 1:
Withdrawl = float(input('Please enter desired amount:'))
elif option == 3:
Pay_in = float(input("How much would you like to pay in?"))
balance = balance + Pay_in
print ("Your Balance is now Rs.", balance)
restart = input("Would you like to go back?")
if restart in ('n', 'no', 'No','N'):
print('Thank you')
break

elif option == 4:
print("Please wait while your card is returned...\n")
print("Thank you for your service")
break
else:
print('Please enter a correct number. \n')
restart = ('Y')
elif pin != (1234):
print('Incorrect Password')
chances = chances - 1
if chances == 0:
print ('\n No more tries')
break
Example 2:
count = 1
for i in range(10):
print (str(i) * i)
for j in range(0, i):
count = count +1
Output:
1
22
333
4444
55555
666666
7777777
88888888
999999999

Chapter 6: Functions
Functions are used to perform particular task
Functions takes some input and produce output or change
The function is a piece of code that you can reuse
You can implement your own functions, in many cases use built-in functions
Built-in functions:
- Python has many built-in function, you should know what task that function performs
L1 = [1,2,3,4,5]
len(L1) -- It writtens number of elements in a list
5
sum(L1) -- prints sum of L1
15
print(L3_sorted)
[1, 2, 3, 4, 5]
L2 -- the input not changed
[5, 3, 4, 2, 1]
L2.sort() -- the input is changed
print(L2)
[1, 2, 3, 4, 5]
User-defined functions:
demo 1:
def add1(a):
----- b=a+1 # indents
----- return b
def - keyword to define a function
add1 - function name
a - function argument (formal parameter)
return - keyword to return the output
# call the fuction
add1(5)
6
def add1(a):
... b = a+1
... return b
...
add1(5)
6
# Save the output of a function in variable c
c = add1(10)
print(c)
11
# Document String - To create help document

def add1(a):
... """
... add 1 to a
... """
... b=a+1
... return b
...

help(add1)
Help on function add1 in module __main__:
add1(a)
add 1 to a
# Passing - Multiple Parameters
- A function can have multiple parameters
def mul(a, b):
... c=a*b
... return c
...
mul(2,3)
6

mul(10,3.15)
31.5
mul(2,"XXXX") - 2 * "XXXX"
'XXXXXXXX'
# No return statement & argument
def mj():
... print("XXXX")
...
mj()
XXXX
# Empty block
def nowork():
...
...
File "<stdin>", line 3
^
IndentationError: expected an indented block

-- use pass to define empty block


def nowork():
... pass
...
print(nowork)
none
-- In function if the return statement is not called, python automatically written
none // Assumed
def nowork():
... pass
... return none // automatically returned
# Usually functions performs more than one task
def add1(a):
... b=a+1
... print(a, "plus 1 equals", b)
... return b
...
add1(2)
2 plus 1 equals 3 -- Output of Print
3 -- Output of return

# Use for loop within the function


In Python, the enumerate() function is used to iterate through a list while keeping track of
the list items' indices.
Example:
pets = ('Dogs', 'Cats', 'Turtles', 'Rabbits')
Then you'll need this line of code:
for i, pet in enumerate(pets):
print i, pet
Your output should be as follows:
0 Dogs
1 Cats
2 Turtles
3 Rabbits
-- use loops within the
function def printStuff(Stuff):
... for i,s in enumerate(Stuff):
... print("Album", i, "rating is", s)
...
album_rating = [10.0,8.5,9.5]
printStuff(album_rating)
Album 0 rating is 10.0
Album 1 rating is 8.5
Album 2 rating is 9.5
# Collecting Arguments
def Ast(*names):
... for name in names:
... print(name)
...

2
# Scope Variable: Local Vs
Global def locvar():
... Date = 1984 -- Local
... return(Date)
...
print(locvar())
1984
Date = 1985 -- Global
print(Date)
1985

Chapter 7: Classes and Objects


1. Classes and Objects
2. Classes in Python
3. Inheritance
4. Abstract class

1. Classes and Objects:


 Python is an Object oriented Language

 class is a blueprint from which a specific object is created
1.class variable - a variable that is shared by all instances of a class

2. Instance Variable - unique to each instance

3.Method - The functions that we define within a class


Every Object has:
- a type
- an internal data representation (a blueprint)
- a set of procedures for interacting with the object(methods)
Syntax:
class Class_name:
statement - 1
statement - 2
statement – n

Class is basically consists of:


data - attributes
methods - functions
Example:
class Student:
pass // to create empty class
std_1 = Student() // object 1
std_2 = Student() // Object 2
std_1.firstname = 'XXXX' // instance variable for std_1 object
std_1.lastname = 'Chandiran'
std_1.email = 'XXXXc@gmail.com'
std_1.salary = 1000
std_2.firstname = 'Paul' // instance variable for std_2 object
std_2.lastname = 'Tilich'
std_2.email = 'paultilich@gmail.com'
std_2.salary = 8000
print(std_1.email)
print(std_2.email)
-- So far what we have created are manual and complex
-- Now we make it easy by defining methods
class Student:
def __init__(self, firstname, lastname, salary)
self.firstname = firstname # equal to std_1.firstname = 'XXXX'
self.lastname = lastname
self.salary = salary
self.email = firstname + '.' + lastname + '@gmail.com'
std_1 = Student("XXXX","Chandiran",10000) std_2 =
Student("santhosh","sivan",5000)
print(std_1.email)
print(std_2.email)
-- print firstname and lastname in a single statment
print(stud1.firstname + ' ' + stud1.lastname)
print('{} {}'.format(std_1.firstname, std_1.lastname))
def fullname(self):
return '{} {}'.format(self.firstname, self.lastname)

-- Class varible
define class variable below the class definition
Built-in Types in Python
Python has lots of data types
Types:
- int 1,2,3..
- float
- Strings
- List
- Dictionary
- Bool

- a type
- an internal data representation (a blueprint)
- a set of procedures for interacting with the
object(methods) An object is an instance of a particular type
Object:Type
Type int: instance of type int
- object 1 = 1
- object 2 = 12
- object 3 = 391
- object 4 = 78
- object 5 = 32
List : instance of type list
- object 1:A = [1,2,3,4]
- Object 2:B = [5,6,7,8]
- Object 3:C = ["a","b","c","d"]
-- You can find the type of object using "type()"
-- List object
A = [1,2,3]
print(A)
[1, 2, 3]
type(A)
<class 'list'>
-- integer object
B = 10
print(B)
10
type(B)
<class 'int'>

Methods:
- A class or type's methods are functions that every instance of that class or type provides
- It's how you interact with the data in a object
- Sorting is an example of a method that interact with data in the object

Ratings = [10,9,6,5,10,8,9,6,2]
Ratings.sort()
print(Ratings)
[2, 5, 6, 6, 8, 9, 9, 10, 10]
-- The sort() interact with the data and change the order of the sequence of data
-- Reverse()
Ratings.reverse()
print(Ratings)
[10, 10, 9, 9, 8, 6, 6, 5, 2]
Defining Your Own Types: Defining class
- Class consists of data attributes and methods
- obj1, obj2, obj3 are the Objects or instances of that
class Example:
Class Circle Class Rectangle
Data Attributes - radius, color - color, height, width
Program: Create a class circle
class Circle (Object):
class - class definition
Circle - Name of the class
Object - Class parent
class Circle(object):
def __init__(self,radius,color):
self.radius = radius;
self.color = color;
c1 = Circle(10,"red")
-- Data attributes are used to initialize each instance of the class
-- __init__ (Special method or constructor used to initialize data
attributes) class Rectangle (object):
def __init__(self,color,height,width):
self.height = height;
self.width = width; self.color
= color;

Chapter 8: FILES
In this chapter you will understand how to import and export various files to python
for analyzing

import os.path
import sys
f1=input("enter a source file").strip()
f2=input("enter a target file").strip()
if os.path.isfile(f2):
print(f2 +"already exists")
infile=open(f1,"r")
outfile=open(f2,"w")
countlines=countcharacters=0
for line in infile:
countlines+=1
countcharacters+=len(line)
outfile.write(line)
print(countlines, "lines and",countcharacters,"characters copied")
print("Contents copied from file 1 to file 2")
infile.close()
outfile.close()

Chapter 9: Pygame

Pygame is a cross-platform set of Python modules designed for writing video games. It
includes computer graphics and sound libraries designed to be used with the Python
programming language
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
is_blue = True
x = 30
y = 30
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
is_blue = not is_blue
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]: y -= 3
if pressed[pygame.K_DOWN]: y += 3
if pressed[pygame.K_LEFT]: x -= 3
if pressed[pygame.K_RIGHT]: x += 3
screen.fill((0, 0, 0))
if is_blue:
color = (0, 128, 255)
else:
color = (255, 100, 0)
pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
pygame.display.flip()
clock.tick(10)

Stay Alive Game with tkinter


#import the modules we need, for creating a
GUI import tkinter
#only press return once
okToPressReturn = True
#the player's attributes.
hunger = 100
day = 0
#-------------------------------------------------------------------
def startGame(event):
global okToPressReturn
if okToPressReturn == False:
pass
else:
#update the time left label.
startLabel.config(text="")
#start updating the values
updateHunger()
updateDay()
updateDisplay()
okToPressReturn = False
#-------------------------------------------------------------------
def updateDisplay():
#use the globally declared variables above.
global hunger
global day
if hunger <= 50:
catPic.config(image = hungryphoto)
else:
catPic.config(image = normalphoto)
#update the time left label.
hungerLabel.config(text="Hunger: " + str(hunger))
#update the day' label.
dayLabel.config(text="day: " + str(day))
#run the function again after 100ms.
catPic.after(100, updateDisplay)
#-------------------------------------------------------------------
def updateHunger():
#use the globally declared variables above.
global hunger
#decrement the hunger.
hunger -= 1
if isAlive():
#run the function again after 500ms.
hungerLabel.after(500, updateHunger)
#-------------------------------------------------------------------
def updateDay():
#use the globally declared variables above.
global day
#decrement the hunger.
day += 1
if isAlive():
#run the function again after 5 seconds.
dayLabel.after(5000, updateDay)
#-------------------------------------------------------------------
def feed():
global hunger
if hunger <= 95:
hunger += 20
else:
hunger -=20
#-------------------------------------------------------------------
def isAlive():
global hunger
if hunger <= 0:
#update the start info label.
startLabel.config(text="GAME OVER! YOU KILLED HIM/HER/IT!")
return False
else:
return True
#-------------------------------------------------------------------
#create a GUI window.
root = tkinter.Tk()
#set the title.
root.title("Stay Alive!")
#set the size.
root.geometry("500x300")
#add a label for the start text.
startLabel = tkinter.Label(root, text="Press 'Return' to start!", font=('Helvetica', 12))
startLabel.pack()
#add a hunger label.
hungerLabel = tkinter.Label(root, text="Hunger: " + str(hunger), font=('Helvetica', 12))
hungerLabel.pack()
#add a 'day' label.
dayLabel = tkinter.Label(root, text="Day: " + str(day), font=('Helvetica', 12))
dayLabel.pack()
hungryphoto = tkinter.PhotoImage(file="hungry.gif")
normalphoto = tkinter.PhotoImage(file="normal.gif")

#add a cat image


catPic = tkinter.Label(root, image=normalphoto)
catPic.pack()
btnFeed = tkinter.Button(root, text="Feed Me", command=feed)
btnFeed.pack()
#run the 'startGame' function when the enter key is pressed.
root.bind('<Return>', startGame)
#start the GUI
root.mainloop()
Chapter 10: Data Analysis
Data analysis is a process of inspecting, cleansing, transforming, and modeling data with the
goal of discovering useful information, informing conclusions, and supporting decision-
making.

K-means clustering is a type of unsupervised learning, which is used when you have
unlabeled data (i.e., data without defined categories or groups). The goal of this algorithm is
to find groups in the data, with the number of groups represented by the variable K. The
algorithm works iteratively to assign each data point to one of K groups based on the
features that are provided. Data points are clustered based on feature similarity. The results
of the K-means clustering algorithm are:

 The centroids of the K clusters, which can be used to label new data

 Labels for the training data (each data point is assigned to a single cluster)

KMEANS
# Dependencies
import matplotlib
from pandas import read_csv
import numpy as np

from sklearn.cluster import KMeans


from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler
import seaborn as sns
from matplotlib.pyplot import hist
# Load the train and test datasets to create two DataFrames
train_url = "http://s3.amazonaws.com/assets.datacamp.com/course/Kaggle/train.csv"
train = read_csv(train_url)
test_url = "http://s3.amazonaws.com/assets.datacamp.com/course/Kaggle/test.csv"
test = read_csv(test_url)
print("***** Train_Set *****")
print(train.head())
print("\n")
print("***** Test_Set *****")
print(test.head())

print("***** Train_Set *****")


print(train.describe())
print("\n")
print("***** Test_Set *****")
print(test.describe())
print(train.columns.values)
# For the train set
train.isna().head()
# For the test set test.isna().head()
print("*****In the train
set*****") print(train.isna().sum())
print("\n")

print("*****In the test set*****")


print(test.isna().sum())
# Fill missing values with mean column values in the train
set train.fillna(train.mean(), inplace=True)
# Fill missing values with mean column values in the test
set test.fillna(test.mean(), inplace=True)
print(train.isna().sum())
print(test.isna().sum())
train['Ticket'].head()
train['Cabin'].head()
train[['Pclass', 'Survived']].groupby(['Pclass'],
as_index=False).mean().sort_values(by='Survived', ascending=False)
train[["Sex", "Survived"]].groupby(['Sex'],
as_index=False).mean().sort_values(by='Survived', ascending=False)
train[["SibSp", "Survived"]].groupby(['SibSp'],
as_index=False).mean().sort_values(by='Survived', ascending=False)
g = sns.FacetGrid(train, col='Survived')
g.map(hist, 'Age', bins=20)
grid = sns.FacetGrid(train, col='Survived', row='Pclass', height=2.2, aspect=1.6)
grid.map(hist, 'Age', alpha=.5, bins=20)
grid.add_legend();
train.info()
train = train.drop(['Name','Ticket', 'Cabin','Embarked'], axis=1)
test = test.drop(['Name','Ticket', 'Cabin','Embarked'], axis=1)
labelEncoder = LabelEncoder()
labelEncoder.fit(train['Sex'])
labelEncoder.fit(test['Sex'])
train['Sex'] = labelEncoder.transform(train['Sex'])
test['Sex'] = labelEncoder.transform(test['Sex'])
# Let's investigate if you have non-numeric data
left train.info()
test.info()
X = np.array(train.drop(['Survived'], 1).astype(float))

y = np.array(train['Survived'])
train.info()
kmeans = KMeans(n_clusters=2) # You want cluster the passenger records into 2:
Survived or Not survived
kmeans.fit(X)
KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300,
n_clusters=2, n_init=10, n_jobs=1, precompute_distances='auto',
random_state=None, tol=0.0001, verbose=0)
correct = 0
for i in range(len(X)):
predict_me = np.array(X[i].astype(float))
predict_me = predict_me.reshape(-1, len(predict_me))
prediction = kmeans.predict(predict_me)
if prediction[0] == y[i]:
correct += 1
print(correct/len(X))
kmeans = kmeans = KMeans(n_clusters=2, max_iter=600, algorithm = 'auto')
kmeans.fit(X)
KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=600,
n_clusters=2, n_init=10, n_jobs=1, precompute_distances='auto',
random_state=None, tol=0.0001, verbose=0)
correct = 0
for i in range(len(X)):
predict_me = np.array(X[i].astype(float))
predict_me = predict_me.reshape(-1, len(predict_me))
prediction = kmeans.predict(predict_me)
if prediction[0] == y[i]:
correct += 1
print(correct/len(X))
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)
kmeans.fit(X_scaled)
KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=600,
n_clusters=2, n_init=10, n_jobs=1, precompute_distances='auto',
random_state=None, tol=0.0001, verbose=0)
correct = 0
for i in range(len(X)):
predict_me = np.array(X[i].astype(float))
predict_me = predict_me.reshape(-1, len(predict_me))
prediction = kmeans.predict(predict_me)
if prediction[0] == y[i]:
correct += 1
print(correct/len(X))

You might also like