HTML NEW TAGS AND COLLECTIVE CHARACTER OBJECTS

 HTML NEW TAGS

HTML TAGS

HTML tags are the hidden keywords within a web page that define how your web browser must format and display the content.
Most tags must have two parts, an opening and a closing part. For example, <html> is the opening tag and </html>is the closing tag. Note that the closing tag has the same text as the opening tag, but has an additional forward-slash ( / ) character. I tend to interperet this as the "end" or "close" character.
There are some tags that are an exception to this rule, and where a closing tag is not required. The <img> tag for showing images is one example of this.
Each HTML file must have the essential tags for it to be valid, so that web browsers can understand it and display it correctly.
The rest of the HTML file can contain as little or as many tags as you want to display your content.

<header> ... </header>

Defines the header block for a document for individual section.

<footer> ... </footer>

Identifies the footer block for the document (or an individual section).

<main> ... </main>

Describes the main content of a document.

<article> ... </article>

Identifies an article inside a document.

<aside> ... </aside>

Specifies content contained in a document sidebar.

<section> ... </section>

Specifies a section block in the document.

<details>...</details>

Describes additional facts or information that the user can view or hide.

<dialog> ... </dailog>

A dailog box or window.

<figcaption>... </figcaption>

The <figure> element caption that helps describes the figure.

<figure> ... </figure>

An independent content block featuring diagrams photos, illustrations or more.

<mark> ... </mark>

Displays a portion of highlighted text within the page content.

<nav> ...</nav>

Navigation links for the user in a document.

<menuitem>...</menuitem>

The specific menu item that a user can raise from a popup menu.

<meter > ...</meter>

Describes the scalar measurement within a known array .

<progress> ... </progress>

Displays text within browsers that do not support ruby annotations.

<rp> .. </rp>

Displays text within browsers that do not support ruby annotations.

<rt>...</rt>

Displays east asian typography character details.

<ruby>....</ruby>

Describes a ruby annotation for east asian typography .

<summary> ... </summary>

Contains a visible heading for a <detail> element 

<bdi>...</bdi>

Helps you format part of text in a different direction from other text.

<time>...</time>

Idebtifies the time and date.

<wbr>

A line break within the content.


COLLECTIVE CHARACTER OBJECTS


&#34; &quot ; quotation marks-"

&#38; &amp;  Ampersand - &

&#60; &lt; less than sign - <

&#62; &gt; Greater than sign - >

&#160; &nbsp; non-breaking space

&#169; &copy; copyright symbol- © 

&#64; &Uuml; @ symbol - @

&#149; &ouml; small bullet- 

&#153; &ucirc; Trademark symbol - 

HTML OBJECTS AND iFRAME

OBJECTS AND iFRAME

<object> ... </object>

The object tag describe an embedded file type , including audio , video , pdfs , additional pages, and more.

height=" "

Describe the height og the object in pixel.

width=" "

Describes the width of the object in pixels.

type=" "

Describe which media type the data contains.

usemap=" "

This is the name of a client-side image map within <object>.

<iframe> .. </iframe>

Contains an inline frame that allows you to embed external information into an existing document.

IFRAME ATTRIBUTES


name=" "

The name of the iframe>

src=" "

The URL source of the origional documents to embed inside the </iframe>

srcdocs=" "

This contains the actual HTML content to display inside the <iframe> on the current page.

width=" "

Defines the width of your <iframe>.

<param />

Appending extra parameter help you customize the iframe content.

<embed> ... </embed>

The embed tag acts as a container for another external application or additional plugs-in.

EMBED ATTRIBUTES

height=" "

Defines the height of the embedded content you're including.

width=" "

Similar to previous , but this time defining the width of the embedded content.

src=" "

The source URL of the external file you're embedding.

type=" "

Describe the media type of embedded content to include.

EXAMPLE


<object width="400" height="400"></object>
<iframe src="demo_iframe.htm" width="200" height="200"></iframe>
<embed src="helloworld.swf" width="200" height="200"></embed>




Django Part 1

Django Part 1




What is Django?

Django is a web framework which helps you build interactive websites using Python. With Django you define the kind of data your site needs to work with, and you define the ways your users can work with that data.

