Python

Python Tutorial with Exercises29 min read

For beginner Python programmers, the main ones are that the print statement of Python 2.x is now a printfunction in Python 3, the raw_input function in Python 2.x is replaced by the input function in Python 3, and an integer division such as 2/3 in Python 2.x is now a real division in Python 3.

So be aware that there are some significant differences between Python 3 and earlier versions.

The following tutorials help you to learn Python 3 programming language by basicly.




Python 3 Tutorials

The first Python program has only one executable line.

Program 1: Print “Hello World”

Python 3 Input

Input means getting data into your program from an input device (usually the keyboard).

Python needs a place to store whatever value is input. These storage places are known as variables, and have to have a name.

In the Python 3 statement below, the variable’s name is text.

The above Python statement, when executed (i.e. run) will output to the screen whatever is within the quote marks. This text is sometimes refered to as a “Enter some thing:”. Python then waits for you to enter something from the keyboard.

Type in some text and then press the Enter key on the keyboard. Whatever you typed in before you hit the Enter key is stored into the variable called text. text is the variable where the input data is stored.

The Assignment symbol =

The purpose of the assignment symbol is to place whatever you typed in, into the variable on its left.

Built-in functions

input(), int() and float() , str() are built-in Python functions. They can be used at any time in any Python statement.

Data types of input values

You can always check the data type of any variable by using the type() built-in function.

 

Program 2: Print given text

 

Program 3: Note that \n within quote marks a new line to be printed

 

Program 4: Use variable

 

Program 5: Calculate the Average of 3 Numbers

 

Program 6: Calculate the Average of Numbers in a Given List

 

Program 7: Calculate the average of 3 numbers using “while”

Examples of use of arithmetic operators

Program 8: Using operands

 

Program 9:

Examples of use of Boolean expressions

Program 10: Python stores true as integer 1, and false as integer 0 but outputs ‘true’ or ‘false’ from print statements

Program 11: string objects and string assignments

 

Program 12: Convert the integer to a string first to concatenate a string and an integer

 

Program 13: Round up a floating point number to the nearest integer

 

Program 14: Round a float number to 2 decimal places, and output that number as € currency printed with a comma after the number of thousands

 

Program 15: Converting one data type to another

 

Program 16: Displaying an object’s memory location

 

if statement

An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.

The else statement is an optional statement and there could be at most only one else statement following if.

Syntax

The syntax of the if…else statement is −

 

Program 17: Displaying boolean values

 

Program 18: Combining boolean expressions with and

 

Program 19: The if statement

 

Program 20: The if statement with multiple statements

 

Program 21: The if statement with multiple statements

 

Program 22: A nested if example (an if statement within another if statement)

 

Program 23: A nested if example – using if/else

 

Program 24: A nested if example – using if/elif/else

 

Program 25: Demo of DeMorgan’s Laws

a Not And is equivalent to an Or with two negated inputs or a Not Or is equivalent to an And with two negated inputs

 

Program 26: Decision using two conditions linked with an and or an or

 

Python while Loop Statements

while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.

Syntax

The syntax of a while loop in Python programming language is −

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop.

In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.

 

Program 27: Examples of while loops

 

Program 28: Examples of while loops

 

Program 29: Examples of while loops – the infinite loop

 

Program 30: Examples of while loops – another infinite loop

 

Program 31: Example of break to end an infinite loop

 

Program 32: Example of continue to end an infinite loop

 

Program 33: ‘sentinel-controlled’ while loop

 

Python for Loop Statements

It has the ability to iterate over the items of any sequence, such as a list or a string.

Syntax

If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.

 

Program 34: Example of the counter-controlled for loop

 

Program 35: Example of the counter-controlled for loop

 

Program 36: ‘continue’ with the for loop

 

Program 37: ‘break’ with the for loop

 

Program 38: Outputting strings and numbers in a single print statement

 

Program 39: Outputting strings and numbers in a single printstatement using string formatting.

 

Program 40: Repeat a program at the user’s request

 

Program 41: Use a loop within a loop

 

Program 42: Use a loop within a loop

 

Program 43: Use a loop within a loop

 

Program 44: Use a loop within a loop

 

