Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: python-tutorial

Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: python-tutorial
Showing posts with label python-tutorial. Show all posts
Showing posts with label python-tutorial. Show all posts

Python Passing a list to a function

Python Passing a list to a function

Passing a list to a function

You can pass a list as an argument to a function, and the function can work with the values in the list. Any changes the function makes to the list will affect the original list. You can prevent a function from modifying a list by passing a copy of the list as a argument.

#Passing a list as an argument
def greet users(names):
 """print a simple greeting to everyone ."""
 for name in names:
  msg = "Hello," + name + "!"

usernames = ['hannah', 'ty', 'margot']

def print_models(unprinted, printed):
 """3d print a set of models."""
 while unprinted:
  current_model = unprinted.pop()
  print("printing " + current_model)

#Store some unprinted designs,
# and print each of them.
unprinted = ['phone case', 'pendant', 'ring']
printed = []
print_models(unprinted, printed)

print("\nUnprinted;", unprinted)
print("printed:", printed)

defprint_models(unprinted, printed):
 """3d print a set of models."""
 while unprinted:
  current_model = unprinted .pop()
  print("printing " + current_model
# Store some unprinted designs
# and print each of them.
original =['phone case', 'pendan', 'ring']
printed = []

print_models(original[:], printed)
print("\nOriginal:", original)


list function

Passing an arbitrary number of arguments 

Sometimes you won't know how many arguments a function will need to accept. Python allows you to collect an arbitrary number of arguments
into one parameter using the operator. A parameter that accepts an arbitrary number of arguments must come last in the function definition.

The ** operator allows a parameter to collect an arbitrary number of keyword arguments.

#Collecting an arbitrary number of arguments
def make_pizza(size, *toppings):
 """Make a pizza."""
 print("\nMaking a " + size + "pizza.")
 for topping in toppings:
  print("-" + topping)

#Make three pizzas with different toppings.
make_pizza('small', 'pepperoni')
make_pizza('large', 'bacon bits', 'pineapple')
make_pizza('medium', 'mushroom', 'peppers', 'onions', 'extra cheese')
#Collecting a arbitrary number of keywords arguments
def build_profile(first, last, **user_info):
 """Build a user's profile dictionary."""
 # Build a dict with the required keys.
 profile = {'first': first, 'last': last}

 # Add any other keys and values.
 for key, value in user_info.items():
  profile[key] = value

 return profile

#Create two users with different kinds 
# of information.
user_0 = build _profile('albert', 'einstein', location='princeton') 
user_1 =build _profile('marie', 'curie', location='paris', field='chemistry')



arbitary list


What's the best way to structure a function?

 As you can see there are many ways to write and call a function. When you're starting out, aim for something that simply works. As you gain experience you'll develop an understanding of the more subtle advantages of different structures such as positional and keywords arguments, and the various approaches to importing functions. For now if your functions do what you need them to, you're doing well.


You can store your functions in a separate file called a module, and then import the functions you need into the file containing your main program. This alows for cleaner program files. (Make sure your module is stored in the same directory as your main program.)


#Importing an entire module
import pizza 
pizza.make_pizza('medium', 'pepperoni')
pizza.make_pizza('small', 'bacon', 'pineapple')
#Importing specific function
from pizza import make_pizza

make_pizza('medium', 'pepperoni')
make_pizza('small', 'bacon', 'pineapple')
#Giving a module an alias
import pizza as p

p.make_pizza('medium', 'pepperoni')
p.make_pizza('small', 'bacon', 'pineapple')
#Giving a function an alias
from pizza import make_pizza as mp

mp('medium', 'pepperoni')
mp('small', 'bacon', 'pineapple')
#Importing all functions from a module
from pizza import *

make_pizza('medium', 'pepperoni')
make_pizza('small', 'bacon', 'pineapple')


def make_pizza(size, *toppings):
 """Make a pizza."""
 print("\n Making a " + size + "pizza.")
 for topping in toppings:
  print("-" + topping)


python modules


What are Function in Python?


Functions are named blocks of code designed to do one specific job. Functions allow you to write code once that can then be run whenever you need accomplish the same task. Functions can take in the information they you need , and return the information they generate. Using functions effectively
makes your programs write ,read,text and fix.

Defining a function

The first line of a function is  its definition, marked by the keyword def. The name, of the functions is followed by a set of parentheses and a colon. A docstring in triple quotes, describes what the function does. The body of a function is indented one level.

To call a function, give the name of the function followed by a set of parantheses.

#making a function
def greet_user():
 """display a simple greeting."""
 print ("hello")



Passing information to a function

Information that's passed function is called an argument: information that's received by a function is called a parameter. Arguments are included in parentheses after the function's name, and parameters are listed in parentheses in the function's definition.

#passing a single argument
def greet_user(username):
 """Display a simple greeting."""
 print("hello, " + username + "!")


python pass value


Positional and keyword arguments

The two main kinds of arguments are positional and keyword arguments. When you use positionl arguments Python matches the first arguments in the function call with the first parameter in the function call with the first parameter in the fumction defination and so forth.

with keyword argument you specify which parameter each argument should be assigned to in the function call. When you use keyword arguments, the order of the arguments doesn't matter.

#using positinial arguments
def describe_pet(animal, name):
 """Display information about a pet."""
 print("\nI have a " + animal + ".")
 print("its name is " + name + ".")
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')

#using keywords arguments

describe_pet(animal='hamster', name='harry')
describe_pet(name='while', animal='dog')


python argument


Defaults values

You can provide a default value for a parameter. When function calls omit this argument the default value will be used. Parameters with default values must be listed after parameter without default values in the functions defination so possitional arguments can still work correctly.

#using a default value 
def descibe_pet(name, animal='dog'):
 """display information about a pet."""
  print("\nI have a " + animal + ".")
  print ("its anme is " + name + ".")

describe_pet(name, animal='dog')

#using none to make an argument optinal
def describe_pet(animal, name=none):
  """display information about a pet."""
 print("\nI have a " + animal + ".")
  if name:
   print("its name is " + name + ".")

describe_pet('hamster', 'harry')


python default value


Return values

A function can return a value or a set of values. When a function returns a value, the calling line must provide a variable in which to store the return value. A function stops running when it reaches a return statement.

#returning a single value
def get_full_name(first, last):
 """return a neatly formatted full name."""
 full_name = first + ' ' + last
 return full_name.title()

musician=get_full_name('jimi', 'hendrix')

#returning a dictionary
def build_person(first, last):
 """return a dictionary of information about a person.
 person = {'first': first, 'last': last}
 return person

musician = build_person('jimi', 'hendrix')

#returning a dictionary with optional values
def build_person(first, last, age=None):
 """return a dictionary of information about aperson.
 person = {'first': first, 'last': last}
 if age:
  person['age'] = age
 return person

musician = build_person('jimi', 'hendrix', 27)

musican = build_person('janis', 'joplin')


python return function


Python Accessing values

Python Accessing values

Accessing values

TO access the value associated with an individual key give the name of the dictionary and then place the key in a set of square brackets. If the key you're asking for is not in the dictionary, an error will occur.
You can also use the get() method, which returns None insteadof an error if the key doesn't exist. You can also specify a default value to use if the key is not in the dictionary.

#Getting the value associated with a key 
alien_0 = {'color': 'green', 'points':5}

#Getting the value with get()

alien_color = alien_0.get('color')
alien_points = alien_0.get('points', 0)



Accessing Python


Python Removing key-value pairs

Python Removing key-value pairs

Removing key-value pairs

You can remove any key-value pair you want from a dictionary. To do so use the del keywords and dictionary name, followed by the key in square brackets. This will delete the key and its associated value.

#Deleting a key-value pair
alien_0 = {'color': 'green', 'points': 5}

del alien_0['points']

Python Identifiers

Python Identifiers
Identifiers in Python

An identifiers is a name given to program element such as variables, array, class and function etc. An identifier is a sequence of letters, digits, and underscores, the first character of which cannot be a digit.

#for vaiables, functions, modules, classes... names
#followed by
#diacritics allowed but should be avoided
#language keywords forbidden
#lower/UPPER case discrimination

Python Introduction

Python Introduction



Python is an object-oriented programming language created by Guido Rossum in 1989. It is ideally designed for rapid prototyping of complex applications.It has interfaces to many OS system calls and libraries and is extensible to C or C++. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source
Python is widely used in Artificial Intelligence, Natural Language Generation, Neural Networks and other advanced fields of Computer Science. Python had deep focus on code readability & this class will teach you python from basics.

Python is a programming language with objects, modules, threads, exceptions and automatic memory management.

Python language

Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

How memory is managed in Python?


Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.

The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.

Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

What is module and package in Python?

In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.

The folder of Python program is a package of modules. A package can have modules or subfolders.

Mention what are the rules for local and global variables in Python?

Local variables: If a variable is assigned a new value anywhere within the function's body, it's assumed to be local.

Global variables: Those variables that are only referenced inside a function are implicitly global.

Explain database connection in Python Flask?

Flask supports database powered application (RDBS). Such system requires creating a schema, which requires piping the shema.sql file into a sqlite3 command. So you need to install sqlite3 command in order to create or initiate the database in Flask.

Flask allows to request database in three ways
  • Before_request() : They are called before a request and pass no arguments
  • After_request() : They are called after a request and pass the response that will be sent to the client
  • Teardown_request(): They are called in situation when exception is raised, and response are not guaranteed. They are called after the response been constructed. They are not allowed to modify the request, and their values are ignored.

 Mention five benefits of using Python?

  • Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.

  • Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically

  • Provide easy readability due to use of square brackets

  • Easy-to-learn for beginners

Having the built-in data types saves programming time and effort from declaring variables

Hello World in Python

print "hello world"
Open Terminal And Create a file hello.py and write the above command. Then run the command to execute the program.
python hello.py