Installing Django

It's usually best to install Django to a virtual environment, where your project can be isolated from your other Python projects. Most commands assume you're working in an active virtual environment.



#Create a virtual environment
$ python -m venv 11_env
#Activate the environment (Linux and OS X)
$ source 11_env/bin/activate
#Activate the environment (Windows)
> 11_env\Scripts\activate
#Install Django to tghe active environment
(11_env)$ pip install Django

Screenshot 

python django

 

python django env

 

python django env

 

python django env

 


Creating a project

To start a project we'll create a new project, create a database, and start a development server.


#Create a new project
$ django-admin.py startproject learning_log.
#Create a database
$python manage.py migrate
#View the project
$ python manage.py runserver
#Create a new app
$python manage.py startapp learning_logs

Screenshot 

python django migration
python django run server

 
python django server

python django model



Working with models

The data in a Django project is structured as a set of models.


#Defining a model
#To define the models for your app, modify the file models.py that was created in your app's folder. The __str__() method tells Django how to represent #data objects based on this model.

from  django.db import models
from django.db import models

# Create your models here.
class Topic(models.Model):
	"""A topic the user is learning about."""
	text = models.CharField(max_length=200)
	date_added = models.DateTimeField(auto_now_add=True)

	def __str__(self):
			return self.text



python model




Activating a model To use a model the app must be added to the tuple INSTALLED_APPS, which is stored in the project's setting.py file.
INSTALLED_APPS = (
--snip--
'django.contrib.staticfiles',

# My apps 
'learning_logs',
)
Set The Template Path in setting.py
'DIRS': [os.path.join(BASE_DIR, 'templates')],

python django setting.py


Migrating the database The database needs to be modified to store the kind of data that the model represents.
$ python mange.py makemigrations learning_logs
$ python manage.py migrate


python django migartion

Creating a superuser A superuser is a user account that has access to all aspects of the project.
$ python manage.py createsuperuser

python django superuser


Registering a model You can register your models with Django's admin site, which makes it easier to work with the data in your project. To do this, modify the app's admin.py file.
from django.contrib import admin

from learning_logs.models import Topic

admin.site.register(Topic)


python admin.py


Building a simple home page 

Users interact with a project through web pages, and a project's home page can start out as a simple page with no data. A page usually needs a URL, a view, and a template.

Mapping a project's URLs
The project's main urls.py file tells Django where to find the urls.py files associated with each app in the project.
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
	url(r'^admin/', include (admin.site.urls)),
	url(r'', include('learning_logs.urls', namespace='learning_logs')),
]

python url


Mapping an app's URLs An app's urls.py file tells Django which view to use for each URL in the app, You'll need to make this yourself, and save it in the app's folder
from django.conf.urls import url

from . import views 

urlpatterns = [
	url(r'^$', views.index, name='index'),
]


python url

Writing a simple view A view takes information from a request and sends data to the browser, often through a template. View function are stored in an app's views.py file. This simple view function doesn't pull in any data, but it uses the template index.html to rernder the home page.
from django.shortcuts import render

def index(request):
	"""The home page for Learning Log."""
	return render(request, 'learning_logs/index.html') 
Final urls.py
from django.conf.urls import include, url
from django.contrib import admin
import sys
sys.path.insert(0, '/home/sanjeev/python/learning_log/learning_logs/')
import views
urlpatterns = [
	url(r'^$', views.index, name='index'),
]

Screenshot 

python django template

 

django localhost

 

python url

python file structure
 

python django sub

 

Python Testing Code

Python Testing Code



Why test your code?

When you write a function or a class, you can also write tests for that code. Testing proves that your code works as it's supposed to in the situations it's designed to handle, and also when people use your programs in unexpected ways. Writing tests gives you confidence that your code will work correctly as more people begin to use your programs. You can also add new features to your programs and know that you haven't broken existing behavior.

A unit tests verifies that one specific aspect of your code works as it's supposed to. A test case is a collection of unit tests which verify your code's behavior in a wide variety of situations.

Testing a function: A passing test

Python's unittest module provides tools for testing your code. To try it out, we'll create a function that returns a full name. we'll use the function in a regular program, and then build a test case for the function.

