Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Learn Python From Scratch Here On Nct
#1
Welcome to Python Tutorial, Powered by Nigeria Coders Team. Let's go!


Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). This tutorial gives enough understanding on Python programming language.

This tutorial is designed for software programmers who need to learn Python programming language from scratch.

You should have a basic understanding of Computer Programming terminologies. A basic understanding of any of the programming languages is a plus.


Code:
#!/usr/bin/python

print "Hello, Python!"


Python Overview
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.

·        √Python is Interpreted: Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP.

·        √Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.

·        √Python is Object-Oriented: Python supports Object-Oriented style or technique of programming that encapsulates code within objects.

·        √Python is a Beginner's Language: Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.

Python Features
Python's features include:

·        √Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly.

·        √Easy-to-read: Python code is more clearly defined and visible to the eyes.

·        √Easy-to-maintain: Python's source code is fairly easy-to-maintain.

·        √A broad standard library: Python's bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh.

·        √Interactive Mode: Python has support for an interactive mode which allows interactive testing and debugging of snippets of code.

·        √Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms.

·        √Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient.

·        √Databases: Python provides interfaces to all major commercial databases.

·        √GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix.

·        √Scalable: Python provides a better structure and support for large programs than shell scripting.
It takes so long to learn simplicity.
#2
Python 3 - Environment Setup
Python 3 is available on for Windows, Mac OS and most of the flavours of Linux operating system. Even though Python 2 is available for many other OSs, Python 3 support either has not been made available for them or has been dropped.

Local Environment Setup
Open a terminal window and type "python" to find out if it is already installed and which version is installed.

Getting Python

√Windows platform

Following different installation options are available:

Windows x86-64 embeddable zip file
Windows x86-64 executable installer
Windows x86-64 web-based installer
Windows x86 embeddable zip file
Windows x86 executable installer
Windows x86 web-based installer

Note: In order to install Python 3.5.1, minimum OS requirements are Windows 7 with SP1. For versions 3.0 to 3.4.x Windows XP is acceptable.

√Linux platform

Different flavours of Linux use different package managers for installation of new packages.

On Ubuntu Linux Python 3 is installed using following command from terminal

$sudo apt-get install python3-minimal


The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python:

Python Official Website : http://www.python.org/

You can download Python documentation from the following site. The documentation is available in HTML, PDF and PostScript formats.

Python Documentation Website : http://www.python.org/doc/

Setting up PATH
Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables.

The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs.

The path variable is named as PATH in Unix or Path in Windows (Unix is case-sensitive; Windows is not).

In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path.

Setting path at Unix/Linux
To add the Python directory to the path for a particular session in Unix:

·        In the csh shell: type

Code:
setenv PATH "$PATH:/usr/local/bin/python3"

and press Enter.

·        In the bash shell (Linux): type

Code:
export PYTHONPATH=/usr/local/bin/python3.4

and press Enter.

·        In the sh or ksh shell: type

Code:
PATH="$PATH:/usr/local/bin/python3"

and press Enter.

Note: /usr/local/bin/python3 is the path of the Python directory

Setting path at Windows
To add the Python directory to the path for a particular session in Windows:

·        At the command prompt : type 
path %path%;C:\Python and press Enter.
It takes so long to learn simplicity.
Reply
#3
Python Variable Types
Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.

Assigning Values to Variables
Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example −


Code:
#!/usr/bin/python

 

counter = 100          # An integer assignment

miles   = 1000.0       # A floating point

name    = "John"       # A string

 

print counter

print miles

print name

Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables, respectively. This produces the following result −

100

1000.0

John

Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example −

a = b = c = 1

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example −

            a, b, c = 1, 2, "john"

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "john" is assigned to the variable c.

Standard Data Types
The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.

Python has five standard data types


·        √Numbers

·        √String

·        √List

·        √Tuple

·        √Dictionary

Python Numbers
Number data types store numeric values. Number objects are created when you assign a value to them. For example −

var1 = 1

var2 = 10

You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −

del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement. For example −

del var

del var_a, var_b

Python supports four different numerical types −

·        √int (signed integers)

·        √long (long integers, they can also be represented in octal and hexadecimal)

·        √float (floating point real values)

·        √complex (complex numbers)
It takes so long to learn simplicity.
Reply
#4
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.

For example −

Code:
#!/usr/bin/python

 

str = 'Hello World!'

 

print str          # Prints complete string

print str[0]       # Prints first character of the string

print str[2:5]     # Prints characters starting from 3rd to 5th

print str[2:]      # Prints string starting from 3rd character

print str * 2      # Prints string two times

print str + "TEST" # Prints concatenated string

This will produce the following result −

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.

The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

For example −

Code:
#!/usr/bin/python

 

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

tinylist = [123, 'john']

 

print list          # Prints complete list

print list[0]       # Prints first element of the list

print list[1:3]     # Prints elements starting from 2nd till 3rd

print list[2:]      # Prints elements starting from 3rd element

print tinylist * 2  # Prints list two times

print list + tinylist # Prints concatenated lists

This produce the following result −

['abcd', 786, 2.23, 'john', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
It takes so long to learn simplicity.
Reply
#5
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example −


Code:
#!/usr/bin/python

 

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )

tinytuple = (123, 'john')

 

print tuple           # Prints complete list

print tuple[0]        # Prints first element of the list