Program 45: Using the built-in square root function math.sqrt
To use any math function, you have to include the statement: import math in your program – usually at the top, but can be anywhere.

 

Program 46: Using the dir function to list out the names of available functions in the math module

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 (:) 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

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

 

Program 47: Showing functions which have no return statement

 

Program 48: Using a programmer-defined function

 

Program 49: Using two programmer-defined functions

 

Program 50: Importing programmer-defined functions

Save codes as myFun.py

 

Program 51: Function with no return statement

 

Program 52: Function with two return statements

 

Program 53: Function with no arguments

 

Program 54: Program with a Boolean function

 

Program 55: Polymorphic function

Polymorphism : the meaning of the operations depends on the objects being operated on. The * operator is said to be “overloaded”

 

Program 56: The scope of a variable

Local scope means the variable is only available in the function where it is defined. Global scope means the variable is available everywhere in the code.

Python Lists

The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number – its position or index. The first index is zero, the second index is one, and so forth.

Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial.

There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements.

The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type.

 

Program 57: Creating and using a Python list

 

Program 58: Creating and printing an empty list

 

Program 59: Appending to an empty list

 

Program 60: List of lists

 

Program 61: Accessing the last item in a list

 

Program 62: Deleting items from a list

 

Program 63: Repeating lists

 

Program 64: List indexing

 

Program 65: Finding the length of a list

 

Program 66: Concatenating lists

 

Program 67: List iteration

 

Program 68: List membership

 

Program 69: Selection of list methods

Program 70: Sequential search of a list

 

Program 71: Sequential search of a list

 

Program 72: binarysearch

 

Program 73: biglist

 

Program 74: Program which demonstrates a bubble sort on a list of 10 random integers

 

Python Strings

Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable.

Program 75: Strings

 

Program 76: Using an apostrophe within a string and using double quote marks within a string

 

Program 77: Multiplying numbers and multiplying strings

 

Program 78: String concatenation

 

Program 79: String indexing

 

Program 80: String slicing

 

Program 81: Finding the length of a string

 

Program 82: %s string formatting code

 

Program 83: Finding a string within a string

 

Program 84: Changing a string within a string

 

Program 85: Escape sequences within a string

 

Program 86: Iteration and membership with strings

 

Program 87: Demonstration of printing Unicode characters

 

Opening and Closing Files

Until now, you have been reading and writing to the standard input and output. Now, we will see how to use actual data files.

Python provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object.

The open Function

Before you can read or write a file, you have to open it using Python’s built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it.

Syntax

Here are parameter details −

  • file_name − The file_name argument is a string value that contains the name of the file that you want to access.
  • access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r).
  • buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).

 

Program 83: Program which uses a file

 

Program 88: Program which uses a file

 

Program 89: Program which uses a file

 

Program 90: Program which uses a file

Object Oriented

Python has been an object-oriented language since it existed. Because of this, creating and using classes and objects are downright easy. This chapter helps you become an expert in using Python’s object-oriented programming support.

If you do not have any previous experience with object-oriented (OO) programming, you may want to consult an introductory course on it or at least a tutorial of some sort so that you have a grasp of the basic concepts.

However, here is small introduction of Object-Oriented Programming (OOP) to bring you at speed

Overview of OOP Terminology

  • Class − A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.
  • Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class’s methods. Class variables are not used as frequently as instance variables are.
  • Data member − A class variable or instance variable that holds data associated with a class and its objects.
  • Function overloading − The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved.
  • Instance variable − A variable that is defined inside a method and belongs only to the current instance of a class.
  • Inheritance − The transfer of the characteristics of a class to other classes that are derived from it.
  • Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.
  • Instantiation − The creation of an instance of a class.
  • Method − A special kind of function that is defined in a class definition.
  • Object − A unique instance of a data structure that’s defined by its class. An object comprises both data members (class variables and instance variables) and methods.
  • Operator overloading − The assignment of more than one function to a particular operator.

 

Program 91: Create objects of the Person class and how to inspect the state of those objects.

 

Program 92: Use accessor methods

 

Program 93: Use accessor and mutator methods

 

Source:

www.annedawson.net

www.tutorialspoint.com

 

Leave a Comment