#A function to test
def get_full_name(first, last):
 """Return a full name."""
 full_name = "{0} {1}".format(first, last)
 return full_name.title()


#===============
#Using the function
from full_name import get_full_name

janis = get_full_name('janis', 'joplin')
print(janis)

bob = get_full_name('bob', 'dylan')
print(bob)

#Testing a function(cont.)
#Building a testcase with one unit test

import unittest
from full_name import get_full_name

class NamesTestCase(unittest.TestCase):
 """Test for names.py."""

 def test_first_last(self):
  """Test names like Janis Joplin."""
  full_name = get_full_name('janis', 'joplin')
  self.assertEqual(full_name, 'Janis Joplin')

unittest.main()

Screenshot 

python testing

 


Testing a function: A failing test

Failing tests are important; they tell you that a change in the code has affected existing behavior. When a test fails, you need to modify the code so the existing behavior still works.

#Modifying the function
def get_full_name(first, middle, last):
 """Return a full name."""
 full_name = "{0} {1} {2}".format(first, middle, last)
 return full_name.title()


#Using the function
from full_name2 import get_full_name

john = get_full_name('john', 'lee', 'hooker')
print(john)

david = get_full_name('david', 'lee', 'roth')
print(david)

Screenshot 

python testing

 

Adding new tests

You can add as many unit tests to a test case as you need. To write a new test, add a new method to your test, add a new method to your test case class.

#Testing middle names

import unittest
from full_names import get_full_name

class NamesTestCase(unittest.TestCase):
"""Tests for names.py"""

def test_first_last(self):
"""Test names like Janis Joplin."""
full_name = get_fullname('janis', 'joplin')
self.assertEqual(full_name, 'Janis Joplin')

def test_middle(self):
"""Test names like David Lee Roth."""
full_name = get_full_name('david', 'roth', 'lee')
self.assertEqual(ful_name, 'David Lee Roth')

unittest.main()

Screenshot 

python testing

 

A variety of assert methods
Python provides a number of assert methods you can use to test your code.
#Verify that a==b, or a!=b
assertEqual(a, b)
assertNotEqual(a, b)
#Verify that x is True, or x is False
assertTrue(x)
assertFalse(x)
#Verify an item is in a list, or not in a list
assertIn(item, list)
assertNotIn(item, list)
Testing a class
Testing a class is similar to testing a function, since you'll mostly be testing your methods.
A class to test

class Accountant():
"""Manage a bank account."""

def__init__(self, balance=0):
self.balance = balance

def deposit(self, amount):
self.balance += amount

def withdraw(self, amount):
self.balance -= amount

Building a testcase
import unittest
from accountant import Accountant

class TestAccountant(unittest.TestCase):
"""Tests for the class Acountant."""

def test_initial_balance(self):
#Default balance should be 0.
acc = Accountant()
self.assertEqual(acc.balance, 0)

# Test non-default balance.
acc = Accountant(100)
self.assertEqual(acc.balance, 100)

unittest.main()
The setUp() method
When testing a class, you usually have to make an instance of the class. The setUp() method is run before every test. Any instances you make in setUp() are available in every test you write.
Using setUp() to support mutiple tests
import unittest
from accountant import Accountant

class TestAccountant(unittest.TestCase):
"""Tests for the class Accountant."""

def setUp(self):
self.acc = Accountant()

def test_initial_balance(self):
# Default balance should be 0.
self.assertEqual(self.acc.balance, 100)

#Test non-default balance.
acc = Accountant(100)
self.assertEqual(acc.balance, 100)

def test_deposit(self):
#Test single deposit.
self.acc.deposit(100)
self.assertEqual(self.acc.balance, 100)

#Test multiple deposits.
self.acc.deposit(100)
self.acc.deposit(100)
self.assertEqual(self.acc.balance, 300)

def test_withdrawal(self):
#Test single withdrawal.
self.acc.deposit(100)
self.acc.withdraw(100)
self.assertEqual(self.acc.balance, 900)

unittest.main()

Python Files and Exceptions

Python Files and Exceptions


What are files? What are exceptions?

Your programs can read information in from files, and they can write data to files. Reading from files allows you to work with a wide variety of information; writing to files allows users to pick up where they left off the next time run your program. You can write text to files, and you can store Python structure such as lists in data files.

