Python Programming Introduction

python programming introduction

What is Python

Python is a interactive programming language. Simple syntex of the language makes Python programs easy to read and write. Python was developed by Guido Van Rossum in 1991 at the national research institute for Mathematics and Computer Science in the Netherlands. Guido Van Rossum named Python by getting inspired from his favourite comedy show Monty Python's Flying Circus.
Ever since the language was developed, it is becoming popular day by day amongst the programmers. Various versions of python have been released till date ranging from versions 1.0 . This website is used python 3.0. Python is used in various application area such as the web, gaming,scientific and numeric computing, text processing, and network programming.


IDLE-AN INTERPRETER FOR PYTHON

IDLE stands for integrated Development and learning Environment. Python IDLE comprises Python shell and Python Editor. While Python shell is an interactive interpreter,Python Editor allows us to work in script mode. While using Python shell, we just need to type python code at the >>>prompt and press the enter key, and the shell will respond with the result of the computation. For Example, when we type
>>>print('Hello World')
and press the enter key, Python shell will display:
hello World
Python shell may also be used as a calculator, for example, when we type 18 + 5 followed by enter , Python shell output the value of the expression, i.e, 23 , as shown below:
>>>18 + 5
23

The expression 18+5 yield the value 23. Similarly, the expression 18-5 yield 13. THe expression 18*5 yield 90. as Python uses * as the symbol for the multiplication operation. The expression 27/5 yield 5.4 . Note that the result of division 27/5 is real number. In python result of diviesion is always a real number .Python operator // (two slashes without any intervening blank) can be used. For example, 27//5 yields 5 .
>>>18+5
23
>>>18*5
90
>>>27/5
5.4
>>>27//5
5
27.0//5
5.0
>>>27%5
2
>>>3**2
9

Table 1.1 Precedence of arithmetic operator
() (parentheses)
** (exponentiation)
- (Negative) / (division)
// (integer division)
* (multiplication)
%(Modules)
+ (addition)
- (subtraction)

PYTHON STRINGS

A string is a sequence of characters. To specify a string, we may enclose a sequence of characters between single, double, or triple quotes. Thus, 'Hello World' , ' "Zeeshan " ', "what's ", '''today's "action" plan?''' are the examples of strings. A string enclosed in single quotes may include double quote marks and vice versa. A string enclosed in triple quotes (also known as docstring. i.e, documentation string) may include both single and double quote marks and may extend over several lines, for example:

>>>'Hello World'
'Hello World'
>>>print('Hello World')
Hello World
>>> """Hello
What's
happening"""
"Hello\nWhat's\nhappening"
>>>print("""Hello
What's
happening""")
Hello
What's
happening

Note that enclosing quote marks are used only to specify a string, and they do not form part of the string. When we print a string using the print instruction, the value of the string, i.e, the sequence of characrters within quotes is printed. Aslo, note that, within a string, \n denotes the beginning of a new line. When a string having \n is printed, everything after \n (excluding \n) is printed on the next line. In this section, we shall study basic operations on strings. Let us begin with the concatenartion operator (+), which is used to produce a string by concatenating two string; for example, the expression 'hello ' + '!!' yields the string 'hello !!' . Similarly, the expression 'how' + ' are' + 'you?' yields 'how are you?' (=('how' + ' are') + ' you') as shown below:
>>>'hello ' + '!!'
'hello !!'
>>> 'how' + ' are' + ' you?'
'how are you?'


The operator * (multiplication) is used to repeat a string a specified number of time; for example, the expression 'hello' * 5 yields the string 'hellohellohellohellohello':
>>> 'hello' * 5
'hellohellohellohellohello'


RELATIONAL OPERATORS

Relation operators are used for comparing two expressions and yield True or False. In an expression involving both arithmetic and relational operators, the arithmetic operators have heigher precedence than the relational operators. In Table 1.2, we give a list of relational operators
Table 1.2 Relational operators
== (equal to)
< (less than)
> (greater than)
<= (less than or equal to)
> = (greater than or equal to)
!= (not equal to)

