From 6684e4613836b2d4ac04daf24e993a0fbd55a799 Mon Sep 17 00:00:00 2001 From: Kushal Das Date: Sat, 9 May 2015 11:41:13 +0530 Subject: [PATCH] Merging changes from py3 branch. --- docs/datastructure.rst | 28 ++++++++--------- docs/file.rst | 30 +++++++++--------- docs/functions.rst | 46 ++++++++++++++-------------- docs/ifelse.rst | 24 +++++++-------- docs/index.rst | 3 +- docs/installation.rst | 12 +++++--- docs/looping.rst | 52 +++++++++++++++---------------- docs/operatorsexpressions.rst | 24 +++++++-------- docs/projectstructure.rst | 4 +-- docs/strings.rst | 8 ++--- docs/variablesanddatatypes.rst | 56 ++++++++++++++-------------------- 11 files changed, 139 insertions(+), 148 deletions(-) diff --git a/docs/datastructure.rst b/docs/datastructure.rst index d4eb243..bfaa8e7 100644 --- a/docs/datastructure.rst +++ b/docs/datastructure.rst @@ -170,7 +170,7 @@ Tuples are data separated by comma. >>> a[1] 'Debian' >>> for x in a: - ... print x, + ... print(x, end=' ') ... Fedora Debian Kubuntu Pardus @@ -316,7 +316,7 @@ If you want to loop through a dict use *iteritems()* method. >>> data {'Kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'} >>> for x, y in data.iteritems(): - ... print "%s uses %s" % (x, y) + ... print("%s uses %s" % (x, y)) ... Kushal uses Fedora Jace uses Mac @@ -355,7 +355,7 @@ If you want to loop through a list (or any sequence) and get iteration number at :: >>> for i, j in enumerate(['a', 'b', 'c']): - ... print i, j + ... print(i, j) ... 0 a 1 b @@ -368,7 +368,7 @@ You may also need to iterate through two sequences same time, for that use *zip( >>> a = ['Pradeepto', 'Kushal'] >>> b = ['OpenSUSE', 'Fedora'] >>> for x, y in zip(a, b): - ... print "%s uses %s" % (x, y) + ... print("%s uses %s" % (x, y)) ... Pradeepto uses OpenSUSE Kushal uses Fedora @@ -392,11 +392,11 @@ In this example , you have to take number of students as input , then ask marks data[name] = marks for x, y in data.iteritems(): total = sum(y) - print "%s 's total marks %d" % (x, total) + print("%s 's total marks %d" % (x, total)) if total < 120: - print "%s failed :(" % x + print("%s failed :(" % x) else: - print "%s passed :)" % x + print("%s passed :)" % x) The output @@ -426,24 +426,24 @@ In this example we will multiply two matrices. First we will take input the numb #!/usr/bin/env python n = int(raw_input("Enter the value of n: ")) - print "Enter values for the Matrix A" + print("Enter values for the Matrix A") a = [] for i in range(0, n): a.append([int(x) for x in raw_input("").split(" ")]) - print "Enter values for the Matrix B" + print("Enter values for the Matrix B") b = [] for i in range(0, n): b.append([int(x) for x in raw_input("").split(" ")]) c = [] for i in range(0, n): c.append([a[i][j] * b[j][i] for j in range(0,n)]) - print "After matrix multiplication" - print "-" * 10 * n + print("After matrix multiplication") + print("-" * 10 * n) for x in c: for y in x: - print "%5d" % y, - print "" - print "-" * 10 * n + print("%5d" % y, end=' ') + print("") + print("-" * 10 * n) The output diff --git a/docs/file.rst b/docs/file.rst index b56cb40..1567d5d 100644 --- a/docs/file.rst +++ b/docs/file.rst @@ -79,8 +79,8 @@ You can even loop through the lines in a file object. :: >>> fobj = open("sample.txt") - >>> for x in fobj: - ... print(x, end='') + >>> for x in f: + ... print(x, end=' ') ... I love Python Pradeepto loves KDE @@ -90,10 +90,10 @@ Let us write a program which will take the file name as the input from the user :: - #!/usr/bin/env python - name = raw_input("Enter the file name: ") + #!/usr/bin/env python3 + name = input("Enter the file name: ") fobj = open(name) - print fobj.read() + print(fobj.read()) fobj.close() In the last line you can see that we closed the file object with the help of close() method. @@ -141,11 +141,11 @@ In this example we will copy a given text file to another file. :: - #!/usr/bin/env python + #!/usr/bin/env python3 import sys if len(sys.argv) < 3: - print "Wrong parameter" - print "./copyfile.py file1 file2" + print("Wrong parameter") + print("./copyfile.py file1 file2") sys.exit(1) f1 = open(sys.argv[1]) s = f1.read() @@ -162,12 +162,12 @@ The first value in *sys.argv* is the name of the command itself. :: - #!/usr/bin/env python + #!/usr/bin/env python3 import sys - print "First value", sys.argv[0] - print "All values" + print("First value", sys.argv[0]) + print("All values") for i, x in enumerate(sys.argv): - print i, x + print(i, x) The output @@ -224,7 +224,7 @@ Let us try to write an application which will count the spaces, tabs, and lines :: - #!/usr/bin/env python + #!/usr/bin/env python3 import os import sys @@ -261,7 +261,7 @@ Let us try to write an application which will count the spaces, tabs, and lines """ if os.path.exists(path): spaces, tabs, lines = parse_file(path) - print "Spaces %d. tabs %d. lines %d" % (spaces, tabs, lines) + print("Spaces %d. tabs %d. lines %d" % (spaces, tabs, lines)) return True else: return False @@ -318,4 +318,4 @@ line by line and find out the number of CPU(s). .. tip:: Always remember to read files line by line than reading them as a whole. Sometimes you may have to read files which are way bigger than your available RAM. -After you do this, try to write your own lscpu command in Python :) +After you do this, try to write your own lscpu command in Python :) \ No newline at end of file diff --git a/docs/functions.rst b/docs/functions.rst index 9a0e83e..9162546 100644 --- a/docs/functions.rst +++ b/docs/functions.rst @@ -35,15 +35,15 @@ Remember the palindrome program we wrote in the last chapter. Let us write a fun :: - #!/usr/bin/env python + #!/usr/bin/env python3 def palindrome(s): return s == s[::-1] if __name__ == '__main__': - s = raw_input("Enter a string: ") + s = input("Enter a string: ") if palindrome(s): - print "Yay a palindrome" + print("Yay a palindrome") else: - print "Oh no, not a palindrome" + print("Oh no, not a palindrome") Now run the code :) @@ -54,15 +54,15 @@ To understand local and global variables we will go through two examples. :: - #!/usr/bin/env python + #!/usr/bin/env python3 def change(b): a = 90 - print a + print(a) a = 9 - print "Before the function call ", a - print "inside change function", + print("Before the function call ", a) + print("inside change function", end=' ') change(a) - print "After the function call ", a + print("After the function call ", a) The output :: @@ -76,16 +76,16 @@ First we are assigning *9* to *a*, then calling change function, inside of that :: - #!/usr/bin/env python + #!/usr/bin/env python3 def change(b): global a a = 90 - print a + print(a) a = 9 - print "Before the function call ", a - print "inside change function", + print("Before the function call ", a) + print("inside change function", end=' ') change(a) - print "After the function call ", a + print("After the function call ", a) Here by using global keyword we are telling that *a* is globally defined, so when we are changing a's value inside the function it is actually changing for the *a* outside of the function also. @@ -137,8 +137,8 @@ To avoid this you can write more idiomatic Python, like the following >>> def f(a, data=None): ... if data is None: ... data = [] - ... data.append(a) - ... return data + ... data.append(a) + ... return data ... >>> print f(1) [1] @@ -152,7 +152,7 @@ Keyword arguments :: >>> def func(a, b=5, c=10): - ... print 'a is', a, 'and b is', b, 'and c is', c + ... print('a is', a, 'and b is', b, 'and c is', c) ... >>> func(12, 24) a is 12 and b is 24 and c is 10 @@ -166,7 +166,7 @@ In the above example you can see we are calling the function with variable names :: >>> def func(a, b=13, v): - ... print a, b, v + ... print(a, b, v) ... File "", line 1 SyntaxError: non-default argument follows default argument @@ -201,7 +201,7 @@ In Python we use docstrings to explain how to use the code, it will be useful in :: - #!/usr/bin/env python + #!/usr/bin/env python3 import math def longest_side(a, b): @@ -216,7 +216,7 @@ In Python we use docstrings to explain how to use the code, it will be useful in return math.sqrt(a*a + b*b) if __name__ == '__main__': - print longest_side(4, 5) + print(longest_side(4, 5)) We will learn more on docstrings in reStructuredText chapter. @@ -237,9 +237,9 @@ In Python any function can act as higher order function. ... return func(value) ... >>> lst = high(dir, int) - >>> print lst[-3:] + >>> print(lst[-3:]) ['imag', 'numerator', 'real'] - >>> print lst + >>> print(lst) .. note:: To know more read `this link `_. @@ -256,6 +256,6 @@ Example:: ... "Returns the square of a given number." ... return num * num ... - >>> print map(square, lst) + >>> print(map(square, lst)) [1, 4, 9, 16, 25] diff --git a/docs/ifelse.rst b/docs/ifelse.rst index c5cdff3..c0fba46 100644 --- a/docs/ifelse.rst +++ b/docs/ifelse.rst @@ -20,10 +20,10 @@ If the value of *expression* is true (anything other than zero), do the what is :: - #!/usr/bin/env python - number = int(raw_input("Enter a number: ")) + #!/usr/bin/env python3 + number = int(input("Enter a number: ")) if number < 100: - print "The number is less than 100" + print("The number is less than 100") Then we run it @@ -40,12 +40,12 @@ Now in the above example we want to print "Greater than" if the number is greate :: - #!/usr/bin/env python - number = int(raw_input("Enter a number: ")) + #!/usr/bin/env python3 + number = int(input("Enter a number: ")) if number < 100: - print "The number is less than 100" + print("The number is less than 100") else: - print "The number is greater than 100" + print("The number is greater than 100") The output @@ -59,16 +59,16 @@ Another very basic example :: - >>> x = int(raw_input("Please enter an integer: ")) + >>> x = int(input("Please enter an integer: ")) >>> if x < 0: ... x = 0 - ... print 'Negative changed to zero' + ... print('Negative changed to zero') ... elif x == 0: - ... print 'Zero' + ... print('Zero') ... elif x == 1: - ... print 'Single' + ... print('Single') ... else: - ... print 'More' + ... print('More') Truth value testing =================== diff --git a/docs/index.rst b/docs/index.rst index 4fdbd0d..db0fdfc 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -8,8 +8,7 @@ Welcome to Python for you and me This is a simple book to learn Python programming language, it is for the programmers who are new to Python. - -The Python 2.x version of the same book can be found `here `_. +The Python 2.x version of the same book can be found `here `_. Contents: diff --git a/docs/installation.rst b/docs/installation.rst index 3b8215f..5e610ca 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -4,28 +4,30 @@ Installation ============ -In this chapter you will learn how to install Python +In this chapter you will learn how to install Python3, the latest of the language. + On Windows ========== -You have to download the latest Windows(TM) installer from the Python site http://www.python.org/ftp/python/2.7.3/python-2.7.3.msi . Install it just as any other Windows software. +You have to download the latest Windows(TM) installer from the Python site, `x86_64 `_ and +`i686 `_. Install it just as any other Windows software. On GNU/Linux ============ -Generally all GNU/Linux distributions come with Python, so no need to worry about that :) If you don't have it then you can install it by either downloading from the Python website or from your distribution's repository. +You will have to install the latest Python from the distribution's repository. For Fedora :: - [user@host]$ sudo yum install python + [user@host]$ sudo yum install python3 For Debian :: - [user@host]$ sudo apt-get install python + [user@host]$ sudo apt-get install python3 diff --git a/docs/looping.rst b/docs/looping.rst index 820232f..86284c3 100644 --- a/docs/looping.rst +++ b/docs/looping.rst @@ -23,7 +23,7 @@ The code we want to reuse must be indented properly under the while statement. T >>> n = 0 >>> while n < 11: - ... print n + ... print(n) ... n += 1 ... 0 @@ -47,10 +47,10 @@ Let us try to solve *Fibonacci* series. In this series we get the next number by :: - #!/usr/bin/env python + #!/usr/bin/env python3 a, b = 0, 1 while b < 100: - print b + print(b) a, b = b, a + b The output @@ -72,14 +72,14 @@ The output In the first line of the code we are initializing *a* and *b*, then looping while b's value is less than 100. Inside the loop first we are printing the value of *b* and then in the next line putting the value of *b* to *a* and *a + b* to *b* in the same line. -If you put a trailing comma in the *print* statement , then it will print in the same line +In your print function call if you pass another argument called end and pass a space string, it will print in the same line with space delimiter. The default value for end is '\n'. :: - #!/usr/bin/env python + #!/usr/bin/env python3 a, b = 0, 1 while b < 100: - print b, + print(b,) a, b = b, a + b The output @@ -96,7 +96,7 @@ Let us write a program to evaluate the power series. The series looks like e**x :: - #!/usr/bin/env python + #!/usr/bin/env python3 x = float(raw_input("Enter the value of x: ")) n = term = num = 1 sum = 1.0 @@ -106,7 +106,7 @@ Let us write a program to evaluate the power series. The series looks like e**x n += 1 if term < 0.0001: break - print "No of Times= %d and Sum= %f" % (n, sum) + print("No of Times= %d and Sum= %f" % (n, sum)) The output :: @@ -139,7 +139,7 @@ In this example we are going to print the multiplication table up to 10. #!/usr/bin/env python3 i = 1 - print("-" * 50), + print("-" * 50) while i < 11: n = 1 while n <= 10: @@ -181,7 +181,7 @@ In a *print* statement if we multiply the string with an integer *n* , the strin >>> print("#" * 20) #################### >>> print("--" * 20) - --------------------------------------- + ---------------------------------------- >>> print("-" * 40) ---------------------------------------- @@ -194,7 +194,7 @@ Design 1 :: #!/usr/bin/env python3 - row = int(raw_input("Enter the number of rows: ")) + row = int(input("Enter the number of rows: ")) n = row while n >= 0: x = "*" * n @@ -215,8 +215,8 @@ The output Design 2 :: - #!/usr/bin/env python - n = int(raw_input("Enter the number of rows: ")) + #!/usr/bin/env python3 + n = int(input("Enter the number of rows: ")) i = 1 while i <= n: print("*" * i) @@ -237,7 +237,7 @@ Design 3 :: #!/usr/bin/env python - row = int(raw_input("Enter the number of rows: ")) + row = int(input("Enter the number of rows: ")) n = row while n >= 0: x = "*" * n @@ -258,7 +258,7 @@ The output Lists ===== -List datastructure + We are going to learn a data structure called list before we go ahead to learn more on looping. Lists can be written as a list of comma-separated values (items) between square brackets. @@ -329,7 +329,7 @@ There is another to loop by using *for* statement. In Python the *for* statement >>> a = ['Fedora', 'is', 'powerfull'] >>> for x in a: - ... print(x, end=" ") + ... print x, ... Fedora is powerfull @@ -340,7 +340,6 @@ We can also do things like >>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> for x in a[::2]: ... print(x) - ... 1 3 5 @@ -350,17 +349,18 @@ We can also do things like range() function ================ -range() is a buitin function. From the help document +range() is a buitin class. From the help document :: - range(...) - range([start,] stop[, step]) -> list of integers - Return a list containing an arithmetic progression of integers. - range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. - When step is given, it specifies the increment (or decrement). - For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! - These are exactly the valid indices for a list of 4 elements. +class range(object) + | range(stop) -> range object + | range(start, stop[, step]) -> range object + | + | Return a virtual sequence of numbers from start to stop by step. + | + | Methods defined here: + Now if you want to see this help message on your system type *help(range)* in the Python interpreter. *help(s)* will return help message on the object *s*. Examples of *range* function @@ -446,7 +446,7 @@ This is a very simple game of sticks. There are 21 sticks, first the user picks if sticks_taken >= 5 or sticks_taken <= 0: print("Wrong choice") continue - print("Computer took: " , (5 - sticks_taken) , "n\n") + print("Computer took: " , (5 - sticks_taken) , "\n") sticks -= 5 diff --git a/docs/operatorsexpressions.rst b/docs/operatorsexpressions.rst index 621d687..4629c95 100644 --- a/docs/operatorsexpressions.rst +++ b/docs/operatorsexpressions.rst @@ -34,11 +34,11 @@ The code :: - #!/usr/bin/env python - days = int(raw_input("Enter days: ")) + #!/usr/bin/env python3 + days = int(nput("Enter days: ")) months = days / 30 days = days % 30 - print "Months = %d Days = %d" % (months, days) + print("Months = %d Days = %d" % (months, days)) The output @@ -52,9 +52,9 @@ In the first line I am taking the input of days, then getting the months and day :: - #!/usr/bin/env python - days = int(raw_input("Enter days: ")) - print "Months = %d Days = %d" % (divmod(days, 30)) + #!/usr/bin/env python3 + days = int(input("Enter days: ")) + print("Months = %d Days = %d" % (divmod(days, 30))) The divmod(num1, num2) function returns two values , first is the division of num1 and num2 and in second the modulo of num1 and num2. @@ -142,11 +142,11 @@ shorthand.py example .. code-block:: python - #!/usr/bin/env python + #!/usr/bin/env python3 N = 100 a = 2 while a < N: - print "%d" % a + print("%d" % a) a *= a The output @@ -255,14 +255,14 @@ This is a program to evaluate the quadratic equation :: - #!/usr/bin/env python3 + #!/usr/bin/env python import math a = int(input("Enter value of a: ")) b = int(input("Enter value of b: ")) c = int(input("Enter value of c: ")) d = b * b - 4 * a * c if d < 0: - print("ROOTS are imaginary") + print "ROOTS are imaginary" else: root1 = (-b + math.sqrt(d)) / (2.0 * a) root2 = (-b - math.sqrt(d)) / (2.0 * a) @@ -276,7 +276,7 @@ In this example we are going to calculate the salary of a camera salesman. His b :: - #!/usr/bin/env python3 + #!/usr/bin/env python basic_salary = 1500 bonus_rate = 200 commision_rate = 0.02 @@ -286,7 +286,7 @@ In this example we are going to calculate the salary of a camera salesman. His b commision = (commision_rate * numberofcamera * price) print("Bonus = %6.2f" % bonus) print("Commision = %6.2f" % commision) - print("Gross salary = %6.2f" % (basic_salary + bonus + commision)) + print("Gross salary = %6.2f") % (basic_salary + bonus + commision) The output diff --git a/docs/projectstructure.rst b/docs/projectstructure.rst index 048886a..b43cfcf 100644 --- a/docs/projectstructure.rst +++ b/docs/projectstructure.rst @@ -173,8 +173,8 @@ Creating account First register yourself in `this link `_. You will receive an email with a link, go to that link and confirm your registration. -.pypirc file -------------- + .pypirc file + ------------- Your account details genrally stay inside a file called *.pypirc* under your home directory. The content of the file will look like diff --git a/docs/strings.rst b/docs/strings.rst index a9cd1d5..e50d8b1 100644 --- a/docs/strings.rst +++ b/docs/strings.rst @@ -173,9 +173,9 @@ Palindrome are the kind of strings which are same from left or right whichever w s = raw_input("Please enter a string: ") z = s[::-1] if s == z: - print "The string is a palindrome" + print("The string is a palindrome") else: - print "The string is not a palindrome" + print("The string is not a palindrome") The output @@ -196,8 +196,8 @@ In this example we will count the number of words in a given line :: #!/usr/bin/env python - s = raw_input("Enter a line: ") - print "The number of words in the line are %d" % (len(s.split(" "))) + s = input("Enter a line: ") + print("The number of words in the line are %d" % (len(s.split(" ")))) The output :: diff --git a/docs/variablesanddatatypes.rst b/docs/variablesanddatatypes.rst index b906239..e7b72ea 100644 --- a/docs/variablesanddatatypes.rst +++ b/docs/variablesanddatatypes.rst @@ -9,27 +9,17 @@ Every programming language is having own grammar rules just like the other langu Keywords and Identifiers ======================== -Python codes can be divided into identifiers. Identifiers (also referred to as names) are described by the following lexical definitions: +The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here: :: - identifier ::= (letter|"_") (letter | digit | "_")* - letter ::= lowercase | uppercase - lowercase ::= "a"..."z" - uppercase ::= "A"..."Z" - digit ::= "0"..."9" - -This means *_abcd* is a valid identifier where as *1sd* is not. The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here: - -:: - - and del from not while - as elif global or with - assert else if pass yield - break except import print - class exec in raise - continue finally is return - def for lambda try + False class finally is return + None continue for lambda try + True def from nonlocal while + and del global not with + as elif if or yield + assert else import pass + break except in raise In Python we don't specify what kind of data we are going to put in a variable. So you can directly write abc = 1 and abc will become an integer datatype. If you write abc = 1.0 abc will become of floating type. Here is a small program to add two given numbers @@ -54,16 +44,16 @@ From the above example you can understand that to declare a variable in Python , Reading input from the Keyboard =============================== -Generally the real life Python codes do not need to read input from the keyboard. In Python we use raw_input function to do input. *raw_input("String to show")* , this will return a string as output. Let us write a program to read a number from the keyboard and check if it is less than 100 or not. Name of the program is testhundred.py +Generally the real life Python codes do not need to read input from the keyboard. In Python we use input function to do input. *input("String to show")* , this will return a string as output. Let us write a program to read a number from the keyboard and check if it is less than 100 or not. Name of the program is testhundred.py .. code-block:: python - #!/usr/bin/env python - number = int(raw_input("Enter an integer: ")) + #!/usr/bin/env python3 + number = int(input("Enter an integer: ")) if number < 100: - print "Your number is smaller than 100" + print("Your number is smaller than 100") else: - print "Your number is greater than 100" + print("Your number is greater than 100") The output @@ -81,14 +71,14 @@ In the next program we are going to calculate investments. :: #!/usr/bin/env python - amount = float(raw_input("Enter amount: ")) - inrate = float(raw_input("Enter Interest rate: ")) - period = int(raw_input("Enter period: ")) + amount = float(input("Enter amount: ")) + inrate = float(input("Enter Interest rate: ")) + period = int(input("Enter period: ")) value = 0 year = 1 while year <= period: value = amount + (inrate * amount) - print "Year %d Rs. %.2f" % (year, value) + print("Year %d Rs. %.2f" % (year, value)) amount = value year = year + 1 @@ -123,12 +113,12 @@ In the next program we will do an average of N numbers. sum = 0 count = 0 while count < N: - number = float(raw_input("")) + number = float(input("")) sum = sum + number count = count + 1 average = float(sum)/N - print "N = %d , Sum = %f" % (N, sum) - print "Average = %f" % average + print("N = %d , Sum = %f" % (N, sum)) + print("Average = %f") % average The output @@ -156,12 +146,12 @@ In this program we will convert the given temperature to Celsius from Fahrenheit :: - #!/usr/bin/env python + #!/usr/bin/env python3 fahrenheit = 0.0 - print "Fahrenheit Celsius" + print("Fahrenheit Celsius") while fahrenheit <= 250: celsius = ( fahrenheit - 32.0 ) / 1.8 # Here we calculate the Celsius value - print "%5.1f %7.2f" % (fahrenheit , celsius) + print("%5.1f %7.2f" % (fahrenheit , celsius)) fahrenheit = fahrenheit + 25 The output