Exceptions are special objects that help your programs respond to errors in appropriate ways. For example if your program tries to open a file that doesn't exists, you use exceptions to display an
informative error message instead of having the program crash.



Reading from file

To read from a file your program needs to open the file and then read the contents of thefile. You can read the entire contents of the file at once, or read the file line by line. The with statement makes sure the file is closed properly when the program has finished accessing the file.

#Reading an entire file at once
filename = 'siddhartha.txt'

with open(filename) as f_obj:
	contents = f_obj.read()

print(contents)

#Reading line by line
#Each line that's read from the files has a newline character at the end of the line, and the print function adds its own newline character. The rstrip() method gets rid of the the extra blank lines this would result in when printing to the terminal.

Screenshot 

python read file

 

filename = 'siddhartha.txt'

with open(filename)as f_obj:
	for line in f_obj:
		print(line.rstrip())

Screenshot 

python read file

 

reading from a file (cont.)
#Storing the lines in a list
filename = 'siddhartha.txt'

with open(filename) as f_obj:
	lines = f_obj.readlines()

for line in lines:
	print(line.rstrip())

Screenshot 

python read file in list

 


Writing to a file


Passing the 'w' argument to open() tells Python you want to write to the file. Be careful; this will erase the contents of the file if it already exists. Passing the 'a' argument tells Python you want to append to the end of an existing file
#Writing to an empty file 
filename = 'programming.txt'

with open (filename, 'w') as f:
	f.write("I love programming!")

#Writing multiple lines to an empty file
filename = 'programming.txt'

with open (filename, 'w') as f:
	f.write("I love programming!\n")
	f.write("I love creating new games.\n")

#Appending to a file
filename = 'programming.txt'

with open (filename, 'a') as f:
	f.write("I also love working with data.\n")
	f.write("I love making apps as well.\n")

with open(filename) as f_obj:
	contents = f_obj.read()

print(contents)

Screenshot 

python file write

 


File paths 


When python runs the open() function, it looks for the file in the same directory where the program that's being excuted is stored. You can open a file from a subfolder using a relative path.You can also use an absolute path to open any file on your system.
#Opening a file from a subfolder
f_path = "text_files/alice.txt"

with open(f_path) as f_obj:
lines = f_obj.readlines()

for line in lines :
print(line.rstrip())

File paths(cont.)

#Opening a file using an absolute path
f_path = "/home/sanjeev/books/alice.txt"

with open(f_path) as f_obj:
	lines = f_obj.readlines()

#Opening a file on windows

#Windows will sometimes interpret forward slashes incorrectly. If you run into this, use backslashes in your file paths.

f_path = "C:\User\sanjeev\books\alice.txt"
with open(f_path) as f_obj:
	lines = f_obj.readlines()


The try-except block

When you think an error may occur, you can write a try except block to handle the exception that might be raised. The try block tells Python to try running some code, and the except block tells Python what to do if the code results in a particular kind of error.

#Handling the ZeroDivisionError exception
try:
with open(f_name) as f_obj:
	lines = f_obj.readlines()
except FileNotFoundError:
	msg = "can't find file {0}.".format(f_name)
print(msg)

Knowing which exception to handle

It can be hard to know what kind of exception to handle when writing code. Try writing your code without a try block, and make it generate an error. The traceback will tell you what kind of exception your program needs to handle.

The else block

The try block should only contain code that may cause an error. Any code that depends on the try block running successfully should be placed in the else block.

#Using an else block
print("Enter two numbers. I'll divide them.")

x = input("First number:")
y = input("second number:")

try:
	result = int(x) / int(y)
except ZeroDivisionError:
	print("You can't divide by zero!")
else:
	print(result)

#preventing crashes from user input
#without the except block in the following example, the program would crash if the user tries to divide by zero. As written, it will handle the error gracefully and keep running.
"""A simple calculator for division only."""

print("Enter two numbers. I'll divide them.")
print("Enter 'q' to quit.")

while True:
	x = input("\nFirst number: ")
	if x == 'q':
		break
	y = input("Second number:")
	if y == 'q':
		break

	try:
		result = int(x) / int(y)
	except ZeroDivisionError:
		print("you can't divide by zero!")
	else:
		print(result)