A relation operator applied on expressions takes the following form:
Thus, the expressions, 23< 25, 23 != 23, and 23 - 2.5 >=5 * 4 , yield True, False, and True, respectively. As arithmetic operators have higher precedence then the relational operators, the expression 23 - 2.5 >= 5 * 4 is evaluated as if it were (23 - 2.5) >= (5 * 4|). When the relational operators are applied to strings, strings are compared left to right, character by charactor, based on their ASCII codes, also called ASCII value. For example, ASCII codes of 'A' - 'Z', 'a' - 'z', and '0' - '9' lie in the range [65,90], [97,122], and [48,57], respectively. Thus, 'h' > 'H' yields True as ASCII value of 'h' (=144) is greater then ASCII value of 'H' (=72). Also 'hello' > 'Hello' yields True since 'h' is greater than 'H' . Similarly, 'hi' > 'hello' yields True because the first characrter in the two strings is identical and ASCII codes of 'i' is greater than ASSCII code of 'e'. Also, if a string is a prefix of another string, the longer strig will be considered larger.

LOGICAL OPERATORS

The logical operators not , and , and or are applied to logical operands True and False, also called Boolean values, and yield either True or False. The operator not is a unary operator, i.e, it requires only one operand. The expression not True and not False yield False and True, respectively. An expression involving two Boolean operands and the and operator yield True if both the operands are True, and False otherwise. Similarly, an expression involving two Boolean operands and the or operator yields True if at least one operand is True, and False otherwise.

>>>(10<5) and ((5/0) < 10)
False



VARIABLES AND ASSIGNMENT STATEMENT

Variables provide a means to name values so that they can be used and manipulated later on. Indeed, a program essentially carries out variable manipulations to achieve the desired objective. For example, variables english, maths, and commerce may be used to deal with the marks obtained in these subjects, and the variables totalMarks and percentage may be used to deal with aggregate marks and the overall percentage of marks, respectively. If a student has obtained 57 marks in english, this may be expressed in Python using the following statement: >>> english = 57 When the above statement is executed, Python associates the variable english with value 57. We can also say that the the variable english is assigned the value 57, or that the variable english refers to value 57. Such a statement that assigns value to a variable is called an assignment statement. we see that the variable english refers to the value 57.
In Python style (often called Pythonic style, or Pythonic way), variables are called names, and an assignment is called an association or a binding. Thus, we say that the name english has been associated with the data object 57, or that the variable english has been bound to the data object 57. Note that, unlike an expression, on the execution of an assignment statement, IDLE does not respond with any output. Of course, the value of the variable english can be displayed as follows: >>> english
57

In the above example, english is a variable whose value is 57. Similarly, the following statements will assign values 64 and 62 to the variables maths and commerce, respectively. >>> maths - 64
>>> commerce 62

In this example, we assume that maximum mark in each subject is 100. Total marks in these three subjects and overall percentage can be computed using another sequence of statements:
>>> totalMarks english + maths + commerce
>>> percentage (totalMarks / 300) 100
>>> percentage:
61.

Assignment Statement


As discussed above, values are assigned to variables using an assignment statement. The syntax for assignment statement is as follows:
variable = expression
where expression may yield a value such as numeric, string, or Boolean. Inm an assignment statement, the expression on the right-hand side of the equal to operator (-) is evaluated and the value so obtained is assigned to the variable on the left-hand side of the operator. We have already seet some examples of variables. In general, we must follow the following rules while using the variables:
● A variable must begin with a letter or (underscore character)
● A variable may contain any number of letters, digits, or underscor characters. No other character apart from these is allowed.
Thus, marks, name, max_marks, _emp, maxMarks, nl, and max_of_3_numbers are valid variables.However, note that the following are not valid variables: total_no.
1st_number
AmountIn$
Total Amount