print tuple[1:3]      # Prints elements starting from 2nd till 3rd

print tuple[2:]       # Prints elements starting from 3rd element

print tinytuple * 2   # Prints list two times

print tuple + tinytuple # Prints concatenated lists

This produce the following result −

('abcd', 786, 2.23, 'john', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')

The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists −


Code:
#!/usr/bin/python

 

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )

list = [ 'abcd', 786 , 2.23, 'john', 70.2  ]

tuple[2] = 1000    # Invalid syntax with tuple

list[2] = 1000     # Valid syntax with list

Python Dictionary
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).


For example −

Code:
#!/usr/bin/python

 

dict = {}

dict['one'] = "This is one"

dict[2]     = "This is two"

 

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
 

print dict['one']       # Prints value for 'one' key

print dict[2]           # Prints value for 2 key

print tinydict          # Prints complete dictionary

print tinydict.keys()   # Prints all the keys

print tinydict.values() # Prints all the values

This produce the following result −

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered.
It takes so long to learn simplicity.
Reply
#6
Python Functions
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.

Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a function in Python.

·        √Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).

·        √Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.

·        √The first statement of a function can be an optional statement - the documentation string of the function or docstring.

·        √The code block within every function starts with a colon (Smile and is indented.

·        √The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

Syntax
def functionname( parameters ):

   "function_docstring"

   function_suite

   return [expression]

By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.

Example
The following function takes a string as input parameter and prints it on standard screen.

Code:
def printme( str ):

   "This prints a passed string into this function"

   print str

   return

Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function −

#!/usr/bin/python

 

# Function definition is here

def printme( str ):

   "This prints a passed string into this function"

   print str

   return;

 

# Now you can call printme function

printme("I'm first call to user defined function!")

printme("Again second call to the same function")

When the above code is executed, it produces the following result −

I'm first call to user defined function!

Again second call to the same function

Pass by reference vs value
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example −

#!/usr/bin/python

 

# Function definition is here

def changeme( mylist ):

   "This changes a passed list into this function"

   mylist.append([1,2,3,4]);

   print "Values inside the function: ", mylist

   return

 

# Now you can call changeme function

mylist = [10,20,30];

changeme( mylist );

print "Values outside the function: ", mylist

Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result −

Values inside the function:  [10, 20, 30, [1, 2, 3, 4]]

Values outside the function:  [10, 20, 30, [1, 2, 3, 4]]

There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.

#!/usr/bin/python

 

# Function definition is here

def changeme( mylist ):

   "This changes a passed list into this function"

   mylist = [1,2,3,4]; # This would assign new reference in mylist

   print "Values inside the function: ", mylist

   return

 

# Now you can call changeme function

mylist = [10,20,30];

changeme( mylist );

print "Values outside the function: ", mylist

The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist.

The function accomplishes nothing and finally this would produce the following result:

Values inside the function:  [1, 2, 3, 4]

Values outside the function:  [10, 20, 30]

Function Arguments
You can call a function by using the following types of formal arguments:

·        √Required arguments

·        √Keyword arguments

·        √Default arguments

·        √Variable-length arguments
It takes so long to learn simplicity.
Reply
#7
The road looks complicated, anybody to guide me or we are both lost?
I am a proud member of NIgerian Coders Team
Reply
#8
(11-01-2016, 09:58 PM)Aphatheology Wrote:
The road looks complicated, anybody to guide me or we are both lost?


A PC is required to make it easier, so you practice as you learn.
It takes so long to learn simplicity.
Reply
#9
(11-02-2016, 06:49 AM)Dealwap Wrote:
A PC is required to make it easier, so you practice as you learn.


qpython nkor
Reply


Possibly Related Threads...
Thread Author Replies Views Last Post
  FUN: Rhombus With Python Mbabalawlar 0 87 01-06-2018, 10:00 PM
Last Post: Mbabalawlar
  FUN: Love Calculator With Python Mbabalawlar 0 118 01-06-2018, 09:56 PM
Last Post: Mbabalawlar
  TUTORIAL: My First Project Quiz In Python Programming Mbabalawlar 0 100 01-06-2018, 09:50 PM
Last Post: Mbabalawlar
  SHARED: Why Learn Python? cheatex 5 455 04-27-2017, 08:54 PM
Last Post: devHammed
  Creating A Simple Random Username And Password Generator With Python Jolliano 4 688 01-01-2017, 10:58 PM
Last Post: Jolliano
  Python Program To Solve Quadratic Equation dealwap 4 664 12-10-2016, 08:43 AM
Last Post: dealwap
  Awesome Python Tricks A Beginner Should Know smartlord 8 717 12-04-2016, 01:48 PM
Last Post: Ahkohd
  How To Validate User's Input In Python Ahkohd 1 307 12-03-2016, 12:39 PM
Last Post: dealwap
  Check If A Variable Is Defined Or Not In Python Ahkohd 0 260 12-03-2016, 09:42 AM
Last Post: Ahkohd
  Why You Should Learn Python As Your First Programming Language dealwap 0 352 11-04-2016, 07:37 AM
Last Post: dealwap



Users browsing this thread: 1 Guest(s)

About Nigeria's Creative Talents

Nigeria's Creative Talents is an online community where every creative Nigerians can share ideas with themselves.

For any more information, please use our contact form.

              User Links

              Advertise