Screenshot 

 
python else


Deciding which errors to report

Well-written, properly tested code is not very prone to internal errors such as syntax or logical errors. But every time your program depends on something external such as user input or the existence of a file, there's a possibility of an exception being raised.

It's up to you how to communicate errors to your users. Sometimes users need to know if a file is missing; sometimes it's better to handle the error silently. A little experience will help you know how much to report.

Failing silently

Sometimes you want your program to just continue running when it encounters an error, without reporting the error to the user. Using the pass statement in an else block allows you to do this

#Using the pass statement in an else block
f_names = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']

for f_name in f_names:
# Report the length of each file found.
	try:
		with open(f_name) as f_obj:
			lines = f_obj.readlines()
	except FileNotFoundError:
		# just move on to the next file.
		pass
	else:
			num_lines = len(lines)
			msg = "{0} has {1} lines.".format(f_name, num_lines)
			print(msg)

Screenshot 

python file handling

 


Avoid bare except blocks

Exception-handling code should catch specific exceptions that you except to happen during your program's execution. A bare except block will catch all exception, including keyboard interrupts and system exits you might need when forcing a program to close.

If you want to use a try block and you're not sure which exception to catch, use Exception. It will catch most exceptions, but still allow you to interrupt programs intentionally.

#Don't use bare except blocks
try:
# Do something 
except:
	pass
#Use Exception instead
try:
#Do something
except Exception:
	pass
	#Printing the exception
try:
	#Do something
except Exception as e:
	print(e, type(e))

Storing data with json

The json module allows you to dump simple Python data structures intoa file, and load the data from that file the next time the program runs. The JSON data format is not specific to Python, so you can share this kind of data with people who work in other languages as well.

Knowing how to mange exceptions is important when working with stored data. You'll usually want to make sure the data you're trying to load exists before working with it.

#Using json.dump() to store data
"""Store some munbers."""

import json 

numbers =[2, 3, 5, 7, 11, 13]

filename = 'number.json'
with open(filename, 'w') as f_obj:
	json.dump(numbers, f_obj)

#Using json.load() to read data
"""Load some previously stored numbers."""


filename = 'number.json'
with open(filename) as f_obj:
	numbers = json.load(f_obj)
	print(numbers)

#Making sure the stored data exists
import json 

f_name = 'number.json'

try:
	with open(f_name) as f_obj:
		numbers = json.load(f_obj)
except FilenotFoundError:
	msg = "Can't find {0}.".format(f_name)
	print(msg)
else:
	print(numbers)

Screenshot 

json exception

 

HTML TABLE (+FORMATTING)

TABLE ( = FORMATTING)


INTRODUCTION

The HTML tables allow web authors to arrange data like text, images, links, other tables, etc. into rows and columns of cells.
The HTML tables are created using the <table> tag in which the <tr> tag is used to create table rows and <td> tag is used to create data cells. The elements under <td> are regular and left aligned by default.

Table Heading

Table heading can be defined using <th> tag. This tag will be put to replace <td> tag, which is used to represent actual data cell. Normally you will put your top row as table heading as shown below, otherwise you can use <th> element in any row. Headings, which are defined in <th> tag are centered and bold by default.

Tables Backgrounds

You can set table background using one of the following two ways −
  • bgcolor attribute − You can set background color for whole table or just for one cell.
  • background attribute − You can set background image for whole table or just for one cell.
You can also set border color also using bordercolor attribute.



<table>...</table>

The table tag identifies and contains all table related content.

<caption> ...</caption>

The caption is a description of what the table is and what it contains.

<thead> ... </thead>

The table headers describe the type of information contained in each coloum underneath.

<tbody> ... </tbody>

The table contains the table's data or information.

<tfoot> .. </tfoot>

Table footers describe all footer content.

<tr> ... </tr>

Contains the information to be included in a single row of the table.

<th> ... </th>

Contains the actual information to be included in a single row of the table.

<td> ... </td>

Contains the actual information or data in a single table cell.

<colgroup> ... </colgroup>

Groups a single (or multiple) column for formatting purposes.