It is a good programming practice to make sure that the variables are meaningful as carefully chosen variables make your code readable. For example, to denote the total marks obtained, it is easy to understand what the variable totalMarka represents than a variable a, x. marks or total used for the same purpose. There are several styles of forming variables, for example:
total_marks
TotalMarks
totalMarks
TOTAL_MARKS
However, one must be consistent in following a style. In this book, we prefer to use the lowerCamelCase style in which the first letter of every word is capitalized, except the first word which begins with a lowercase letter, for example, totalMarks. While forming variables, it is important to note that Python is case-sensitive. Thus, age and Age are different variables. So, if we assign a value to the variable age and display the value of Age. the system will respond with an error message. >>> age = 24
>>> Age

Traceback (most recent call last):
File "", line 1, in
Age
NameError: name 'Age' is not defined
Next, let us examine the following statements:
>>> a = 5
>>> b = a
>>>a = 7

Shorthand Notation

By now, we have seen several examples of assignment statements. The following assignment statement updates value of the variable a by adding 5 to the existing value.
>>>a = a + 5
Alternatively, we can write the above statement as
>>> a += 5
Thus, the operator+-serves as shorthand notation in assignment statement Similarly, the statements
>>> a = a + b + c
>>> a - a ** (b + c)

can be written as follows, respectively:
>>> a += b + c
>>> a **= b + c

As the shorthand notation works for all binary mathematical operators, a b
is equivalent to
a = b
Python also allows multiple assignments in a single statement; for example, the following sequence of three assignment statements
>>> msg= 'Meeting'
>>> day = 'Mon'
>>> time = '9'

may be replaced by a single statement:
>>> msg, day, time = 'Meeting', 'Mon', '9'
Thus, we can specify more variables than one on the left side of an assignment statement, and the corresponding number of expressions, like , , , ,..., , , ...
This notation can be used to enhance the readability of the program. We may also assign a common value to multiple variables, for example, the assignment statement >>> totalMarks = count = 0
may be used to replace the following two assignments:
>>> totalMarks = 0
>>> count = 0

Suppose we wish to swap values of two variables, say, numi and num2. For this purpose, we use a variable temp as follows:
>>> numl, num2 = 10, 20
>>> temp = numl
>>> num1 = num2
>>> num2 = temp
>>> print (numl, num2)
20 10

Note that before executing the assignment statement
numi = num2
we save the value of the variable num1 in the variable temp, so that the same can be assigned to the variable num2 in the following assignment statement. A variable that is used to hold the value of another variable temporarily is often called temporary variable.
Alternatively, we can use the following statement to swap the values of two variables:
>>> numl, num2 = num2, num1



SCRIPT MODE

So far, we have done all work using Python shell, an interactive environment of IDLE. The definitions of objects, names, etc., exist only during an IDLE session. When we exit an IDLE session, and start another IDLE session, we must redo all computations. This is not a convenient mode of operation for most of the computational tasks. Python provides another way of working called script mode. All the instructions necessary for a task are stored in a file often called a source file script, program, source code, or a module. Python requires that such a file must have extension .py or -pyw. To create a script, Python IDLE provides a New Window option in the File menu. On clicking the New Window option, a Python Editor window opens, where we can write a sequence of instructions, collectively called a program or a script. A script can be saved using the Save As option in the File menu. It may be executed in shell by selecting Run Module option in the Run menu. As a trivial example, the script readNshow in takes two numbers from the user and outputs these numbers. On executing the first line of the script, the system waits for the user to enter a number which is assigned to the variable number1. On executing the second line of the script, the system waits for the user to enter another number which is assigned to the variable number2. The values of variables numberland number 2 are displayed on executing the third line of the script.
The problem with the above script is that as we have developed it just now, we remember that the program requires two numbers as the input. However, if we wish to use it a month later, we may forget what inputs are required by the program, and we will need to examine the program again before running it. Surely, we would like to avoid this effort. A good programming practice is to display to the user what data is to be entered. The modified script readNshowWell achieves this by displaying a message to the user as the system waits for user input.


0 Response to "Python Programming Introduction"

ads