<col / >

Defines a single column of information inside a table.

EXAMPLE

<table>
<colgroup>
<col span="2" style="background-color:#181alt">
<col style="background-color:#2c323c">
</colgroup>
<tr>
<th>isbn</th>
<th>tilte</th>
<th>price</th>
</tr>
<tr>
<td>3476896</td>
<td>my first html</td>
<td>$53</td>
</tr>
</table>

SAMPLE



Python Class Reference

Python Class Reference


What are classes?

Classes are the foundation of object-orineted programming. Classes represent real-world things you want to model in your programs: for example dogs, cars, and robots. You use a class to make objects, which are specific instances of dogs, cars, and robots. A class defines the generalbehaviour that a whole category of object can have, and the information that can be associated with those objects.

Classes can inherit from each other - you can write a class that extends the functionality of an existing class. This allows you to code efficiently for a wide variety of situations.

Creating and using a class consider how we might model a car. What information would we associated with a car, and what behaviour wouldit have? The information is stored in variable called attributes, and the behaviour is represented by functions. Functions that are part of a class are called methods.

#The car class
class Car():
  """A simple attempt to model a car."""

  def_init_(self, make, model, year):
    """Initialize car attributes."""
    self.make = make
    self.model = model
    self.year =year

    #Fuel capacity and level in gallons.
    self.fuel_capacity = 15
    self.fuel_level = 0

  def fill_tank(self):
    """Fill gas tank to capacity."""
    self.fuel_level = self.fuel_capacity
    print("Fuel tank is full.")

  def drive (self):
    """Simulate driving."""
    print("The car is moving.")

Creating and using a class(cont.)

#Creating an object from a class

my_car = Car('audi', 'a4', 2016)

#Acessing attributes values

print(my_car.make)
print(my_car.model)
print(my_car.year)

#Calling methods

my_car.fill_tank()
my_car.drive()

#Creating multiple objects

my_car = Car('audi', 'a4', 2016)
my_old_car = Car('subaru', 'outback', 2013)
my_truck = Car('toyota', 'tacoma', 2010)

Modifying attributes

You can modify an attribute's value directly, or you can write methods that manage updating values more carefully.

#Modifying an attribute directly

my_new_car = Car('audi', 'a4', 2016)
my_new_car.fuel_level = 5

#Writing a method to update an attribute's value

def update_fuel_level(self, new_level):
  """update the fuel level."""
  if new_level <= self.fuel_capacity:
    self.fuel_level = new_level
  else:
    print("The tankl can't hold that much!")

#Writing a method to increment an attribute's value

def add_fuel(self, amount):
  """Add fuel to the tank."""
  if (self.fuel_level + amount <= self.fuel_capacity):
    self.fuel_level += amount
    print("Added fuel.")
  else:
    print("The tank won't hold that much.")

Naming conventions

In python class names are written in CamelCase and object names are written in lowercasewith underscore. Modules that contain classes should still be named in lowercases with underscores.

Class inheritance

If the class you're writing is a specialized version of another class , you can use inheritance, when one class inherits from another, it automatically takes on all the attributes and methods of the parent class. The child class is free to introduce new attributes and methods , and override attributes and methods of the parent class.

To inherit from another class inlcude the names of the parent class in parenthesis when defining the new class.

The __init__() method for a child class 
class ElectricCar(Car):
  """A simple model of an electric car."""
  def__init__(self, make, model, year):
    """Initialize an electric car."""
    super().__init__(make, model, year)

  #Attributes specific to electric cars.
  #Battery capacity in kWh.
  self.battery_size = 70
  #Charge level in %
  self.charge_level = 0

#Adding new methods to the child class

class ElectricCar(Car):
  --snip--
  def charge(self):
    """Fully charge the vehicle."""
    self.charged_level = 100
    print("The vehicle is fully charged.")

#Using child methods and parent methods

my_ecar = ElectricCar('tesla', 'models', 2016)
my_ecar.charge()
my_ecar.drive()


Finding you workflow

There are many ways to model real world objects and situations in code, and sometimes that variety can feel overwhelming. Pick an approach and try it - if your first attempt doesn't work, try a different approach.

Class inheritance(cont.)

#Overriding parent methods
class ElectricCar(Car):
  --snip--
  def fill _tank(self):
    """Display an error message."""
    print("This car has no fuel tank!")

Instances as attributes

A class can have objects as attributes. This allows classes to work together to method complex situations.

#A Battery class
class Battery():
  """A battery for an electric car."""

  def__init__(self, size=70):
    """Initialize battery attributes."""
    #Capacity in KWh, charge level in %.
    self.size = size
    self.charge_level = 0

  def get_range(self):
    """Return the battery's range."""
    if self.size == 70:
    return 240
    elif self.size == 85:
    return 270
#Using an instance as an attribute
class ElectricCar(Car):
  --snip--

  def__init__(self, make, model, year):
    """Intialize an electric car."""
    super().__init__(make, model, year)

    #Attribute specific to electric cars.
    self.battery = Battery()

def charge(self):
    """Fully charge the vehicle."""
    self.battery.charge_level = 100
    print("The vehicle is fully charged.")

#Using the instance
my_ecar = ElectricCar('tesla', 'model x', 2016)

my_ecar.charge()
print(my_ecar.battery.get_range())
my_ecar.drive()

Importing classes

Class files can get long as you add detailed information and functionality. To help keep your program files uncluttered, you can store your classes in modules and import the classes you need into your main program.

Storing classes in a file
"""Represent gas and electric cars."""

Class_Car():
  """A simple attempt to model a car."""
  --snip--

class Battery():
  """A battery for an electric car."""
  --snip--

class ElectricCar(Car):
  """A simple model of an electric car."""
  --snip--

#Importing individual classes from a module
from Car import Car, ElectricCar

my_beetle = Car('volkswagen', 'beetle', 2016)
my_beetle.fill_tank()
my_beetle.drive()

my_tesla = ElectricCar('tesla', 'model's', 2016)
my_tesla.charge()
my_tesla.drive()

#Importing an entire module
import car

my_beetle = car.Car('volkswagen', 'beetle', 2016)
my_beetle.fill_tank()
my_beetle.drive()

my_tesla = car.ElectricCar('tesla', 'models', 2016)
my_tesla.charge()
my_tesla.drive()

#Importing all classes from a module
from car import *

my_beetle = car.Car('volkswagen', 'beetle', 2016)

Classes in python 2.7

#Classes should inherit from object
class ClassName(object):
The Car Class in python 2.7
class car(object):
#Child class__init__()method is different
class ChildClassName(parentclass):
    def__init__(self):
        super(ClassName, self).__init__()
#The ElectricCar class in python 2.7
class ElectricCar(Car):
    def__init__(self, make, model, year):
        super(ElectricCar, self).__init__(make, model, year)

Storing objects in a list

A list can hold as many items as you want, so you can make a large number of objects from a class and store them in a list. Here's an example showing how to make a fleet of rental cars, and make sure all the cars are ready to drive.

#A fleet of rental cars
from car import Car, ElectricCar

# Make liststo hold a fleet of cars.
gas_fleet = []
electric_fleet = []

# Make 500 gas cars and 250 electric cars.
for _ in range(500):
    car = Car ('ford', 'focus', 2016)
    gas_fleet.append(car)
for _ in range (250):
    ecar = ElectricCar('nissan', 'leaf', 2016)
    electric_fleet.append(ecar)

# Fill tha gas cars, and charge electric cars.
for car in gas fleet
    car.fill_tank()
for ecar in electric_fleet:
    ecar.charge()

print("Gas cars:", len(gas_fleet))
print("Electric cars:", len(electric_fleet))

Screenshot

python class

 

Partial Complete Code

 

class Car():
  """A simple attempt to model a car."""
  def __init__(self,make,model,year):
    """Initialize car attributes."""
    self.make = make
    self.model = model
    self.year =year

    #Fuel capacity and level in gallons.
    self.fuel_capacity = 15
    self.fuel_level = 0

  def fill_tank(self):
    """Fill gas tank to capacity."""
    self.fuel_level = self.fuel_capacity
    print("Fuel tank is full.")

  def drive (self):
    """Simulate driving."""
    print("The car is moving.")

  def update_fuel_level(self,new_level):
    """update the fuel level."""
    if new_level <= self.fuel_capacity:
      self.fuel_level = new_level
    else:
      print("The tankl can't hold that much!")

  #Writing a method to increment an attribute's value
  def add_fuel(self, amount):
    """Add fuel to the tank."""
    if (self.fuel_level + amount<= self.fuel_capacity):
      self.fuel_level += amount
      print("Added fuel.")
    else:
      print("The tank won't hold that much.")

#Creating an object from a class


class ElectricCar(Car):
  """A simple model of an electric car."""
  def __init__(self, make, model, year):
    """Initialize an electric car."""
    super().__init__(make, model, year)
    #Attributes specific to electric cars.
    #Battery capacity in kWh.
    self.battery_size = 70
    #Charge level in %
    self.charge_level = 0

#Adding new methods to the child class

class ElectricCar(Car):
  # --snip--
  def charge(self):
    """Fully charge the vehicle."""
    self.charged_level = 100
    print("The vehicle is fully charged.")

#Using child methods and parent methods

my_ecar = ElectricCar('tesla', 'models', 2016)
my_ecar.charge()
my_ecar.drive()


my_car = Car('audi', 'a4', 2016)

#Acessing attributes values

print(my_car.make)
print(my_car.model)
print(my_car.year)

#Calling methods

my_car.fill_tank()
my_car.drive()

#Creating multiple objects

my_car = Car('audi', 'a4', 2016)
my_old_car = Car('subaru', 'outback', 2013)
my_truck = Car('toyota', 'tacoma', 2010)

#Modifying an attribute directly

my_new_car = Car('audi', 'a4', 2016)
my_new_car.fuel_level = 5

#Writing a method to update an attribute's value

HTML INPUT TYPE ATTRIBUETS

INPUT TYPE ATTRIBUETS


type=" "

Specifies the field input type, including text, password,date time,checkbox,password submit etc.

name=" "

Describes the name of the form.

value=" "

escribes the value or input field information.

size=" "

specifies the input element width in characters.

maxlength=" "

Identifies the maximum input element character numbers allowed.

required

another helpfully explicit tag, making sure the <input> element is completely field out prior to the user submitting the form.

step=" "

Identifies the legal number intervals for an input field.

width=" "

Specifies the width (in pixel) of an <input> element.

height=" "

Dictates the height (again, in pixels) of an <input>element.

place holder=" "

provides a helpful hint to the user describing what the <input> element values should be.

pattern-=" " 

Identifies a regular expression that the <input> element  gets checked against making sure the user entered the correct information.

min=" "

The maximum value allowed for each <input> element.

max=" "

The maximum value allowed for each <input> element.

autofocous

Says to make sure that the <input> element comes into focous after the page loads.

disabled 

Disables an <input> element on the form.

<textarea> ... </textarea>

Specifies a large text input for longer messages.

<select> ... </select>

Describe a drop-down box for user's to select one form a variety of options.

SELECT ATTRIBUTES



name=" "

The name for a drop down combination box.

size=" "

Specifies the number of available , visible options in a drop-down.

multiple

allows for multiple selections to be made at one time.

required 

Requires that a value is selected before a user can submit a form.

autofocous

Specifies that a drop-down list automatically comes into focous after a page loads.

<optgroup> ... </optgroup>

specifies the entire grouping of available options.

<option> ... >/options>

Defines one of the available options in the drop down list.

OPTION ATTRIBUTES


value=" "

Explains the options value available for selection.

selected

Define the default selected option for users.

<button> ... </button>

Define the clickable button for users to submit options.


EXAMPLE


<form action="action_page.php" method="post">
<fieldset>
<legend>Personal information:</legend>
First name:<br>
<input type="text" name="firstname" value="mickey" placeholder="first name"><br>
Last name:<br>
<input type="text" name="lastname" value="mouse" placeholder=Last Name"><br><br>
Favorite car brand:<br>
<select>
<option value="volvo">volve</option>
<option value="saab">saab</option>
<option value="mercedes">mercedes</option>
<option value="audi">audi</option>
</select>
<text"area name="description"></textarea>
<input type="submit" value="submit">
</fieldset>
</form>

SAMPLE