Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

License

NotificationsYou must be signed in to change notification settings

Web-Dev-Collaborative/PYTHON_PRAC

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

54 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Python is a very popular coding language. Little people use it for serious projects, but it is still useful to learn. It was created in 1991 byGuido van Rossum.
Look at a few uses of python:

.├── DOCS│   ├── _static│   └── tutorial├── Readings├── exploring-python├── learn-python3-samples│   ├── advance│   ├── async│   ├── basic│   ├── commonlib│   ├── context│   ├── db│   ├── debug│   ├── function│   ├── functional│   ├── gui│   │   └── turtle│   ├── io│   ├── mail│   ├── micropython│   │   ├── hellorobot│   │   ├── rccar│   │   ├── smallcar│   │   └── tank│   ├── module│   ├── multitask│   ├── oop_advance│   ├── oop_basic│   ├── regex│   ├── socket│   ├── test│   └── web│       └── mvc│           └── templates├── prac-4-beginners│   ├── code│   │   ├── 05-interactive-code│   │   │   └── m-n-m│   │   ├── 06-organizing-code-with-functions│   │   │   └── rocks-game│   │   ├── 07-data-structures│   │   │   ├── rocks-game│   │   │   └── simple_dict│   │   ├── 08-problem-solving│   │   │   └── tictactoe│   │   ├── 09-working-with-files│   │   │   └── rocks-game│   │   ├── 10-external-libraries│   │   │   └── rocks-game│   │   └── 11-error-handling│   │       └── rocks-game│   ├── practices│   │   ├── ch04_first_lines│   │   ├── ch05_interactive_code│   │   ├── ch06-organizing-code-with-functions│   │   ├── ch07_data_structures│   │   ├── ch08_problem_solving│   │   │   └── readme_files│   │   ├── ch09_working_with_files│   │   ├── ch10_external_libraries│   │   └── ch11-error-handling│   ├── readme_resources│   └── solutions│       ├── ch-04-writing-your-first-lines-of-code│       ├── ch-05-interactive-code│       ├── ch-06-organizing-code-with-functions│       ├── ch-07-data-structures│       ├── ch-08-problem-solving│       ├── ch-09-working-with-files│       ├── ch-10-external-libraries│       └── ch-11-error-handling├── projecteuler-solutions├── projects-DS│   ├── Data-Structures-Notes-master│   │   ├── BST_and_Heaps│   │   ├── Doubly_Linked_List│   │   ├── Interview_Problems│   │   └── Linked_Lists│   ├── Data-Structures-and-Algorithms-master│   │   ├── assets│   │   └── src│   │       ├── algorithms│   │       │   ├── strings│   │       │   │   └── knuth-morris-pratt│   │       │   └── tree│   │       │       ├── breadth-first-search│   │       │       └── depth-first-search│   │       ├── analysis-of-algorithms│   │       │   └── asymptotic-notation│   │       └── data-structures│   │           ├── graph│   │           ├── linked lists│   │           └── tree│   │               ├── binary-search-tree│   │               └── binary-tree│   ├── Data-Structures-master│   │   ├── avl_tree│   │   ├── binary_search_tree│   │   ├── doubly_linked_list│   │   ├── heap│   │   ├── javascript│   │   │   └── tests│   │   ├── lru_cache│   │   ├── python│   │   │   ├── binary_search_tree│   │   │   ├── doubly_linked_list│   │   │   ├── heap│   │   │   ├── linked_list│   │   │   └── queue│   │   └── queue│   └── data_struct_and_algo-master└── python-mega-algo    ├── arithmetic_analysis    │   └── image_data    ├── backtracking    ├── bit_manipulation    ├── blockchain    ├── boolean_algebra    ├── cellular_automata    ├── ciphers    ├── compression    │   └── image_data    ├── computer_vision    ├── conversions    ├── data_structures    │   ├── binary_tree    │   ├── disjoint_set    │   ├── hashing    │   │   └── number_theory    │   ├── heap    │   ├── linked_list    │   ├── queue    │   ├── stacks    │   └── trie    ├── digital_image_processing    │   ├── dithering    │   ├── edge_detection    │   ├── filters    │   ├── histogram_equalization    │   │   ├── image_data    │   │   └── output_data    │   ├── image_data    │   ├── resize    │   └── rotation    ├── divide_and_conquer    ├── dynamic_programming    ├── electronics    ├── file_transfer    │   └── tests    ├── fractals    ├── fuzzy_logic    ├── genetic_algorithm    ├── geodesy    ├── graphics    ├── graphs    │   └── tests    ├── hashes    ├── knapsack    │   └── tests    ├── linear_algebra    │   └── src    ├── machine_learning    │   ├── forecasting    │   └── lstm    ├── maths    │   ├── images    │   └── series    ├── matrix    │   └── tests    ├── networking_flow    ├── neural_network    ├── other    ├── physics    ├── project_euler    │   ├── problem_001    │   ├── problem_002    │   ├── problem_003    │   ├── problem_004    │   ├── problem_005    │   ├── problem_006    │   ├── problem_007    │   ├── problem_008    │   ├── problem_009    │   ├── problem_010    │   ├── problem_011    │   ├── problem_012    │   ├── problem_013    │   ├── problem_014    │   ├── problem_015    │   ├── problem_016    │   ├── problem_017    │   ├── problem_018    │   ├── problem_019    │   ├── problem_020    │   ├── problem_021    │   ├── problem_022    │   ├── problem_023    │   ├── problem_024    │   ├── problem_025    │   ├── problem_026    │   ├── problem_027    │   ├── problem_028    │   ├── problem_029    │   ├── problem_030    │   ├── problem_031    │   ├── problem_032    │   ├── problem_033    │   ├── problem_034    │   ├── problem_035    │   ├── problem_036    │   ├── problem_037    │   ├── problem_038    │   ├── problem_039    │   ├── problem_040    │   ├── problem_041    │   ├── problem_042    │   ├── problem_043    │   ├── problem_044    │   ├── problem_045    │   ├── problem_046    │   ├── problem_047    │   ├── problem_048    │   ├── problem_049    │   ├── problem_050    │   ├── problem_051    │   ├── problem_052    │   ├── problem_053    │   ├── problem_054    │   ├── problem_055    │   ├── problem_056    │   ├── problem_057    │   ├── problem_058    │   ├── problem_059    │   ├── problem_062    │   ├── problem_063    │   ├── problem_064    │   ├── problem_065    │   ├── problem_067    │   ├── problem_069    │   ├── problem_070    │   ├── problem_071    │   ├── problem_072    │   ├── problem_074    │   ├── problem_075    │   ├── problem_076    │   ├── problem_077    │   ├── problem_080    │   ├── problem_081    │   ├── problem_085    │   ├── problem_086    │   ├── problem_087    │   ├── problem_089    │   ├── problem_091    │   ├── problem_097    │   ├── problem_099    │   ├── problem_101    │   ├── problem_102    │   ├── problem_107    │   ├── problem_109    │   ├── problem_112    │   ├── problem_113    │   ├── problem_119    │   ├── problem_120    │   ├── problem_121    │   ├── problem_123    │   ├── problem_125    │   ├── problem_129    │   ├── problem_135    │   ├── problem_173    │   ├── problem_174    │   ├── problem_180    │   ├── problem_188    │   ├── problem_191    │   ├── problem_203    │   ├── problem_206    │   ├── problem_207    │   ├── problem_234    │   ├── problem_301    │   └── problem_551    ├── quantum    ├── scheduling    ├── scripts    ├── searches    ├── sorts    ├── strings    └── web_programming286 directories

Python syntax was made for readability, and easy editing. For example, the python language uses a: and indented code, while javascript and others generally use{} and indented code.

Lets create apython 3 repl, and call itHello World. Now you have a blank file calledmain.py. Now let us write our first line of code:

helloworld.py

print('Hello world!')

Brian Kernighan actually wrote the first “Hello, World!” program as part of the documentation for the BCPL programming language developed by Martin Richards.

Now, press the run button, whichobviously runs the code. If you are not using replit, this will not work. You should research how to run a file with your text editor.

If you look to your left at the console where hello world was just printed, you can see a>,>>>, or$ depending on what you are using. After the prompt, try typing a line of code.

Python 3.6.1 (default, Jun 21 2017, 18:48:35)[GCC 4.9.2] on linuxType "help", "copyright", "credits" or "license" for more information.> print('Testing command line')Testing command line> print('Are you sure this works?')Are you sure this works?>

The command line allows you to execute single lines of code at a time. It is often used when trying out a new function or method in the language.

Another cool thing that you can generally do with all languages, are comments. In python, a comment starts with a#. The computer ignores all text starting after the#.

shortcom.py

# Write some comments!

If you have a huge comment, donot comment all the 350 lines, just put''' before it, and''' at the end. Technically, this is not a comment but a string, but the computer still ignores it, so we will use it.

longcom.py

'''Dear PYer,I am confused about how you said you could use triple quotes to makeSUPERLONGCOMMENTS!I am wondering if this is true,and if so,I am wondering if this is correct.Could you help me with this?Thanks,Random guy who used your tutorial.'''print('Testing')

Unlike many other languages, there is novar,let, orconst to declare a variable in python. You simply goname = 'value'.

vars1.py

x = 5y = 7z = x*y # 35print(z) # => 35

Remember, there is a difference between integers and strings.Remember: String ="". To convert between these two, you can put an int in astr() function, and a string in aint() function. There is also a less used one, called a float. Mainly, these are integers with decimals. Change them using thefloat() command.

vars2.py

x = 5x = str(x)b = '5'b = int(b)print('x = ', x, '; b = ', str(b), ';') # => x = 5; b = 5;

Instead of using the, in the print function, you can put a+ to combine the variables and string.

There are many operators in python:

  • +
  • -
  • /
  • *
    These operators are the same in most languages, and allow for addition, subtraction, division, and multiplicaiton.
    Now, we can look at a few more complicated ones:
  • %
  • //
  • **
  • +=
  • -=
  • /=
  • *=
    Research these if you want to find out more…

simpleops.py

x = 4a = x + 1a = x - 1a = x * 2a = x / 2

You should already know everything shown above, as it is similar to other languages. If you continue down, you will see more complicated ones.

complexop.py

a += 1a -= 1a *= 2a /= 2

The ones above are to edit the current value of the variable.
Sorry to JS users, as there is noi++; or anything.

Fun Fact:
The python language was named after Monty Python.

If you really want to know about the others, viewPy Operators

Like the title?
Anyways, a' and a" both indicate a string, butdo not combine them!

quotes.py

x = 'hello' # Goodx = "hello" # Goodx = "hello' # ERRORRR!!!

slicing.py

String Slicing

You can look at only certain parts of the string by slicing it, using[num:num].
The first number stands for how far in you go from the front, and the second stands for how far in you go from the back.

x = 'Hello everybody!'x[1] # 'e'x[-1] # '!'x[5] # ' 'x[1:] # 'ello everybody!'x[:-1] # 'Hello everybod'x[2:-3] # 'llo everyb'

Methods and Functions

Here is a list of functions/methods we will go over:

  • .strip()
  • len()
  • .lower()
  • .upper()
  • .replace()
  • .split()

I will make you try these out yourself. See if you can figure out how they work.

strings.py

x = " Testing, testing, testing, testing       "print(x.strip())print(len(x))print(x.lower())print(x.upper())print(x.replace('test', 'runn'))print(x.split(','))

Good luck, see you when you come back!

Input is a function that gathers input entered from the user in the command line. It takes one optional parameter, which is the users prompt.

inp.py

print('Type something: ')x = input()print('Here is what you said: ', x)

If you wanted to make it smaller, and look neater to the user, you could do…

inp2.py

print('Here is what you said: ', input('Type something: '))

Running:
inp.py

Type something:Hello WorldHere is what you said: Hello World

inp2.py

Type something: Hello WorldHere is what you said: Hello World

Python has created a lot of functions that are located in other .py files. You need to import thesemodules to gain access to the,, You may wonder why python did this. The purpose of separate modules is to make python faster. Instead of storing millions and millions of functions, , it only needs a few basic ones. To import a module, you must writeinput <modulename>. Do not add the .py extension to the file name. In this example , we will be using a python created module named random.

module.py

import random

Now, I have access to all functions in the random.py file. To access a specific function in the module, you would do<module>.<function>. For example:

module2.py

import randomprint(random.randint(3,5)) # Prints a random number between 3 and 5

Pro Tip:
Dofrom random import randint to not have to dorandom.randint(), justrandint()
To import all functions from a module, you could dofrom random import *

Loops allow you to repeat code over and over again. This is useful if you want to print Hi with a delay of one second 100 times.

for Loop

The for loop goes through a list of variables, making a seperate variable equal one of the list every time.
Let’s say we wanted to create the example above.

loop.py

from time import sleepfor i in range(100):     print('Hello')     sleep(.3)

This will print Hello with a .3 second delay 100 times. This is just one way to use it, but it is usually used like this:

loop2.py

import timefor number in range(100):     print(number)     time.sleep(.1)

while Loop

The while loop runs the code while something stays true. You would putwhile <expression>. Every time the loop runs, it evaluates if the expression is True. It it is, it runs the code, if not it continues outside of the loop. For example:

while.py

while True: # Runs forever     print('Hello World!')

Or you could do:

while2.py

import randomposition = '<placeholder>'while position != 1: # will run at least once    position = random.randint(1, 10)    print(position)

The if statement allows you to check if something is True. If so, it runs the code, if not, it continues on. It is kind of like a while loop, but it executesonly once. An if statement is written:

if.py

import randomnum = random.randint(1, 10)if num == 3:     print('num is 3. Hooray!!!')if num > 5:     print('Num is greater than 5')if num == 12:     print('Num is 12, which means that there is a problem with the python language, see if you can figure it out. Extra credit if you can figure it out!')

Now, you may think that it would be better if you could make it print only one message. Not as many that are True. You can do that with anelif statement:

elif.py

import randomnum = random.randint(1, 10)if num == 3:    print('Num is three, this is the only msg you will see.')elif num > 2:    print('Num is not three, but is greater than 1')

Now, you may wonder how to run code if none work. Well, there is a simple statement calledelse:

else.py

import randomnum = random.randint(1, 10)if num == 3:    print('Num is three, this is the only msg you will see.')elif num > 2:    print('Num is not three, but is greater than 1')else:    print('No category')

So far, you have only seen how to use functions other people have made. Let use the example that you want to print the a random number between 1 and 9, and print different text every time.
It is quite tiring to type:

Characters: 389

nofunc.py

import randomprint(random.randint(1, 9))print('Wow that was interesting.')print(random.randint(1, 9))print('Look at the number above ^')print(random.randint(1, 9))print('All of these have been interesting numbers.')print(random.randint(1, 9))print("these random.randint's are getting annoying to type")print(random.randint(1, 9))print('Hi')print(random.randint(1, 9))print('j')

Now with functions, you can seriously lower the amount of characters:

Characters: 254

functions.py

import randomdef r(t):     print(random.randint(1, 9))     print(t)r('Wow that was interesting.')r('Look at the number above ^')r('All of these have been interesting numbers.')r("these random.randint's are getting annoying to type")r('Hi')r('j')

Chapter 01 - Getting Ready with Python

Installing Python 3, And Launching Python Shell

This video should help you get up and running with Python 3

Installing Python is really a cakewalk. Search for “Python download” onwww.google.com. Download the installable and install it.

A quick word of caution on Windows

  • Make sure that you have the check-box “Add Python 3.6 to PATH”, checked.

Once you have installed Python, you can launch the Python Shell.

  • Windows - Launch cmd prompt by typing in ‘cmd’ command.
  • Mac or Linux - Launch up terminal.

Command to launch Python 3 is different in Mac.

  • In Mac, type inpython3
  • In other operating systems, including windows, typepython

You can type code in python shell and code as well!

You can useprint(5*4), and it shows20.

You can execute the code, and the shell would immediately give you output.

Using the the Python Shell is an awesome way to learn Python.

Chapter 02 - Introduction To Python Programming

Most programmers find programming a lot of fun, and besides, it also gets their work done.

Programming mainly involvesproblem solving, where one makes use of a computer to solve a real world problem.

During our journey here, we will approach programming in a very different way. We will not only introduce you to the Python language, but also help you pick up essential problem solving skills.

As a programmer, you need to be able to look at a problem, and identify the important programming concepts relevant to solving it. Finally, you need to be able to use the language features and syntax, to express your solution on the computer. While all this looks complex, we want to make it easy for you. Together, we will tackle a variety of programming challenges, using these same steps. We will start with simple challenges (such as a Multiplication Table), and gradually increase the difficulty level over the duration of this book.

Learning to program is a lot like learning to ride a bicycle. The first few steps are the most challenging ones.

Once you get over these initial steps, your experience will become more and more enjoyable.

Are you ready for your first programming challenge? Let’s get going now! We wish you all the best.

Summary

In this step, we:

  • Were introduced to the concept of problem solving
  • Understood how good programmers approach problem solving

Step 01: Our First Programming Challenge

Our firstprogramming challenge aims to do, what every kid does in math class: read out a multiplication table. We now want to give this task to the computer. Here is the statement of our problem:

ThePrint Multiplication Table Challenge (PMT-Challenge)

  1. Compute the multiplication table for5, with entries from1 to10.
  2. Display this table.

The display needs to be:

5 * 1 = 5

5 * 2 = 10

5 * 3 = 15

5 * 4 = 20

5 * 5 = 25

5 * 6 = 30

5 * 7 = 35

5 * 8 = 40

5 * 9 = 45

5 * 10 = 50

This is the challenge. For convenience, let’s give it a label, sayPMT-Challenge. What would be the important concepts we need to learn, to solve this challenge? The following list of concepts would be a good starting point:

  • Statements
  • Expressions
  • Variables
  • Literals
  • Conditionals
  • Loops
  • Methods

In the rest of this chapter, we will introduce these concepts to you, one-by-one. We will also show you how learning each concept, takes us closer to a solution toPMT-Challenge.

Summary

In this step, we:

  • Stated our first programming challenge
  • Identified what programming concepts we need to learn, to solve this challenge

Step 02: Breaking DownPMT-Challenge

Typically when we do programming, we have problems. Solving the problem typically need a step-by -step approach. Common sense tells us that to solve a complex problem, we break it into smaller parts, and solve each part one by one. Here is how any good programmer worth her salt, would solve a problem:

  • Simplify the problem, by breaking it into sub-problems
  • Solve the sub-problems in stages (in some order), using the language
  • Combine these solutions to get a final solution

ThePMT-Challenge is no different! Now how do we break it down, and where do we really start? Once again, your common sense will reveal a solution. As a first step, we could get the computer to calculate say,5 * 3. The second thing we can do, is to try and print the calculated value, in a manner similar to5 * 3 = 15. Then, we could repeat what we just did, to print out all the entries of the5 multiplication table. Let’s put it down a little more formally:

Here is how our draft steps look like

  • Calculate5 * 3 and print result as15
  • Print5 * 3 = 15 (15 is result of previous calculation)
  • Do this ten times, once for each table entry (going from1 to10)

Let’s start with that kind of a game plan, and see where it takes us.

Summary

In this step, we:

  • Learned that breaking down a problem into sub-problems is a great help
  • Found a way to break down thePMT-Challenge problem

Step 03: Introducing Operators And Expressions

Let’s focus on solving the first sub-problem ofPMT-Challenge, the numeric computation. We want the computer to calculate5 * 5 for example, and print25 for us. How do we get it to do that? That’s what we would be looking at in this step.

Snippet-01: Introducing Operators

Launch up Python shell. We want to calculate5 * 5. How do we do that?

Using our knowledge of school math, let’s try5 X 5.

    >>> 5 X 5    File "< stdin >", line 1    5 X 5      ^    SyntaxError: invalid syntax

The Python Shell hits back at us, saying “invalid syntax”. This is how Python complains, when it doesn’t fully understand the code you type in. Here, it says our code has a “SyntaxError”.

The reason why it complains, is because ‘X’ is not a validoperator in Python.

The way you can do multiplication is by using the ‘*operator .

5 into 5” is achieved by the code5 * 5, and you can see the result25 being printed. Similarly,5 * 6 gives us30.

    >>> 5 * 6    30

There are a wide range of other operators in Python:

  • 5 + 6 gives a result of11.

  • 5 - 6 leads to-1.

    >>> 5 + 611>>> 5 - 6-1

10 / 2, gives an output of5.0 . There is one interesting operator,**. Let’s try10 ** 3. We ran this code, and the result we get is1000. Yes you guessed right, the operator performs “to the power of”. “10 to the power of3” is10 * 10 * 10, or1000.

    >>> 10 / 2    5.0    >>> 10 ** 3    1000

Another interesting operator is%, called “modulo”, which computes the remainder on integer division. If we do10 % 3, what is the remainder when10 is divided by3?3 * 3 is9, and10 - 9 is1, which is what% returns in this case.

Let’s look at some terminology:

  • Whatever pieces of code we gave Python shell to run, are calledexpressions. So,5 * 5,5 * 6 and5 - 6 are allexpressions. An expression is composed ofoperators andoperands.
  • In the expression5 * 6, the two values5 and6 are called operands, and the* operatoroperates on them.
  • The values5 and6 areliterals, because those are constants which cannot be changed.

The cool thing about Python, is that you can even have expressions with multiple operators. Therefore, you can form an expression with5 + 5 + 5, which evaluates to15. This is an expression which has three operands, and two+ operators. You can even have expressions with different types of operators, such as in5 + 5 * 5.

    >>> 5 + 5 + 5    15    >>> 5 + 5 * 5    30

Try and play around with the expressions, and understand the output which results.

Summary

In this step, we:

  • Learned how to give code input to the Python Shell
  • Understood that Python has a predefined set of operators
  • Used a few types of basic operators and their operands, to form expressions

Step 04: Programming Exercise IN-PE-01

At this stage, your smile tells us that you enjoy evaluating Python expressions. What if we tickle your mind a bit, to make sure it hasn’t fallen asleep? Here is your first programming exercise.

Exercises

  1. Write an expression to calculate the number of minutes in a day.
  2. Write an expression to calculate the number of seconds in a day.
Note

You need to solve these problems by yourself. If you are able to work them out, that’s fantastic! But if not, that’s part of the learning process.

Solutions

Solution 1

    >>> 24 * 60    1440

We wanted to calculate the number of minutes in a day. How do we do that? Think about this…

  • How many number of hours are there in a day?24.
  • And how many minutes does each hour have? It’s60.
  • So if you want to find out the number of minutes in a day, it’s24 * 60, which is1440.

Solution 2

    >>> 24 * 60 * 60    86400

How many seconds are there in a day?

  • Let’s start with the number of hours,24.
  • The number of minutes in an hour is60, and
  • The number of seconds in a minute is60 as well.
  • So it’s24 * 60 * 60, or86400.

Summary

In this step, we:

  • Solved a Programming Exercise involving common scenarios, using Python code involving:
    • Expressions
    • Operators
    • Literals

Step 05: Puzzles On Expressions

Let’s look at a few puzzles related to expressions, in this step. Before that, let’s revise some of the terminology we had learned earlier.

5 + 6 + 10 is an example of an expression. In this expression,5,6 and10 are operands. The+ here is the operator. You can have multiple operators in an expression. We also did mention that the operands, namely10,6 and5, are literals. Their values will not change.

Here are a few puzzles coming up, to explore aspects of expressions.

Snippet-01: Puzzles On Expressions

Think about what would happen when you do something of this kind:5 $ 2. You’re right, it would throw aSyntaxError. When Python does not understand the code you type in, it reports an error. Here, the expression we’re typing is5 $ 2, which does not make sense to Python, hence theSyntaxError.

    >>> 5 $ 2    File "< stdin >", line 1    5 $ 2    ^    SyntaxError: invalid syntax    >>> 5$2    File "< stdin >", line 1    5 $ 2    ^    SyntaxError: invalid syntax

Let’s say we type in5+6+10, without any spaces between the operands, and the operators. What do you think will happen? Surprisingly, the Python Shell does calculate the value!

    >>> 5+6+10    21

In an expression, using spaces makes it easier for you to read it, but it’s not mandatory.5 + 6 + 10 is easier to read than5+6+10, but does not make any difference to the Python compiler.

The next puzzle tries to evaluate5 / 2, which is “5 divided by2”. What would be the output?2.5.

    >>> 5/2    2.5

If you’re coming from other programming languages like Java or C, this might be a surprising result. If you try this in Java for instance, you would get2 as the output. Note that even though both operands are integers, the result of the/ operation is a floating point value,2.5 . Python does what is expected by a programmer!

The puzzle after that tries to play with5 + 5 * 6. What would be the result of this expression? Will it be5 + 5 or10, then10 * 6, which is60? Or, will it be5 plus5 * 6, which is5 +30, that’s35?

    >>> 5 + 5 * 6    35

The correct result is35.

Python decides this is based on theprecedence of operators.

Operators in Python are divided into two sets as follows:

  • **,*,/ and% have higher precedence, or priority.
  • + and- have a lower precedence.

Sub-expressions involving operators from {*,/,%,**} are evaluated before those involving operators from {+,-}

Let’s try another small puzzle on precedence, with5 - 2 * 2. What would be the result of this? Will it be6, or1? It’s1, because* has a higher precedence than-. Thus2 * 2 is4, and5 - 4 gives us1.

    >>> 5 - 2 * 2    1

Let’s say we want to execute5 - 2, to give an output of2. How do we change the operator precedence?

You cannot really change the precedence, but you can add parentheses to group sub-expressions differently.

    >>> (5 - 2) * 2    6    >>> 5 - ( 2 * 2 )    1

Parentheses have the highest precedence in Python, and can be used to override operator precedence.(5 - 2) gets calculated first, and the final result of the expression is6.

A positive thing about using parentheses is, that it makes expressions more readable. So even in situations such as5 - 2 * 2, where we know the result according to precedence, adding parentheses is good.

Summary

In this step, we went about solving a few puzzles about expressions, touching concepts such as:

  • SyntaxError for incorrect operators
  • White-space in expressions
  • Floating Point division by default
  • Operator Precedence
  • Using parentheses

Step 06: Printing Text

In the previous step, we learned how to use expressions to compute values. In this step, let’s see how we can actually print multiplication table entries, that are readable by the user.

Snippet-01: Printing Text

How do we go about printing a complete multiplication table entry? We want to print text such as5 * 6 = 30 . But trying to do so, as we know it, gives us aSyntaxError. Clearly, there is a different way to print text, as compared to an expression.

    >>> 5 * 6 = 30      File "<stdin>", line 1    SyntaxError: can't assign to operator

Let’s first try to print a simple piece of text,Hello. Typing in this piece of code directly on Python Shell also gives us an error.

    >>> Hello    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    NameError: name 'Hello' is not defined

Only expressions work that way, andHello is not really an expression.

"Hello" is typically called astring, and represents the text of letters'H','e','l','l','o'."Hello" is hence different from the number5.

There are a number of in-built functions in Python to help print strings. One of these is theprint() function. Can you just sayprint Hello?

    >>> print Hello      File "<stdin>", line 1        print Hello                  ^    SyntaxError: Missing parentheses in call to 'print'. Did you mean print(Hello)?

The Python compiler gives you an error, that says “missing parentheses”.

Willprint(Hello) work?

    >>> print (Hello)    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    NameError: name 'Hello' is not defined

Nope! Again, this one failed because you need to indicate that"Hello" is a string.

How do I indicate that"Hello" is a string? By putting it within double quotes.

Let’s tryprint ("Hello")

    >>> print ("Hello")    Hello    >>> print("Hello")    Hello

print("Hello") finally results in"Hello" being printed out. To be able to print"Hello", the things we need to do are:

  • Typing the method name print ,
  • open parentheses ( ,
  • Followed by a double quote " ,
  • The text Hello,
  • and another double quote " ,
  • finished off with a closed parentheses ).

What we have written here is called astatement, a simple piece of code to execute. As part of this statement, we arecalling afunction, namedprint().

What exactly are we trying to print?

The text"Hello", which is called aparameter orargument, toprint().

Now let’s get back to what we wanted to do, which is to print5 * 6 = 30. The most basic version would be something of this kind,print("5 * 6 = 30"). Here, we are passing the entire value in the form of a string.

    >>> print("5 * 6 = 30")    5 * 6 = 30

This prints the text on the console, as-is. The thing you need to understand here is, we aren’t really calculating30 using the formula5 * 6, but directly putting text30 in here. That’s calledhard-coding.

In a later step, we will look at how to actually calculate the value and pass it in.

Summary

In this step, we:

  • Understood that displaying text on the console is not the same as printing an expression value
  • Learned about theprint() function, that is used to print text in Python.
  • Found a way to print the text"5 * 6 = 30" on the console, by hard-coding values in a string

Step 07: Puzzles On Utility Methods, And Strings

In the previous step, we learned how to print5 * 6 = 30. It was not a perfect solution, because we hard-coded everything. we used an in-built function namedprint(), passed a string to it, and invoked the method.

In this step, let’s look at a number of puzzles related to in-built methods, their parameters, and strings in general.

For example, let’s doprint("5 * 6"), as in the previous step. What does this code result in?

    >>> print("5*6")    5*6    >>> print('5*6')    5*6

It just prints the string"5 * 6".

Let’s say we try the codeprint(5 * 6),

    >>> print(5*6)    30

Without the double quotes,5 * 6 is an expression. What will be the output?30.

If you callprint() with an expression argument, it prints the value of the expression. However, when we pass something within double quotes, it becomes a piece of text, printed as-is.

An interesting thing to note is, that in Python you can use either double-quotes (" and"), or single-quotes (' and') with text values.

Let’s look at a few other in-built methods within Python.

Considerabs() (which stands for absolute value), a method that accepts a numeric value. You can useabs(10.5), passing10.5 as a value to it, and it prints the absolute value of10.

    >>> abs 10.5      File "<stdin>", line 1        abs 10.5               ^    SyntaxError: invalid syntax    >>> abs(10.5)    10.5

If you pass in a string value, will it work? It complains, “abs() function will not work with a string, it only works with numeric values”.

    >>> abs("10.5")    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: bad operand type for abs(): 'str'

Let’s say you want to use a function that computes “to the power of”, for instance “2 to the power of5”. In Python, there’s an in-built function namedpow(), which does just what we need. Topow(), you can pass two parameters and calculate the result. How do you do that?

Will this work:pow 2 5? No, not at all. This code does not work as well:pow(2 5).pow(2, 5) is the correct syntax.

    >>> pow 2 5      File "<stdin>", line 1        pow 2 5            ^    SyntaxError: invalid syntax    >>> pow(2 5)      File "<stdin>", line 1        pow(2 5)              ^    SyntaxError: invalid syntax    >>> pow(2, 5)    32

You’ll see that32 is printed.

Let’s see another example, “10 to the power of3”.pow(10,3) is the alternative to saying10 ** 3. This gives us1000, similar to howpow() would.

    >>> pow(10, 3)    1000    >>> 10 ** 3    1000

max() returns maximum in a set of numbers.min() function returns the minimum value.

    >>> max(34, 45, 67)    67    >>> min(34, 45, 67)    34

These are some of the in-built functions in Python, and we saw how to call the in-built functions by passing in a varied number of parameters.

Python is case sensitive. So let’s say I want of calculatepow(2,5). So this would give me32. Now, what if I say capital'P' instead of small'p' here?Pow(2,5) would lead to an error.

    >>> pow(2,5)    32    >>> Pow(2,5)    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    NameError: name 'Pow' is not defined

The only things not case-sensitive in Python, are string values. Earlier we saw that the codeprint("Hello") displays the text"Hello". Inside a string, the text can be in any case. Hence,print("hello") displays"hello" ,with a small'h'.

    >>> print("Hello")    Hello    >>> print("hello")    hello    >>> print("hellO")    hellO    >>> print ( "hellO" )    hellO

However inside your code, you need to be very particular about the case of function names, class names, variable names, and the like.

In your code, whitespace does not really matter. You can add space here and here, and you would still get the same output. However, in case of strings, whitespace does matter.

If we sayprint("hellO World"), it would print"hellO World", with a space in between. And if you doprint("hellO World") with three spaces, it would print the same. In expressions, white-space does not affect the output.

    >>> print ( "hellO World" )    hellO World    >>> print ( "hellO     World" )    hellO     World

The last thing we want to look at, is anescape sequence. Let’s say you want to print a double quote,", in the code. If we were to do this:print("Hello""), what would happen? The compiler says error!

    >>> print("Hello"")      File "<stdin>", line 1        print("Hello"")                      ^    SyntaxError: EOL while scanning string literal

If you want to print a" inside a string, use an escape sequence. In Python, the symbol'\' is used as anescape character. On using'\' adjacent to the", it printsHello" (notice the trailing"). We have used the'\' toescape the", by forming anescape sequence\".

>>> print("Hello\"")Hello">>>

The other reason why you would want to use a'\' is to print a<NEWLINE>. If you want to print"Hello World", but with"Hello" on one line and"World" on the next,'\n' is the escape sequence to use.

    >>> print("Hello\nWorld")    Hello    World

The other important escape sequence is'\t', which prints a<TAB> in the output. When you doprint("Hello\tWorld"), you can see the tab-space between"Hello" and"World".

    >>> print("Hello\tWorld")    Hello   World

Another useful escape sequence is\\ . If you want to print a\ , then use the sequence\\ . You would see that it printsHello\World . Think about what would happen if we put six\ . Yes you’re right! It would print this string:"\\\" .

    >>> print("Hello\\World")    Hello\World    >>> print("Hello\\\\\\World")    Hello\\\World

One of the things with Python is, it does not matter whether you use double quotes or single quotes to enclose strings. There are some interesting, and useful ways of using a combination of both, within the same string. Have a look at this call:print("Hello'World"), and notice the output we get. In a similar way, the following code will be accepted and run by the Python system:print('Hello"World').

    >>> print('Hello"')    Hello"    >>> print("Hello'World")    Hello'World    >>> print("Hello\"World")    Hello"World    >>> print("Hello\"World")    Hello"World

The above two examples can be used as a tip by newbie programmers when they form string literals, and want to use them in their code:

  • If the string literal contains one or more single quotes, then you can use double quotes to enclose it.
  • However if the string contains one or more double quotes, then prefer to use single quotes to enclose it.

Summary

In this step, we:

  • Explored a number of puzzles related to code involving:
    • Built-in functions for numeric calculations
    • Theprint() function to display expressions and strings
  • Covered the following aspects of the above utilities:
    • Case-sensitive aspects of names and strings
    • The role played by whitespace
    • The escape character, and common escape sequences

Step 08: Formatted Output With print()

In the previous step, we learned how to print a hard-coded string, such as"5 * 6 = 30".

In this step, let’s try to replace the hard-coded30 with a computed value.

Let’s start with a simple scenario. Let’s say we want to place that calculated value within a string, and display it. How do we do that?

Snippet-01: print() Formatted Output

format() method can be used to print formatted text.

Let’s see an example:

    >>> print("VALUE".format(5*2))    VALUE

We were expecting10 to be printed, but it’s actually printingVALUE.

How do we get10 to be printed then?

    >>> print("VALUE {0}".format(5*2))    VALUE 10

By having an open brace{, closed brace}, and and by putting the index of the value between them. Here, the value is the first parameter, and it’s index will be0.

"VALUE {0}" is what we need.

Let’s take another example. Suppose to theformat() function, we pass three values:10,20 and30.

Typically when we count positions or indexes, we start from0.

To print the first value, you need to pass in an index of0. To print the second value, pass an index of1.

    >>> print("VALUE {0}".format(10,20,30))    VALUE 10    >>> print("VALUE {1}".format(10,20,30))    VALUE 20    >>> print("VALUE {2}".format(10,20,30))    VALUE 30

Now going back to our problem, we wanted to display"5 * 6 = 30", but without hard-coding. Instead of30, we want the calculated value of5 * 6.

    >>> print("5 * 6 = 30".format(5,6,5*6))    5 * 6 = 30

Let replace"5 * 6 = 30" with"5 * 6 = {2}".2 is the index of parameter value5*6.

    >>> print("5 * 6 = {2}".format(5,6,5*6))    5 * 6 = 30

Cool! Progress made.

Let’s replace5 * 6 with the right indices -{0} * {1}.

    >>> print("{0} * {1} = {2}".format(5,6,5*6))    5 * 6 = 30

The great thing about this, is now we can replace the values we passed toprint() in the first place, without changing the indexes! So, we can display results for5 * 7 = 35 and5 * 8 = 40. We are now able to print5 * 6 = 30,5 * 7 = 35,5 * 8 = 40, and can do similar things for other table entries as well.

    >>> print("{0} * {1} = {2}".format(5,7,5*7))    5 * 7 = 35    >>> print("{0} * {1} = {2}".format(5,8,5*8))    5 * 8 = 40    >>> print("{0} * {1} = {2}".format(5,8,5*8))    5 * 8 = 40

Summary

In this step, we:

  • Discovered that Python provides a way to do formatted printing of string values
  • Looked at theformat() function, and saw how to call it withinprint()
  • Observed how we could work only with the indexes of parameters toformat(), and change the parameters we pass without changing the code

Step 09: Puzzles On format() and print()

In this step, let’s look at a few puzzles related to the format, and the print methods.

Snippet-01: format() And print() Puzzles

Let’s say we pass in additional values, such as:5 * 8,5 * 9 and5 * 10. However, within the call toformat(), we are only referring to the values at index0, index1 and index2. The values at indexes3 and4 are not used at all. What would happen when we run the code?

    >>> print("{0} * {1} = {2}".format(5,8,5*8,5*9,5*10))    5 * 8 = 40

Would this throw an error? No, it does not. You can see that the additional values which are passed in, are conveniently ignored.

Let’s say instead of passing in a value of2, we pass4. What would happen?

    >>> print("{0} * {1} = {4}".format(5,8,5*8,5*9,5*10))    5 * 8 = 50

5 * 10 is the value at index4

Now let’s take a different scenario. We remove all the parameters passed toformat(). However, inside the call toprint(), we continue to say{0} * {1} = {4}. So we are trying to print the value at index4, but are only passing two values to the functionformat(). What do you think will happen?

    >>> print("{0} * {1} = {4}".format(5,8))    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    IndexError: tuple index out of range

It saysIndexError, which means :“you are asking me to fetch the value at index4, but only passing in two values. How can I do what you want?”

Let’s look at a few more things related to other data types. We try to format the following insideprint():{0} * {1} = {2}, and would pass in2.5,2, and2.5 * 2 . Here,2 is an integer value, but2.5 is a floating point value. You can see that it prints2.5 * 2 = 5.0. So this approach of formatting values withprint(), works also with floating point data as well.

    >>> print("{0} * {1} = {2}".format(2.5,2,2.5*2))    2.5 * 2 = 5.0

Now, are there are other types of data thatformat() works with? Yes, strings can join the party.

Let’s say over here, we do:print("My name is {0}".format("Ranga")). What would happen?

    >>> print("My name is {0}".format("Ranga"))    My name is Ranga

Index0 will be replaced with the first parameter toformat().

Summary

In this step, we:

  • Understood the behavior when the parameters passed toformat():
    • Exceed the indexes accessed byprint()
    • Are less than the indexes accessed byprint()
    • Are of type integer, floating-point or string

Step 10: Introducing Variables

We are slowly making progress toward our main goal, which is to print the5 multiplication table.

In the first statement, we are printing5 * 1 = 5, and then changing the literals. To make it print5 * 2 = 10, we are changing1 to2. Next, we are changing2 to3. How do we make it a little simpler, so that our effort is reduced?

    >>> print("{0} * {1} = {2}".format(5,1,5*1))    5 * 1 = 5    >>> print("{0} * {1} = {2}".format(5,2,5*2))    5 * 2 = 10    >>> print("{0} * {1} = {2}".format(5,3,5*3))    5 * 3 = 15

Let’s try a different approach.

What would happen if you replace1 withindex, and5 * 1 with5 * index, and try to run it?

It gives an error! It says: “index is not defined”.

Let’s try and fix this, and executeindex = 2. What would happen?

    >>> index = 2

Aha! This compiles.

    >>> print("{0} * {1} = {2}".format(5,index,5*index))    5 * 2 = 10

And this statement is printing5 * 2 = 10.

Let’s try something else. Let’s makeindex = 3. What would happen?

    >>> index = 3    >>> print("{0} * {1} = {2}".format(5,index,5*index))    5 * 3 = 15

The same statement on being run, prints5 * 3 = 15.

How can you check the value thatindex has? Just type inindex.

    >>> index    3    >>> print("{0} * {1} = {2}".format(5,index,5*index))    5 * 3 = 15

Theindex symbol we have used here, is what is called avariable.

In Python, it’s also called aname.

You can see that the valueindex referring to, can change over the duration of a program.

Initially,index was referring to a value of1. later,index was referring to a value of3.

Now, think about how you would print the entire table. All that you need to do, is start from1, execute the same statement withprint() andformat(), to get output5 * 1 = 5. Next, Change the value of index to2, and then print the same statement. Next,index = 3, and print the same statement again.

    >>> index = 1    >>> print("{0} * {1} = {2}".format(5,index,5*index))    5 * 1 = 5    >>> index = 2    >>> print("{0} * {1} = {2}".format(5,index,5*index))    5 * 2 = 10    >>> index = 3    >>> print("{0} * {1} = {2}".format(5,index,5*index))    5 * 3 = 15

With the same statementprint("{0} * {1} = {2}".format(5,index,5*index)), we are able to print different values. The value ofindex varies, but the code remains the same!

Variables make the program much more easier to read, as well as more generic.

Snippet-02: Classroom Exercise On Variables

Let’s do a simple exercise with variables.

We want to create three variablesa,b andc. Let’s initially give them some values, say a value of5 toa,6 tob and7 toc.

We want to get output of this kind:5 + 6 + 7 = 18, without using the literal values.

You would want to use the values stored in the variables ina,b andc.

If you’re hard-coding, the way to do it is withprint("5 + 6 + 7 = 18").

    >>> a = 5    >>> b = 6    >>> c = 7    >>> print("5 + 6 + 7 = 18")    5 + 6 + 7 = 18    >>> print("5 + 6 + 7 = 18".format(a,b,c,a+b+c))    5 + 6 + 7 = 18

The way you can do that is with code like this:print("{0} + {1} + {2} = {3}".format(a,b,c,a+b+c)).

    >>> print("{0} + {1} + {2} = {3}".format(a,b,c,a+b+c))    5 + 6 + 7 = 18

How do you confirm we are accessing values stored in the variables?

Let’s change the values ofa,b andc. Let’s makea = 6 ,b = 7 , andc = 8 . Execute same statement.

    >>> a = 6    >>> b = 7    >>> c = 8    >>> print("{0} + {1} + {2} = {3}".format(a,b,c,a+b+c))    6 + 7 + 8 = 21

You can see the magic of variables at play here! Based on what values these variables are referring to, you can see that the output of the print statement changes.

Summary

In this step, we:

  • Were introduced to variables, or names, in Python
  • Observed how we could pass in values of variables to theformat() function

Step 11: Puzzles On Variables

In the previous step, we were introduced to the concept of variables in Python.

We will start with looking at a few puzzles.

Snippet-01: Puzzles On Variables

What if I try to refer to a variable which is not yet created?

    >>> count    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    NameError: name 'count' is not defined    >>> print(count)    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    NameError: name 'count' is not defined

Before using a variable, you need to have it assigned a value. If you have not defined a variable before, then you cannot use it. Considerprint(count), it does not know what count is. So it would throw an error, saying: “count is not defined, I have no idea what count is.”

Once you assign a value to a variable, you can use it.

    >>> count = 4    >>> print(count)    4

The statementcount = 4 where we are creating a variable namedcount for the first time, is called avariable definition.

This is the first time you’re referring to a variable, and assigning a value to it.

Python will create a variable in its memory.

Variable names are case sensitive.count andCount are not the same thing.

    >>> Count    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    NameError: name 'Count' is not defined    >>> count    4

There are rules to follow while naming variables.

All variable names should either start with an alphabet , or an underscore_ .count,_count are valid.1count is invalid.

    >>> 1count = 5      File "<stdin>", line 1        1count = 5             ^    SyntaxError: invalid syntax    >>> count = 5    >>> _count = 5    >>> 1count      File "<stdin>", line 1        1count             ^    SyntaxError: invalid syntax    >>> 2count      File "<stdin>", line 1        2count             ^    SyntaxError: invalid syntax

After the first symbol, you can also use a numeral in variable names.

    >>> c12345 = 5

To summarize the rules for naming variables.

  • This should start with an alphabet (a capital or a small alphabet) or underscore.
  • Starting the second character, it can be alphabet, or underscore, or a numeric value.

Summary

In this step, we:

  • Understood that a variable needs to be defined before it is used
  • Learned that there are certain rules to be followed while giving names to variables

Step 12: Introducing Assignment

In this step, we will look at an important concept in Python, calledassignment. In previous steps, we created variables, likei = 5.

Snippet-01: Introducing Assignment

You can create other variables using whatever valuei is referring to. If we sayj = i, what would happen?

    >>> i = 5    >>> j = i    >>> j    5

j would start referring to the same value thati is referring to. This statement is called anassignment.

Let’s tryj = 2 * i.

    >>> j = 2 * i    >>> j    10

j refers to a value of10

= has a different meaning in programming compared to mathematics.

In mathematics, When we executej = i, it meansj andi are equal.

In prgramming, the value of the expression on right hand side is assigned to the variable on the right hand side. Can you use a constant on the left hand side of an assignment? The answer is “No”!

    >>> 5 = j      File "<stdin>", line 1    SyntaxError: can't assign to literal

The Python Shell throws an error, saying “Can’t assign to literal”, as5 is a literal.

Let’s create a couple of variables.num1 = 5 andnum2 = 3. We would want to add these and create a fresh variable. Let’s say the name of the variable issum.

    >>> num1 = 5    >>> num2 = 3    >>> sum = num1 + num2    >>> sum    8

Create 3 variablesa,b andc with different values and calculate their sum.

    >>> a = 5    >>> b = 6    >>> c = 7    >>> sum = a + b + c    >>> sum    18

We have just seen the mechanics of how assignment works in Python.

Summary

In this step, we:

  • Learned what happens when you assign a value to a variable, which may or may not exist
  • Discovered that literal constants cannot be placed on the left hand side of the assignment(=) operator

Step 13: Introducing Formatted Printing

Until now, we have been using theformat() method to format and print values. Let’s see a better approach to printing values.

This is the approach we used until now.

    >>> a = 1    >>> b = 2    >>> c = 3    >>> sum = a + b + c    >>> print("{0} + {1} + {2} = {3}".format(a, b, c ,sum))    1 + 2 + 3 = 6

Python has the concept of formatted strings. The syntax to use a formatted string is very simple -f"".

If we want to print the value of a variablea, we can use{a} in the text.

    >>> print(f"")    >>> print(f"value of a is {a}")    value of a is 1    >>> print(f"value of b is {b}")    value of b is 2

The variable within braces is replaced by its value.

You can use expressions in a formatted string. Example below uses{a+b}.

    >>> print(f"sum of a and b is {a + b}")    sum of a and b is 3

This feature was introduced in a Python 3 release.

Let’s get back to the original problem we wanted to solve: printing5 + 6 + 7 = 18, using formatted strings.

    >>> print(f"{a} + {b} + {c} = {sum}")    1 + 2 + 3 = 6

You can see how easy it turns out to be!

Step 14: The PMT-Challenge Revisited

We want to print the5-table from5 * 1 = 5 onward, until we reach to5 * 10 = 50. The best solution we have right now, is shown below:

Snippet-01:

    >>> index = 1    >>> print("{0} * {1} = {2}".format(5,index,5*index))    5 * 1 = 5    >>> index = 2    >>> print("{0} * {1} = {2}".format(5,index,5*index))    5 * 2 = 10    >>> index = 3    >>> print("{0} * {1} = {2}".format(5,index,5*index))    5 * 3 = 15    >>> index = 4    >>> print("{0} * {1} = {2}".format(5,index,5*index))    5 * 4 = 20

Can we do something, to make sure that the code remains the same all the time, but theindex value gets updated?

    >>> index = index + 1    >>> print("{0} * {1} = {2}".format(5,index,5*index))    5 * 5 = 25    >>> index = index + 1    >>> print("{0} * {1} = {2}".format(5,index,5*index))    5 * 6 = 30    >>> index = index + 1    >>> print("{0} * {1} = {2}".format(5,index,5*index))    5 * 7 = 35

We usedindex = index + 1 to incrementindex value.

If we execute these same two statements again and again, we can print the entire table! This is exactly what loops help us do: execute the same statements repeatedly.

The simplest loop available in Python is thefor loop.

When we run afor loop, we need to specify the range of values -1 to10 or1 to20, and so on.range() function helps us to specify a range of values.

    >>> range(1,10)    range(1, 10)

The syntax of thefor loop is:for i in range(1, 10): .... Here,i is the name of thecontrol variable. In Python, you need to put a colon, ‘:’, and in the next line give indentation.

    >>> for i in range(1,10):    ...   print(i)    ...    1    2    3    4    5    6    7    8    9

You would see that it prints from1 to9.

When we run a loop inrange(1, 10),1 isinclusive and10 isexclusive.The loop runs from1 to the value before10, which is9.

The leading whitespace beforeprint(i) is calledindentation. We’ll talk about indentation later, when we talk about puzzles related to thefor loop.

How can you extend this concept to solving ourPMT-Challenge problem?

    >>> print(f"{5} * {index} = {5*index}")    5 * 7 = 35

What we were doing earlier, was callingprint() with a formatted string. Now we want to print this statement for different values ofi.

How can you do that?

Let’s start with a simple example.

    >>> for i in range(1,11):    ...   print(f"{i}")    ...    1    2    3    4    5    6    7    8    9    10

print(f"{i}") prints the value of i.

Now, how do we get it to print5 * 1 = 5 to5 * 10 = 50?

    >>> for i in range(1,11):    ...   print(f"5 * {i} = {5 * i}")    ...    5 * 1 = 5    5 * 2 = 10    5 * 3 = 15    5 * 4 = 20    5 * 5 = 25    5 * 6 = 30    5 * 7 = 35    5 * 8 = 40    5 * 9 = 45    5 * 10 = 50    >>> 5 * 4 * 50    1000

print(f"5 * {i} = {5 * i}") prints a specific multiple of 5.

Step 15: Loops

In a previous step, we took a major step in programming. We wrote our first for loop with Python. In this step, let’s try a few puzzles to understand the for loop even further.

The syntax of the for loop we looked at earlier was:

  for i in range(1, 10):    print(i)

Snippet-01:

Let’s say we write afor loop, but don’t give a: after therange() method, to close the first line. What would happen?

    >>> for i in range(1,10)      File "<stdin>", line 1        for i in range(1,10)                           ^        SyntaxError: invalid syntax

Invalid syntax. A: is mandatory within thefor loop syntax.

Let’s provide a: and in the next line, useprint(i) without space before it (without indentation).

    >>> for i in range(1,10):    ... print(i)      File "<stdin>", line 2        print(i)            ^    IndentationError: expected an indented block

Most other programming languages use open brace{ and closed brace} as delimiters in afor loop. However, Python uses indentation to identify which code is part of afor loop, and which is not. So if we are writing the body of afor loop, we must use indentation, and leave atleast a single<SPACE>.

    >>> for i in range(1,10):    ...   print(i)    ...    1    2    3    4    5    6    7    8    9

How do we execute two lines of code as part of thefor loop?

    >>> for i in range(1,10):    ...  print(i)    ...  print(2*i)    ...    1    2    2    4    3    6    4    8    5    10    6    12    7    14    8    16    9    18

We are indenting both statements with a space -print(i) andprint(2*i).

When for loop has only one line of code, you can specify it right after the:

    >>> for i in range(2,5): print(i)    ...    2    3    4

However, this is not considered to be a good programming practice. Even though you may want to execute just one statement in afor loop, indentation on a new line is recommended.

Another best practice is to use four<SPACE>s for indentation, instead of just two. This would give clear indentation of the code.

    >>> for i in range(2,5):    ...     print(i)    ...    2    3    4

Anybody who looks at the code immediately understands that thisprint() is part of thefor loop.

Let’s say you only want to print the odd numbers till10, which are1,3,5,7 and9. Therange() function offers an interesting option.

    >>> for i in range (1,11,2):    ...   print(i)    ...    1    3    5    7    9

Infor i in range(1, 11, 2), we pass in a third argument, called astep. After each iteration, the value ofi is increment bystep.

Summary

In this step, we:

  • Looked at a few puzzles about thefor loop, which lay emphasis on the following aspects of for:
    • The importance of syntax elements such as the colon
    • Indentation
    • Variations of therange() function

Step 16: Programming Exercise PE-BA-02

In the previous step, after initially exploring the Pythonfor loop, we looked at a number of puzzles.

In this step, let’s look at a few exercises.

Exercises

  1. Print the even numbers up to 10. We would want to print 2 4 6 8 10, using a for loop.
  2. Print the first 10 numbers in reverse
  3. Print the first 10 even numbers in reverse
  4. Print the squares of the first 10 numbers
  5. Print the squares of the first 10 numbers, in reverse
  6. Print the squares of the even numbers

Solution 1

Instead of starting with1, we need to start with2. Each time,i it would be incremented by2, and2 4 6 8 and 10 would be printed.

    >>> for i in range (2,11,2):    ...   print(i)    ...    2    4    6    8    10

Solution 2

We would want to print the numbers in reverse. Think about how you would do that using therange() function. We’d want go from10,9,8, and so on up to1.

    >>> for i in range (10,0,-1):    ...   print(i)    ...    10    9    8    7    6    5    4    3    2    1

The value to start with is10. As we discussed earlier, the end value is exclusive. So to print from10 to1, we want to end one value which is0.range(10, 0) seems to be what we need.

Usually these step value is positive, but we need to go backwards from10. Hence, we would give a step value of-1.

Solution 3

Now, let’s print the first10 even numbers in reverse.

    >>> for i in range (20,0,-2):    ...   print(i)    ...    20    18    16    14    12    10    8    6    4    2

Solution 4

Next, we would want to print the squares of the first 10 numbers.

    >>> for i in range (1,11):    ...     print(i * i)    ...    1    4    9    16    25    36    49    64    81    100

Solution 5

Let’s print the squares in the reverse order.

    >>> for i in range (10,0,-1):    ...     print(i*i)    ...    100    81    64    49    36    25    16    9    4    1

Solution 6

Print the squares of the even numbers. How to do that?

    >>> for i in range (10,0,-2):    ...     print(i*i)    ...    100    64    36    16    4

The key part is using a step of-2

We leave it as an exercise for you, to print squares of odd numbers.

Summary

In this video, we: * Tried out a few exercises involving the for loop, by playing around with printing sequences of numbers.

  • Used the for loop to simplify the solution to thePMT-Challenge problem.

Step 17: Review: The Basics Of Python

It must have been a roller-coaster ride to solve the multiplication table challenge so far. If you’re new to programming, there are a wide range of topics and concepts, that you would have learned during this small journey.

Let’s quickly revise the important concepts we have learned during this small journey.

  • 1,11,5, … are all called literals because these are constant values. Their values don’t really change. _Consider5 _ 4 _ 50`. This is an expression. `_`is an operator, and`5`, `4`and`50 are operands.
  • The namei ini = 1, is called a variable. It can refer to different values, at different points in time.
  • range() andprint() are in-built Python functions.
  • Every complete line of code is called statement. The specific statementprint(), is invoking a method. The other statement which we looked at earlier, was an assignment statement.index = index + 1 would evaluateindex + 1, and have theindex variable refer to that value.
  • The syntax of thefor loop was very simple.for var in range(1, 10) : ..., followed by statements you would want to execute in a loop, with indentation. For the sake of indentation we left four<SPACE>s in front of each statement inside thefor loop.

So that, in a nutshell, is what we have learned over the course of our first section.

Chapter 03 - Introducing Methods

In the last section, we introduced you to the basics of python. We learned those concepts by applying them to solve thePMT-Challenge problem. The code below is what we ended up with as we solved that chellenge.

Snippet-01: Current Solution ToPMT-Challenge

    >>> for i in range (1,11):    ...   print(f"8 * {i} = {8 * i}")

If we wanted to change the code to print the7 table, we need to change the value7 used in the for loop, to8. It’s simple, but still not as friendly as you would like.

    >>> for i in range (1,11):    ...   print(f"7 * {i} = {7 * i}")

To print a7 table, it would be awesome if could sayprint_multiplication_table, and give a value of 7 beside it, and it would do the rest:

    >>> print_multiplication_table(7)    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    NameError: name 'print_multiplication_table' is not defined    >>> print_multiplication_table(8)    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    NameError: name 'print_multiplication_table' is not defined

Similarly,print_multiplication_table(8), could print the multiplication table for8!

To be able to do this, we need to create amethod, or afunction. Creating a method makes the codereusable, and we can invoke that method very easily by passingarguments.

In this section, we take an in-depth look at methods.

Step 01: Defining Your First Method

Methods are very important building blocks in Python programming. In this step, we will create a simple method that prints"Hello World", twice.

Snippet-01:

When we talk about a method, we need to give it a name. We are already using an in-built Python method here, which isprint().

    >>> print("Hello World")    Hello World    >>> print("Hello World")    Hello World

Similar to that, we need to give a name to our body of code. Let’s say the name isprint_hello_world_twice.

The syntax to create a method in Python is straightforward:

  • At the start, use the keyworddef followed by a space.

  • Followed by name of the method -print_hello_world_twice.

  • Add a pair of parenthesis:().

  • This is followed by a colon: (similar to what we used in afor loop).

    >>> def print_hello_world_twice():...     print("Hello World")...     print("Hello World")...

All statements in a method should be indented. The twoprint("Hello World") are indented. So, they are part of the method body.

print_hello_world_twice() defines a method, and it has certain code inside its body.

How do we call this method? Is it sufficient to sayprint_hello_world_twice?

    >>> print_hello_world_twice    <function print_hello_world_twice at 0x10a71ef28>

Python Shell says, there’s a function defined with that specific name.

How do we execute a method? Very simple! Add a pair of parentheses to the name,()!

    >>> print_hello_world_twice()    Hello World    Hello World    >>> print_hello_world_twice()    Hello World    Hello World

Now, we are able to run the method.

Summary

In this step, we:

  • Learned we can define our own methods in the code we write
  • Understood how to define a method, and all its syntax elements
  • Saw how we can invoke a method we write

Step 02: Programming Exercise PE-MD-01

We will now leave you with two exercises, based on what we have learned about methods so far.

Exercises

  1. Write a method calledprint_hello_world_thrice(). It should print"Hello World" thrice to the output. Define this method, and also invoke it.

  2. Write and execute a method, that prints four statements:

    1. “I have created my first variable.”
    2. “I’ve created in my first loop.”
    3. “I’ve created my first method.”
    4. “I am excited to learn Python.” You need to print these four statements on four consecutive lines.

Solutions

Solution 1

    >>> def print_hello_world_thrice():    ...     print("Hello World")    ...     print("Hello World")    ...     print("Hello World")    ...    >>> print_hello_world_thrice()    Hello World    Hello World    Hello World

Solution 2

    >>> def print_your_progress():    ...     print("Statement 1")    ...     print("Statement 2")    ...     print("Statement 3")    ...     print("Statement 4")    ...    >>> print_your_progress()    Statement 1    Statement 2    Statement 3    Statement 4    def print_your_progress():        print("Statement 1")        print("Statement 2")        print("Statement 3")        print("Statement 4")

For convenience, we have changed the exact text we need to print. Call this method with the syntaxprint_your_progress(), and you’re able to execute its code.

Now try another exercise. We want to print"Statement 1","Statement 2","Statement 3" and"Statement 4" on different lines, using just one print statement. How can you do that?

    >>> def print_your_progress():    ...     print("Statement 1\nStatement 2\nStatement 3\nStatement 4")    ...    >>> print_your_progress()    Statement 1    Statement 2    Statement 3    Statement 4

We are using the newline character\n.

Let’s look at the difference between defining and executing a method.

When we are writing a method definition, we are writing the code as part of its body. It has a specific syntax, and starts with thedef keyword.

A definition by itself cannot cause the code in its body to be executed.

print_your_progress() represents a method call. The code inside the method is executed.

Summary

In this step, we:

  • Implemented solutions to a few exercises that test our understanding of Python methods. We touched concepts such as:
    • Defining a method body
    • The way to invoke a method, to run its code
    • The difference between the two

Step 03: Passing Parameters To Methods

In the previous step,we created methods. We definedprint_hello_world_twice(), and this printed"Hello World" twice. In this step, let’s talk aboutmethod arguments, orparameters.

Snippet-01:

    >>> print_hello_world_twice()    Hello World    Hello World    >>> print_hello_world_thrice()    Hello World    Hello World    Hello World

Earlier, we wrote code forprint_hello_world_thrice(), which prints the message three times.

Let’s say you want to print it five times. You would need to write another method that does what you need. Doesn’t that seem monotonous?

Instead of that, Won’t it be great if I can call the method by the same name, sayprint_hello_world(5), and it would print “Hello World” five times?

The5 which we are passing here is called anargument.

How do we define our method to accept this argument?

Let’s call our argumentno_of_times. If you have any experience with other programming languages, they generally need you to specify the parameter type. Something likeThis parameter is an integer/float/string, or other types. But Python does not require parameter type.

    >>> def print_hello_world(no_of_times):    ...    print("Hello World")    ...    print(no_of_times)    ...

Although we are not doing exactly what we set out to, let’s see what would happen. What would happen if we sayprint_hello_world() ?

    >>> print_hello_world()    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: print_hello_world() missing 1 required positional argument: 'no_of_times'

Error! Something like “Hey, you have createdprint_hello_world with a parameter, but not passing anything in here! Go ahead and pass a value”. Let’s pass in a value, such as5.

    >>> print_hello_world(5)    Hello World    5    >>> print_hello_world(10)    Hello World    10    >>> print_hello_world(100)    Hello World    100

Withprint_hello_world(5), you can see"Hello World" and5 being printed. We are now able to define this method to accept a value, and print that value by invoking it. You can pass in any value, such as10,100, or others.

Now think of a different solution for this method, where you don’t repeat the same piece of code to print"Hello World". Considerprint_hello_world(5), it should still print"Hello World"5 times. How do you do that?

Think about using something along the lines of a loop.

Snippet-02:

For now, what we are doing is we are printing"Hello World"10 times.

    >>> def print_hello_world(no_of_times):    ...    for i in range(1,10):    ...       print("Hello World")    ...    >>> print_hello_world(5)    Hello World    Hello World    Hello World    Hello World    Hello World    Hello World    Hello World    Hello World    Hello World

Our method callprint_hello_world(5) now prints"Hello World"10 times.

However just print the message5 times. We need to make use of the parameterno_of_times inside thefor loop as well.

    >>> def print_hello_world(no_of_times):    ...    for i in range(1,no_of_times):    ...       print("Hello World")    ...    >>> print_hello_world(5)    Hello World    Hello World    Hello World    Hello World

Now let’s execute the method again. You can see that it’s printing4 times only.

Why is it not printing5 times?

That’s becauseno_of_times as a second parameter torange() is exclusive.

    >>> def print_hello_world(no_of_times):    ...    for i in range(1,no_of_times+1):    ...       print("Hello World")    ...    >>> print_hello_world(5)    Hello World    Hello World    Hello World    Hello World    Hello World

Great, it’s now printing the message5 times!

    >>> print_hello_world(7)    Hello World    Hello World    Hello World    Hello World    Hello World    Hello World    Hello World

If you pass a different argument like7, the message is displayed7 times.

Something you need to always be cautious about in Python, is the indentation. Over here, thefor loop is part of the method body. So we have extra indentation for it. The print is part of thefor loop body. So guess what, even more indentation for that code.

Summary

In this step, we:

  • Learned how to pass arguments to a method
  • Understood that the method definition needs to have parameters coded in
  • Observed that arguments passed during a method call can be accessed inside a methods body

Step 04: Classroom Exercise CE-MD-01

In this step, Let’s look at a few exercises related to the method parameter.

Exercises

  1. Write a method calledprint_numbers(), that would print all successive integers from1 ton.

  2. The second one is to write a method calledprint_squares_of_numbers(), that prints squares of all successive integers from1 ton.

Solutions

Solution 1

    >>> def print_numbers(n):    ...    for i in range(1, n+1):    ...       print(i)    ...    >>> print_numbers(5)    1    2    3    4    5    >>>

If you are programming in other languages such as Java, you are used to naming methods in this way:printNumbers(). This convention is popularly known as “Camel Case”.

That’s NOT how Python programmers name their methods. Pythonic way is to use underscore_ to separate words in the method name, as inprint_numbers().

Solution 2

Let’s defineprint_squares_of_numbers(). This would be very similar toprint_numbers(), working with the same range. Only, we need to sayprint(i*i) .

    >>> def print_squares_of_numbers(n):    ...    for i in range(1, n+1):    ...       print(i*i)    ...    >>> print_squares_of_numbers(5)    1    4    9    16    25

How is a parameter different from an argument?

  • Inside the definition of the method, the name within parentheses is referred to as aparameter. In our recent exercise,n is a parameter, because it’s used in the definition ofprint_squares_of_numbers.
  • When you are passing a value to a method during a method call, say5, that value is called anargument.
  • Don’t worry too much about it. Just follow this convention for now:
    • In the method call, call it anargument.
    • In a method definition, call it aparameter.

Summary

In this step, we looked at a few simple exercises related to passing method arguments

Step 05: Methods With Multiple Parameters

In this step, let’s look at creating a method with multiple parameters.

Snippet-01:

print_hello_world accepts one parameter and prints “Hello World” the specified number of times.

    >>> def print_hello_world(no_of_times):    ...    for i in range(1,no_of_times+1):    ...       print("Hello World")    ...

Let’s say we want to print another piece of textWelcome To Python, a specified number of times. How do you do that?

You can always create another method similar to the first one, such asprint_welcome_to_python(no_of_times) and print the necessary text inside.

However, is that what a good programmer does?

A good programmer tries to create a more generic solution.

    >>> def print_string(str, no_of_times):    ...    for i in range(1,no_of_times+1):    ...       print(str)    ...    >>> print_string("Hello World", 3)    Hello World    Hello World    Hello World

The good programmer that you are, you created a new method calledprint_string(str, no_of_times) accepting a text parameter, in addition tono_of_times.

Syntax rules for method parameters are quite strict. If we sayprint_string("Welcome to Python") and run it, we get an error! Python Shell says: “I needno_of_times to be present in here”.

    >>> print_string("Welcome to Python")    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: print_string() missing 1 required positional argument: 'no_of_times'

Let’s say you want to assign default values forstr andno_of_times inprint_string(). By default, we want to always print"Hello World", and that too5 times.

The Python language makes this very easy.def print_string(str = "Hello World", no_of_times=5). The rest of the method remains the same.

    >>> def print_string(str="Hello World", no_of_times=5):    ...    for i in range(1,no_of_times+1):    ...       print(str)    ...

Now you can callprint_string(), and"Hello World" is displayed5 times.

    >>> print_string()    Hello World    Hello World    Hello World    Hello World    Hello World

If it’sprint_string("Welcome To Python"), what does it do? It prints"Welcome To Python",5 times.

    >>> print_string("Welcome to Python")    Welcome to Python    Welcome to Python    Welcome to Python    Welcome to Python    Welcome to Python

Considerprint_string("Welcome to Python", 8), it would print that string8 times.

    >>> print_string("Welcome to Python", 8)    Welcome to Python    Welcome to Python    Welcome to Python    Welcome to Python    Welcome to Python    Welcome to Python    Welcome to Python    Welcome to Python

Isn’t that cool!

Summary

In this step, we:

  • Looked at how to pass multiple parameters to a method, starting with two arguments
  • Learned how you can define default values for those parameters
  • Observed we could pass default arguments for none, some or all of those parameters

Step 06: Back To Multiplication Table - Using Methods

Let’s get back to our original goal, of why we needed methods. We wanted to create a multiplication table for a number, and observed that each time we needed to we needed change that number, we were forced to make a change in the code. This is not something we liked, and that’s why we started investigating how methods can be used.

In this step, Let’s try our hand at creating a multiplication table method.

Snippet-01:

    >>> for i in range (1,11):    ...    print(f"7 * {i} = {7 * i}")

Let’s define a method calledprint_multiplication_table(), and pass in a parameter to it.

    >>> def print_multiplication_table(table):    ...    for i in range(1,11):    ...       print(f"{table} * {i} = {table * i}")    ...    >>> print_multiplication_table(7)    7 * 1 = 7    7 * 2 = 14    7 * 3 = 21    7 * 4 = 28    7 * 5 = 35    7 * 6 = 42    7 * 7 = 49    7 * 8 = 56    7 * 9 = 63    7 * 10 = 70

Now you have the entire multiplication table for7.

You can then callprint_multiplication_table() with arguments8,9,and so on, by simply changing thetable arguemnt value.

We now want to create even betterprint_multiplication_table() method.

We want to control the start point, as well as the end point, in the call torange(). We want to sayprint_multiplication_table(7, 1, 6), to print the7 table with entries from1 to6. How can you do that?

    >>> def print_multiplication_table(table, start, end):    ...    for i in range(start, end+1):    ...       print(f"{table} * {i} = {table * i}")    ...    >>> print_multiplication_table(7, 1 , 6)    7 * 1 = 7    7 * 2 = 14    7 * 3 = 21    7 * 4 = 28    7 * 5 = 35    7 * 6 = 42

Simple! Define those range limits as additional parameters!

The other thing we can obviously do, is have default values for thestart, and theend.

    >>> def print_multiplication_table(table, start=1, end=10):    ...    for i in range(start, end+1):    ...       print(f"{table} * {i} = {table * i}")    ...    >>> print_multiplication_table(7)    7 * 1 = 7    7 * 2 = 14    7 * 3 = 21    7 * 4 = 28    7 * 5 = 35    7 * 6 = 42    7 * 7 = 49    7 * 8 = 56    7 * 9 = 63    7 * 10 = 70

Callingprint_multiplication_table(7) would give us entries from7 * 1 = 7 to7 * 10 = 70.

Now you can actually send out this method, to your friends, who would find it easy to use, and cool!

Summary

In this step, we:

  • Learned how to define a method to print the multiplication table for a number
  • Looked at how to enhance this method to make table printing more flexible
  • Further enhanced that method to accept default arguments while printing a table

Step 07: Indentation Is King

In Python, indentation denote blocks of code. So if you want to put something in afor loop, or outside it, proper indentation would be sufficient. In this step, let’s explore indentation in depth. Let’s start by creating a simple method.

Snippet-01:

    >>> def method_to_understand_indentation():    ...     for i in range(1,11) :    ...        print(i)    ...    >>> method_to_understand_indentation()    1    2    3    4    5    6    7    8    9    10

Consider the code below:print(5) is indented at the same level asfor loop.

    >>> def method_to_understand_indentation():    ...     for i in range(1,11) :    ...        print(i)    ...     print(5)    ...

You can see thatprint(5) is called only once. It is not part of thefor loop.

    >>> method_to_understand_indentation()    1    2    3    4    5    6    7    8    9    10    5

Let’s change the code in this method a bit.print(5) is indented the same way asprint(i)

    >>> def method_to_understand_indentation():    ...     for i in range(1,11) :    ...        print(i)    ...        print(5)    ...

print(5) is part of the for loop. It is executed 10 times.

    >>> method_to_understand_indentation()    1    5    2    5    3    5    4    5    5    5    6    5    7    5    8    5    9    5    10    5

Whether we’re talking about loops, methods or conditionals, proper indentation is very important in Python.

We indicate a block of code, by having all lines of that block at the same indentation level. There are no specific delimiters like for instance a pair of braces{...}, as in other programming languages.

Summary

In this step, we:

  • Ran through a few examples to see how indentation works in Python

Step 08: Puzzles on Methods - Named Parameters

In this step, let’s look at a variety of puzzles related to methods.

Snippet-01:

Consider the following method: I would want to print the default string 6 times. How do we do it?

    >>> def print_string(str="Hello World", no_of_times=5):    ...     for i in range(1,no_of_times+1):    ...        print(str)    ...    >>> print_string()    Hello World    Hello World    Hello World    Hello World    Hello World

Will it work if we call the method as in:print_string(6)?

    >>> print_string(6)    6    6    6    6    6

6 is passed as the first parameter.6 is matched tostr, and the method prints6 the default number of times, which is5.

to default to"Hello World", and print it6 times.

You can do this in Python by usingnamed parameters. During the method call, you can specifyno_of_times = 6.no_of_times is a named parameter.

There is no provision of doing something like this, in other languages like Java.

Call it asprint_string(no_of_times=6):

    >>> print_string(no_of_times=6)    Hello World    Hello World    Hello World    Hello World    Hello World    Hello World

str gets a default value, and"Hello World" is printed6 times.

Named parameters are very useful, when a method has a number of parameters, and you would want to make it very clear which parameter you’re passing a value for.

Let’s callprint_string(7, 8). what happens?

    >>> print_string(7, 8)    7    7    7    7    7    7    7    7

You would see that7 is printed8 times.

Sinceprint() method is quite flexible, you can pass a number as the first argument. You can even pass afloat.

    >>> print_string(7.5, 8)    7.5    7.5    7.5    7.5    7.5    7.5    7.5    7.5

What would be the result of this -print_string(7.5, "eight")?

    >>> print_string(7.5, "eight")    Traceback (most recent call last):      File "<stdin>", line 1, in <module>      File "<stdin>", line 2, in print_string    TypeError: must be str, not int

Note howno_of_times is used inside the method… as an argument torange().range() only accepts integers, nothing else. When you run the code withprint_string(7.5, "eight"), we get an error.

It says:TypeError: ```no_of_times``` must be ```int```, not string.

A simple rule of thumb is, if you have a parameter, you can pass any type of data to it. That could be an integer, a floating point value a string, or a boolean value. The Python language does not check for the type of a parameter. However, Python will throw an error if the function which is using that parameter, expects it to be of a specific type. Therange() function expects that theno_of_times is an integer value.

Snippet-02:

The last thing which we would be looking at, is method naming conventions. We named our methods in a consistent way:print_string,print_multiplication_table, and the like.

This is exactly the format which most Python developers use, to name their methods.

Convention is to use underscore to separate words in a name.

However, there are a few rules for naming a method: One of the important rules is also related to variable names. We observed that a variable name cannot start with a number.

    >>> def 1_print():      File "<stdin>", line 1        def 1_print():             ^    SyntaxError: invalid token

Similarly,1_print will not be accepted as a method name.

  • You can start a name with an alphabet, or with an underscore.
  • From the second character onward, you are allowed to use numeric symbols.

Methods and variables cannot be named using Python keywords.

Now, what is a keyword? For example, when we talked aboutfor loop, as in:

```for i in range(1, 11): print(i)```...
  • for is a keyword
  • in is a keyword
  • def is a keyword.

Later we will look at a few other keywords, such aswhile,return,if,else,elif, and many more.

    >>> def def():      File "<stdin>", line 1        def def():              ^    SyntaxError: invalid syntax    >>> def in():      File "<stdin>", line 1        def in():             ^    SyntaxError: invalid syntax    >>> def for():      File "<stdin>", line 1        def for():              ^    SyntaxError: invalid syntax

Summary

In this step, we:

  • Were introduced to the concept of named parameters
  • Explored the typical naming rules and conventions for methods in Python
  • Observed that reserved keywords cannot be used to name variables or methods

Step 09: Methods - Return Values

Let’s try and understand the importance of return values from a method. We will learn how to return a value from a method.

Snippet-01:

Let’s name our method asproduct_of_two_numbers(), and let’s have parametersa andb that it accepts:

    >>> def product_of_two_numbers(a,b):    ...     print(a * b)    ...    >>> product_of_two_numbers(1,2)    2

Can we take the product of these two numbers into a variable, and use it in other code, in the same program?

Suppose we say aproduct = product_of_two_numbers(1,2), is this allowed?

Let’s run this code, and see what’s stored inproduct.

    >>> product = product_of_two_numbers(1,2)    2    >>> product

It’s empty.

Theproduct_of_two_numbers() method is not really returning anything back, to be used elsewhere.

Have a look at some of the built-in Python functions, such asmax() for example.

    >>> max(1,2,3)    3    >>> max(1,2,3,4)    4    >>> maximum = max(1,2,3,4)    >>> maximum    4    >>> maximum * 5    20

If I callmax() with four parameters, as inmaximum = max(1,2,3,4), the value4 gets stored in maximum.

Later on in the code that follows, we can saymaximum * 5, or we can print the value ofmaximum, or a similar calculation. This gives our programs a lot more flexibility.

So instead of just printinga*b, if this function could return a value, that would be quite useful.

    >>> def product_of_two_numbers(a,b):    ...      product = a * b;    ...      return product    ...    >>> product_of_two_numbers(2,3)    6

We are creating a variableproduct and doing areturn product.

Lets runproduct_result = product_of_two_numbers(2, 3)

    >>> product_result = product_of_two_numbers(2,3)    >>> product_result    6    >>> product_result * 10    60

You can see how simple it is to return values from a method!

Summary

In this step, we:

  • Learned how to return values from inside a method
  • Observed how we can store the values returned by a method call

Step 10: Programming Exercise PE-MD-02

In this step let’s look at a couple of exercises about returning values from methods.

Exercises

  1. Write a method to return the sum of three integers.

  2. Write a method which takes as input two integers, representing two angles of a triangle, and computes the third angle.

Hint: The sum of the angles in a triangle is180 degrees. So if I am passing50 and50,50 plus50 is100. So some of three angles should be180, so the third angle will be180 - 100, which is80.

Solution 1

    >>>def sum_of_three_numbers(a, b, c):    ...     sum = a + b + c    ...     return sum    ...    >>> sum_of_three_numbers(1,2,3)    6    >>> something = sum_of_three_numbers(1,2,3)    >>> something * 5    30

The shorter way of doing that would have been to have a temporary variable called instead ofsum. We could directlyreturn a + b + c.

    >>> def sum_of_three_numbers(a, b, c):    ...     return a + b + c    ...    >>> something = sum_of_three_numbers(1,2,3)    >>> something * 5    30

In methods, you can usereturn expression as well. Thatexpression gets evaluated, and the value gets returned back. You’d see that the result remains the same.

Solution 2

The second is to write a method to take two integers, representing two angles of a triangle, and compute the third one.

    >>> def calculate_third_angle(first, second) :    ...     return 180 - ( first + second )    ...    >>> calculate_third_angle(50, 20)    110

In your programming career, you would be writing a number of methods. It’s very important that you are comfortable doing so. Most of the methods that you write would return values back.

That’s the reason why we’re creating a lot of examples involving method calls.

Summary

In this step, we:

  • Looked at a couple of exercises related to returning values from methods
  • Observed that returning expressions avoids creating unnecessary variables, and shortens method definitions

Chapter 04 - Introduction To Python Platform

Until now we had been using Python Shell to execute all our code.

In the real world, we’ll be write Python code in a variety of scripts. Before we would go into an IDE and use the IDE to write the script, we thought it would be useful for us to understand how you can write Python code without the benefit of an IDE.

This would also help us understand the Python environment, in-depth.

In the next few steps, we’ll be looking at how to create simple Python scripts, using any text editor of your choice. Use Notepad, Notepad++. Editpad, or whichever text editing software you are comfortable with. We’ll see what involved in executing the program, and what’s happening in the background.

Here are a few videos you might want to look at.

Step 01 - Writing and Executing Python Shell Programs

Here’s a recommended video to watch -Writing and Executing your First Python Script

Let’s get started with creating a simple script file.

We want to type in a simple Python script, or a piece of Python code, such asprint("Hello world"). Does it get any simpler than this?

We’ll save this into any folder on our hard disk, with a name ‘first.py’ .

first.py

print("Hello world")

The ‘.py’ is not really mandatory, but typically all python files end with a ‘.py’ extension.

Here’s how you can run it:

  • Launch your terminal, or command prompt
  • ‘cd’ to the folder where this python script file is saved
  • execute the commandpython first.py

You will see thatHello World will be printed.

If you are familiar with other programming languages, you would need a class, need to put the code in that class, and similar stuff.

While Python supports Object Oriented Programming, is not mandatory to create a class.

It’s almost as if you’re typing commands, starting from the line one! That’s why we call it a python script.

Summary

In this small step, we tried to create a simple python script, and we ran it from the command line. All we needed to do, was use the same command we use to launch up the python shell, and followed it up with a name of the file. We created a file called first.py, executed that, and were able to see the output on the console.

As an exercise, try and add a few more methods and try to run those methods as well, as part of this script.

Step 02 - Python virtual machine and bytecode

In this step, let’s try and understand what’s happening in the background.

We wrote a simple piece of code using a text editor. We created a file named first.py, and all we did was:python3 first.py. If you look at other languages like Java for example, there is a separate compilation phase and then an execution phase. But with Python, just this command does both compilation and execution.

We saw that, as soon as we make a change and we runpython3 first.py , the change is compiled and executed as well!

In Python, there is an intermediate format calledPython byte code. Code is first compiled to bytecode, and then executed on thePython virtual machine.

When we installed Python, we installed both the python compiler and interpreter, as well as the virtual machine.

In Python,bytecode is not standardized. Different implementations of Python have different byte code. There are about 80 Python implementations, like CPython and Jython.

  • CPython is a Python implementation in C language.
  • Jython is a Python implementation in Java language. The bytecode which Jython uses is actually Java bytecode, and you can run it on the Java virtual machine.

Python leaves a lot of flexibility to the implementations of Python. They have the flexibility to choose the bytecode, and to choose the virtual machine that is compatible. The bytecode is tied to the specific virtual machine you are using. Therefore, if you’re using CPython to compile the bytecode, you’ll not be able to use Jython to run it.

You should make sure, that whatever implementation you are using to compile, is the same one you’re using to run the code as well.

Summary

A lot of this sounds like boring theory. Don’t worry about it. As a beginner, this might not be very important for you right now.

It’s very important for you to understand the process. What’s happening is you were writing Python code, and when you ran the commandpython3 first.py, it is both compiled and executed. An intermediate format called bytecode is created, which is not really standardized in Python. The bytecode is executed in a Python virtual machine.

The idea behind this quick section, is to give you a little bit of background on what’s happening behind the scenes. I’ll see you in the next section. Until then, bye-bye!

Chapter 05 - Introduction To VSCode

Let’s start using the IDE VSCode to write our Python Code

Here are recommended videos to watch

Step 01 - Installing and Introduction to VSCode

In this quick step, we’ll help you install VSCode.

Here’s the video guide for this step

Go to Google and type in “VSCode Community Edition Download”. Click the link which comes up first:https://www.jetbrains.com/VSCode/download.

You’ll go to a page where you can choose the operating system: whether you are on Windows, Mac, or Linux.

Once you choose that, you can download the appropriate community version.

On the right hand side, you’ll see a community version, and you can click the download link, to start the download.

If you are having a problem, you can also use the direct link to download.

Once you download VSCode, all you need to do is double-click the package which is downloaded. Follow the instructions, and you can continue with the defaults, until you completely install VSCode.

When you launch VSCode for the first time, it should ask you for a theme, where you can choose the default.

You’re all set to go ahead with the next step in the course.

VSCode is an awesome IDE, and I’m sure you learn a lot about it.

Step 02 - Write and Execute a Python File with VSCode

In this step, let’s launch up the VSCode IDE, and create our first Python project with a Python script. We want to be able to launch a Python script by the end of this step.

Here’s the video guide for this step

Launch the VSCode IDE. You’ll see that it takes a little while to launch the first time, and then brings up a welcome screen.

We would want to create a number of Python files. All these files will be in a project. You can think of our project as a collection of Python scripts, or modules.

To get started, let’s create a new project by clicking ‘create new project’. Let’s name it - ‘01-first-python-project’.

Right now there are no files in the project.

Let’s create our first Python file, using the IDE.

The way you can do that is by saying ‘right-click’ -> ‘new’ -> ‘Python file’, and then we’ll give this a name of ‘hello_world’, and click OK.

Now you can go ahead and write your first Python program. Let’s write some simple code, likeprint("Hello World"), and save it.

You can do a right-click here, and say ‘Run hello_world’.

A small window comes up below, which shows the output. It says'Hello World'.

Step 03 - Execise - Write Multiplication Table Method with VSCode

Let’s start with a simple exercise. We created the multiplication table method in the Python Shell. What we do now, is we’ll create the same thing but in a Python file of its own.

Here’s the video guide for this step:

Chapter 06 - Introducing Data Types and Conditionals

Welcome to this section, where we will talk about numeric data types, and conditional program execution. After looking at the numeric and boolean data types, we will turn our attention to executing code, based on logical conditions.

Step 01: Numeric Data Types

In previous sections, we created variables of this kind:number = 5 ,value = 2.5, etc. The5 here is an integer, and integers represent numbers, such as1,2,6,-1 and-2. In Python, theclass for this particular data type isint.

If you write code liketype(5), you’d get'int' as the output.

In Python, there are no primitive types. What does that mean? Every value that you see in a Python program, is an object, an instance of someclass.

In later sections, We’ll understand what is aclass, and what is an object or an instance. For now, the most important thing for you to remember, is that behind every value, there is aclass.

Snippet-01:

Let’s look at2.5, which is a floating point value.

If you go ahead and dotype(2.5), what would you see? You would see it’s of type `float.

    >>> type(2.5)    <class 'float'>    >>> type(2.55)    <class 'float'>

When you perform a division operation between two integers, there is a chance that the result of the operation is afloat. If you do5/2, the result is2.5. If we were to do4/2, even then it’s of typefloat.

    >>> type(5/2)    <class 'float'>    >>> type(4/2)    <class 'float'>    >>> 4/2    2.0    >>> 1 + 2    3

All the operations we looked at until now, can also be performed on floating point values.

    >>> value1 = 4.5    >>> value2 = 3.2    >>> value1 + value2    7.7    >>> value1 - value2    1.2999999999999998    >>> value1 / value2    1.40625    >>> value1 % value2    1.2999999999999998

value1 - value2 returns1.299999999999998. Why?

Floating point numbers don’t really represent accurate values. That’s one of the things you need to always keep in mind.

Typically, if you’re doing any highly sensitive financial calculations, don’t usefloats to represent your values. Instead, useDecimal. More about it later.

Operations can also be performed betweenint andfloat.

    >>> i + value1    14.5    >>> i - value1    5.5    >>> i / value1    2.2222222222222223    >>>

Result of an operation between aint and afloat, is always afloat.

Summary

In this step, we:

  • Looked at the two basic numeric types:int andfloat.
  • Saw the basic operations you can do amongints, amongfloats, and also betweenints andfloats.

Step 02: Programming Exercise PE-DT-01

In this step, let’s do a simple exercise with numeric values.

Exercises

  1. You need to create a method calledsimple_interest, and pass three parameters:principal,interest andduration (in years). You also want to calculate the amount after the specific duration, and return it back. Call this method with a few example values.

For example, if you want to callsimple_interest with10000, with an interest of5 percent, for a duration of5 years, the correct answer would be as follows:10000 is the principal. In addition to10000, you get the interest. The interest for one year is10000 * 0.05, as the interest figure is in percentage.So that’s500 a year, into5 which is2500. The result would be12500, and this value should be printed.

Solution 1

    def calculate_simple_interest(principal, interest, duration) :            return principal * (1 + interest * 0.01 * duration)    print(calculate_simple_interest(10000,5,5))

Summary

In this step, we:

  • Wrote a very simple method to do a simple interest calculation

Step 03: Puzzles On Numeric Types

In this section, we are looking at numeric types. In this specific step, we would be looking at a few puzzles related to values of these types.

Snippet-01:

Let’s create a simple variablei = 1.i = i + 1. What would be the value ofi after that?

    >>> i = 1    >>> i = i + 1    >>> i    2

It would be2. There is a shortcut way of doing the same thing, by using the+= operator.

    >>> i += 1    >>> i    3

Typically in other programming languages, you can do something of this kind:i++. There is no provision in Python to use increment operators like++, in either prefix or suffix mode, like++i, ori++.

    >>> i++      File "<stdin>", line 1        i++          ^    SyntaxError: invalid syntax    >>> ++i    3

Let’s look at compound assignments.

    >>> i += 1    >>> i    4    >>> i -= 1    >>> i    3    >>> i /= 1    >>> i *= 2    >>> i    6.0

What you see here, is Dynamic Typing in Python. The type of a variable can change during the lifetime of the program.

>>> i = 2>>> type(i)<type 'int'>>>> i = i/2.0>>> type(i)<type 'float'>

Let’s create a couple more numbers.number1 = 5 andnumber2 = 2. What could be the result ofnumber1 / number2? You know it, it’s2.5 .

number1 // nummber2 truncates the value of2.5, to2.

    >>> number1//number2    2

If you can donumber1 // number2, can you also do this:number1 //= number2?

    >>> number1 //= 2    >>> number1    2

5 ** 3 is5 ‘to the power of’3, which is5 * 5 * 5, or125.

    >>> 5 ** 3    125    >>> pow(5,3)    125

This can also be achieved by invokingpow(5, 3). We have an operator, as well as a method at our disposal.

The last thing we will look at, are type conversion functions.

If you need to convert anint value to afloat, or afloat to anint.

    >>> int(5.6)    5

What if you want to round a value?5.6 is nearer to6 than5. You can use a function calledround(), and here,round(5.6) gives the correct result6.

    >>> round(5.6)    6    >>> round(5.4)    5    >>> round(5.5)    6

round() can also allows you to specify number of decimals in the result.

    >>> round(5.67, 1)    5.7    >>> round(5.678, 2)    5.68

You can also convertint tofloat, by using the functionfloat().

    >>> float(5)    5.0

Summary

In this step, we:

  • Looked at a few corner cases related to your numeric types.
  • Examined the different operators available for use with values of numeric types
  • Learned about the usage of type conversion functions

Step 04: Introducing Boolean Type

We will now shift our attention to thebool data type.

A boolean value is something which can be either “true” or “false”.

Snippet-01:

In Python, “true” is represented byTrue, and “false” byFalse. It’s important to remember that it’sTrue with a capital'T', andFalse with a capital'F'.

    >>> True    True    >>> False    False    >>> true    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    NameError: name 'true' is not defined    >>> false    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    NameError: name 'false' is not defined

The boolean variableis_even indicates whether a number is even or not.

    >>> is_even = True    >>> is_odd = False

Let’s create a variablei = 10. We want to find out ifi > 15. What do you think is the result?False.

    >>> i = 10    >>> i > 15    False    >>> i < 15    True

In general, boolean values can represent the result of logical conditions.

Let’s look at other operations that can result inbool values. We looked at> and<. Another operation which you can perform, is>=.

    >>> i >= 15    False    >>> i >= 10    True    >>> i > 10    False    >>> i <= 10    True    >>> i < 10    False

== is the comparison operator. We are only comparing the value ofi against10, not changing its value.

    >>> i == 10    True    >>> i == 11    False

Summary

In this step, we:

  • Were introduced to thebool data type
  • Learned thatbool variables are useful handy while testing logical conditions

Step 05: Introducing Conditionals

In this step, let’s look atif statement.

Sometimes you need to execute code only when certain conditions are true. You can use aif condition, which is the simplest conditional in Python. Let’s look at an example.

Snippet-01:

Let’s sayi has a value of5. You want to print something, only ifi has a value greater than3. How do you do that?

    >>> i = 5    >>> if i>3:    ...     print(f"{i} is greater than 3")    ...    5 is greater than 3

The syntax of theif is very simple:if followed by a condition; with the condition you want to check. It looks like:if i>3: ... You need to indent the body of theif with<SPACE>s as usual.

Let’s sayi has a value of2. What would happen if we execute the same code again?

    >>> i = 2    >>> if i>3:    ...     print(f"{i} is greater than 3")    ...

You would see that nothing is printed to the console. Based on the value ofi , either the statement is executed, or it’s not. That’s what anif helps us to do.

The way you can think about anif, is the body of code under theif is executed only when this condition isTrue. If this condition is notTrue, that code is not executed at all.

    >>> if(False):    ...   print("False")    ...    >>> if(True):    ...   print("True")    ...    True

Let’s take two different numbers, saya = 5, andb = 7. We want to compare them, and predict ifa is greater thatb .

    >>> a = 5    >>> b = 7    >>> if(a>b):    ...   print("a is greater than b")    ...    >>> a = 9    >>> if(a>b):    ...   print("a is greater than b")    ...    a is greater than b

Summary

In this step, we:

  • Were introduced to theif statement, the simplest Python conditional
  • Understood how anif helps in implementing conditional program logic

Step 06: Classroom Exercise CE-DT-01

In this step, let’s look at a couple of exercises with the if statement.

Snippet-01:

Let’s say we define four variables:a = 1,b = 2 ,c = 3 andd = 5. we want to find out, ifa + b is greater thanc + d.

    >>> a = 1    >>> b = 2    >>> c = 3    >>> d = 5    >>> if a+b > c+d :    ...    print("a+b > c +d")    ...    >>> a = 9    >>> if a+b > c+d :    ...    print("a+b > c +d")    ...    a+b > c +d

Let’s say we are given three values meant to be the angles of a triangle. Their values areangle1 = 30,angle2 = 20 andangle3 = 60. You want to find out if these three angles actually form a valid triangle. You know that the sum of the angles of a triangle is always180 degrees.

    >>> angle1 = 30    >>> angle2 = 20    >>> angle3 = 60    >>> if(angle1 + angle2 + angle3 == 180):    ...      print("Valid Triangle")    ...    >>> angle2 = 90    >>> if(angle1 + angle2 + angle3 == 180):    ...      print("Valid Triangle")    ...    Valid Triangle

The last exercise is to check if a number is even or not.

Hint L you need to use one of the operators we talked about earlier. That’s right, use the modulo operator%.

    >>> i = 2    >>> if(i%2==0):    ...   print("i is even")    ...    i is even    >>> i = 3    >>> if(i%2==0):    ...   print("i is even")    ...

Summary

In this step, we:

  • Looked at a few exercises related to the if statement, for writing and testing conditions.

Step 07 - Logical Operators - and or not

In this step, let’s look at the different operators that can be used onbool values. These operators are called logical operators -and,or ,not and^ (xor).

Let’s say we have a valueTrue, and the otherFalse, and we want to play around with them.

Logical operatorand returns true only when both operands areTrue.

    >>> True and False    False    >>> True and True    True    >>> True and False    False    >>> False and True    False    >>> False and False

Logical operatoror returns true when atleast one of the operands isTrue.

    False    >>> True or False    True    >>> False or True    True    >>> True or True    True    >>> False or False

Logical operatornot returns negation.

    False    >>> not True    False    >>> not(True)    False    >>> not False    True    >>> not(False)    True

The XOR operation, denoted by the^ operator, isTrue when operands have different boolean values.

    >>> True ^ True    False    >>> True ^ False    True    >>> False ^ True    True    >>> False ^ False    False

Summary

In this step, we:

  • Looked at the logical operators that act on boolean values, such asand,or,not and^
  • Explored each of these operators, finding out when they returnTrue, and whenFalse.

Step 08: Puzzles On Logical Operators

In this step, Let’s look at a few simple puzzles to look at the logical operators.

Snippet-01:

Let’s sayi has a value of10, andj has a value of15. You want to find out if bothi andj are even. How do you do that?

    >>> i = 10    >>> j = 15    >>> if i%2==0 and j%2==0:    ...   print("i and j are even")    ...    >>> j = 14    >>> if i%2==0 and j%2==0:    ...   print("i and j are even")    ...    i and j are even    >>> if i%2==0 or j%2==0:    ...      File "<stdin>", line 2        ^    IndentationError: expected an indented block    >>> if i%2==0 or j%2==0:    ...   print("atleast one of i and j are even")    ...    atleast one of i and j are even

If we want to find out if at least one ofi andj is even, we can use theor operator.

    >>> i = 15    >>> j    14    >>> if i%2==0 or j%2==0:    ...   print("atleast one of i and j are even")    ...    atleast one of i and j are even    >>> j = 23    >>> if i%2==0 or j%2==0:    ...   print("atleast one of i and j are even")    ...    >>> i    15

Now try and guess the value of this.if(True ^ False): print("Message")

    >>> if(True ^ False):    ...     print("This will Print")    ...    This will Print    >>> if(False ^ True):    ...     print("This will Print")    ...    This will Print    >>> if(True ^ True):    ...     print("This will Print")    ...

Xor operation using^ - message will get printed if the operands are different.

What would happen if both of them areTrue? No message is printed.

So you would use^ in situations, where you’d want one of the operands to beTrue, and the other to beFalse.

Let’s say,x = 5, and you want to checkif not x == 6: print("This"). What will be the result of running this code?

    >>> x = 5    >>> if not x == 6:    ...   print("This")    ...    This    >>> x = 6    >>> if not x == 6:    ...   print("This")    ...

Actually, there is a shortcut for such a condition:if x != 6 : print("This").

    >>> if x!=6:    ...   print("This")    ...    >>> x=5    >>> if x!=6:    ...   print("This")    ...    This

int() is a conversion function, which when given say afloat value, returns anint value. Considerint(True), what would happen?

    >>> int(True)    1    >>> int(False)    0

int(True) returns 1.int(False) returns 0.

    >>> x = -6    >>> if x:    ...   print("something")    ...    something

One of the most interesting facts about boolean stuff, is anything which is non-zero, is considered to beTrue.

0 is the only integer value which is considered to beFalse.

    >>> bool(6)    True    >>> bool(-6)    True    >>> bool(0)    False    >>>

So, if I have a value ofx = -6, and executeif x: print("something") what do you think will happen?

"something" will be printed.

You can use the functionbool(), to convertint to abool value.

  • bool(6) returnsTrue
  • bool(-6) returnsTrue
  • bool(0) returnsFalse.

Except forbool(0), all the other results would beTrue.

Summary

In this step, we:

  • Looked at a few puzzles related to the logical operators
  • Looked at conversion functions such asbool() andint() to convert between boolean and integer data

Step 09:

In this step, let’s look at two other important components of anif statement:else andelif. Let’s start withelse.

Snippet-01:

Consider a scenario wherei has a value of2. Let’s try to print a message"i is even" ifi is an even number. Otherwise, print"i is odd".

Earlier we wrote code along these lines:if i % 2 == 0 : print("i is even"). However if this condition is notTrue, we would want toprint("i is odd"). How do we accomplish that?

    >>> i = 2    >>> if i%2 == 0:    ...   print("i is even");    ... else:    ...   print("i is odd");    ...    i is even

Anelse clause provides an alternative code body to execute, if theif condition isFalse.

    >>> i = 3    >>> if i%2 == 0:    ...   print("i is even");    ... else:    ...   print("i is odd");    ...    i is odd

Let’s look atelif.

We want to do something ifi has value of3, and something totally different ifi has a value of4.

In short, we want to specify 2 alternatives to theif condition. How can that be done?

    >>> if i==1:    ...   print("i is 1")    ... elif i==2:    ...   print("i is 2")    ... else:    ...   print("i is not 1 or 2")    ...    i is not 1 or 2    >>>

That’s where theelif clause comes into the picture. The code inelif is executed if the previous conditions are false and the currentelif condition is true.

Summary

In this step, we:

  • Looked at two important components of theif statement:else andelif.
  • Understood that theelif clauses and the finalelse clause provide alternative conditions to check, when earlier if conditions are true.

Step 10: Classroom Exercise CE-DT-02

In this step, let’s do a simple exercise withif,else andelif.

Before getting to the exercise, let’s try and learn how to get console input from the user.

Until now, we had been hard-coding all the data we were to use. Let’s make that part more dynamic now.

Snippet-01:

How do we get input from the user? We want to get input from the console, and assign it to a variable. The way we can do that, is by statementvalue = input()

    value = input("Enter a Value: ")    print("you entered ", value)

We can call theinput() method with a text ‘prompt’, such as"Enter A Value: ". What we can initially do here, is print the value which was entered, back to the console, byprint("you entered ", integer_value).

An interesting point to explore here, is the type of data input at the console.

Let’s do aprint(type(value)).

    value = input("Enter a Value: ")    print("you entered ", value)    print(type(value))

Input a value ofTest. It has a class ofstr.

Let’s run it again to see other possibilities. This time, let’s enter a numeric value, say12. what would happen?

We again getstr.

We want to get an integer value from the input. How can we do it?

int() function converts string to int. Let’s use it.

value = input("Enter a Value: ")integer_value = int(value)print("you entered ", integer_value)print(type(integer_value))

Let’s run our code once again.

"Enter A Value: " is prompted, and we enter15. And now, of it says"You entered 15", and the type it indicates to us, isint.

Design a menu

  • Ask the User for input:
    • Enter two numbers
    • Choose the Option:
      • 1 - Add
      • 2 - Subtract
      • 3 - Multiply
      • 4 - Divide
  • Perform the Operation
  • Publish the Result

Let’s design a menu, and then ask the user for input.

We have codes for each of the operations : add is1, subtract is2, divide is3, and multiply is4.

In the first version of the program let’s get all the inputs and print them out.

Solution

The first version of the program is simple to write

number1 = int(input("Enter Number1: "))number2 = int(input("Enter Number2: "))print(f"You entered {number1}")print(f"You entered {number2}")print(number1 + number2)print("\n\n1 - Add")print("2 - Subtract")print("3 - Divide")print("4 - Multiply")print("5 - Exit")choice = int(input("Choose Operation: "))print(choice)

We will continue this exercise to complete it, in the next step.

Summary

In this step, we:

  • Looked at the in-builtinput() function that can read console input
  • Learned thatinput() always returns what the user enters, as a string
  • We can convert the string frominput(), to the data type we expect by invoking conversion functions

Step 11: Continued - Classroom Exercise CE-DT-02

Exercises

In the previous step, we got the input from the user. Let’s continue the exercise in this step. We want to write an if condition.

Solution (Continued)

Extending the solution is easy. Write appropriateif,elif andelse conditions.

number1 = int(input("Enter Number1: "))number2 = int(input("Enter Number2: "))print("\n\n1 - Add")print("2 - Subtract")print("3 - Divide")print("4 - Multiply")choice = int(input("Choose Operation: "))# print(number1 + number2)# print(choice)if choice==1:    result = number1 + number2elif choice==2:    result = number1 - number2elif choice==3:    result = number1 / number2elif choice==4:    result = number1 * number2else:    result = "Invalid Choice"print(result)

We added the following code to account for invalid input.

else:    result = "Invalid Choice"

Summary

In this step, we:

  • Augmented the Menu Exercise to get all the input from the console, and compute a value from them
  • Corrected the logic to handle incorrect input

Step 12: Puzzles On Conditionals

In this step, let’s look at a few puzzles related to theseif,elif andelse clauses.

Puzzle-01

Let’s start with the first puzzle. Guess the output.

k = 15if (k > 20):  print(1)elif (k > 10):  print(2)elif (k < 20):  print(3)else:  print(4)

When we run it, you can see that the output is2.

k has a value of15, is it greater than20? No! Execution goes to theelif, isk greater then10? Yes. It prints2 and goes out of the completeif-else block.

Inside theif conditional, theif,elif andelse clauses are all independent ones. Only one matching block is ever executed.

Puzzle-02

What do you think would be the output of this particular piece of code?

l = 15    if (l < 20):        print("l<20")if (l > 20):    print("l>20")else:    print("Who am I?")

Note that there are two totally differentif conditions in here :if l < 20: ... immediately followed byif l > 20: ... else: ....

The firstif is true.l<20 is printed.

The secondif is a separate statement. The condition is false. So.else gets executed. Therefore,"who am I" gets printed.

Puzzle-03

Let’s run this code.

m = 15if m>20:    if m<20:        print("m>20")    else:        print("Who am I?")

You can see that nothing is printed.

The most important thing to focus on here, is indentation.

The secondif block is executed only if the firstif is true.

Puzzle-04

What would be the output?

number = 5if number < 0:  number = number + 10number = number + 5print(number)

10 is printed.

The most important thing to focus on here, is indentation.

Onlynumber = number + 10 is part ofif block. It is not executed because the condition is false.

number = number + 5 is not part ofif. So, it gets executed.

Let’s add a couple of spaces beforenumber = number + 5.

What would be the output?

number = 5if number < 0:  number = number + 10  number = number + 5print(number)

5 is printed.

Both the statementsnumber = number + 10 andnumber = number + 5 are part ofif block. They are not executed because the condition is false.

Summary

In this step, we:

  • Looked at a few puzzles related toif,elif andelse
  • Explored the importance of indentation and the different condition clauses inside anif statement

Step 01: The Python Type To Denote Text

Let’s start looking at another important data type in Python, that’s used to represent strings. Not surprisingly, it is in fact namedstr!

Let’s look at valid string representations.

    >>> message = "Hello World"    >>> message = 'Hello World'    >>> message = 'Hello World"      File "<stdin>", line 1        message = 'Hello World"                          ^     SyntaxError: EOL while scanning string literal

In Python, you can use either ```or""` to delimit string values.

type() method can be used to find type of a variable.

    >>> message = "Hello World"    >>> type(message)    <class 'str'>

Thestrclass provides a lot of utility methods.

    >>> message.upper()    'HELLO WORLD'    >>> message.lower()    'hello world'    >>> message = "hello"

message.capitalize() does init caps. Only first character is changed to uppercase.

    >>> "hello".capitalize()    'Hello'    >>> 'hello'.capitalize()    'Hello'

You can also run this directly -'hello'.capitalize(). Isn’t that cool!

That’s because each piece of text in python is an object of thestrclass, and we can directly call methods of thatclass onstr objects.

Now let’s shift our attention to methods, which gives us more information about the specific contents of a string.

  • We want to find out if this string contains numeric values?
  • Does it contain alphabets only?
  • Does it contain alpha-numeric values?
  • Is it lowercase?
  • Is it uppercase?

To find if a piece of text contains only lower case alphabets.

    >>> 'hello'.islower()    True    >>> 'Hello'.islower()    False

If the first letter is in uppercase, thenistitle() will return aTrue value.

    >>> 'Hello'.istitle()    True    >>> 'hello'.istitle()    False

To find if a piece of text contains only upper case alphabets.

    >>> 'hello'.isupper()    False    >>> 'Hello'.isupper()    False    >>> 'HELLO'.isupper()    True

isdigit() checks if a string is a numeric value.

    >>> '123'.isdigit()    True    >>> 'A23'.isdigit()    False    >>> '2 3'.isdigit()    False    >>> '23'.isdigit()    True

isalpha() checks if a string only contains alphabets.

    >>> '23'.isalpha()    False    >>> '2A'.isalpha()    False    >>> 'ABC'.isalpha()    True

isalnum() checks if a string only contains alphabets and/or numerals.

    >>> 'ABC123'.isalnum()    True    >>> 'ABC 123'.isalnum()    False

Lastly, we look at things which you can use, to check characters of a string.

endswith is self explanatory.

    >>> 'Hello World'.endswith('World')    True    >>> 'Hello World'.endswith('ld')    True    >>> 'Hello World'.endswith('old')    False    >>> 'Hello World'.endswith('Wo')    False

startswith is self explanatory as well.

    >>> 'Hello World'.startswith('Wo')    False    >>> 'Hello World'.startswith('He')    True    >>> 'Hello World'.startswith('Hell0')    False    >>> 'Hello World'.startswith('Hello')    True

find method returns if a piece of text is present in another string. Returns the first match index.

    >>> 'Hello World'.find('Hello')    0    >>> 'Hello World'.find('ello')    1

A value of-1 is returned, if you’re searching for something which is not present in the string.

If you are searching for'Ello' with a capital'E' ,you’ll not be able to find it. Search is case sensitive.

    >>> 'Hello World'.find('Ello')    -1    >>> 'Hello World'.find('bello')    -1    >>> 'Hello World'.find('Ello')    -1

Step 02: Type Conversion Puzzles

We’ll now try and convert values from one type to another, and try and play around with them.

str converts boolean value to a text value.

    >>> str(True)    'True'

All text value except for empty string represent True. So,bool returns True for everything except empty string.

    >>> bool('True')    True    >>> bool('true')    True    >>> bool('tru')    True    >>> bool('false')    True    >>> bool('False')    True    >>> bool('')    False

Let’s try and convert a few integer values to strings.

    >>>str(123)    '123'    >>> str(12345)    '12345'    >>> str(12345.45678)    '12345.45678'

Let’s do the reverse.

    >>> int('45')    45    >>> int('45.56')    ValueError: invalid literal for int()

if we doint('45.56'), you can see that it throws an error. It says “I cannot convert this to anint, as45.56 is an invalid integer”.

You can also pass an additional parameter toint indicating the numeric system - 16 for Hexa decimal, 8 for Octal etc. Default is 10 - Decimal.

    >>> int('45abc',16)    285372    >>> int('a',16)    10    >>> int('b',16)    11    >>> int('c',16)    12    >>> int('f',16)    15    >>> int('g',16)    ValueError: invalid literal for int() with base 16: 'g'

You can also convert string to float.

    >>> float("34.43")    34.43    >>> float("34.43rer")    ValueError: could not convert string to float: '34.43rer'

Summary

In this quick step, we looked at converting different types to strings, and converting strings to different types. So we looked atint,bool andfloat values, and we looked at how to convert them to string, and how to convert strings back to these specific types.

Step 02: Strings Are Immutable

In this step, let’s learn an important fact about strings in Python.

String values are immutable.

What does immutability mean, and why do we say strings are immutable?

Let’s create a very simple string:message = 'Hello', and we’re sayingmessage.upper(). But what does it do? It prints'HELLO', with all characters in uppercase. Well, what would happen if you doprint(message)? It says'Hello'.

    >>> message = "Hello"    >>> message.upper()    'HELLO'    >>> message    'Hello'

You would see we tried change the content of message, but it has not changed.

When we executemessage.upper(), a new string is created, and it is returned back. Original string remained unchanged. This is called immutability.

Once you define a string in Python, you’ll not be able to change the value of it.

You can use - “OK. I can do something of this kind:message = message.upper()”.

What would happen now?

Will the value ofmessage get changed? It prints'HELLO', with all caps.

Did the value ofmessage change? Does this prove that strings are mutable?

The important thing you need to understand about all this stuff, is how objects are stored inside Python.

There are things called variables, and there are things called objects.

When we runmessage = 'Hello'

  • We are creating one object ofstr class with a values'Hello'.
  • We are creating one variable calledmessage
  • The location of'Hello' is stored intomessage

In Python, your variables are nothing but a name.

If location of'Hello' in memory isA, then the value stored inmessage isA.message is called a reference.

What happens withmessage = message.upper()?

A new object is created with value'HELLO' at a different locationB.

A reference ot locationB is stored intomessage variable.

Summary : The original value at locationA has not changed and cannot be changed forstr variables. Hence ‘str’ objects are immutable.

Variables are just names referring to a location. They don’t really contain the value. Variables contain a reference to the location that contains the object.

Step 03: Python Has No Separate Character Type

One of the things that surprises people new to Python, is that there is no character data type in Python.

Typically we have text data types in all the languages, don’t we?'Hello World' for example, is text data, and we stored it inmessage. This is called a string.

In other languages, you would have something to represent a single character symbol. For example in Java, you can have achar data type, to store a single characterch, in which'h' is one character. But in Python, there is no separate data type to store single characters.

For example, let’s see how Python treats the first character of the following stringmessage. The way you can access the first character of a string is by sayingmessage[0].

    >>> message = "Hello World"    >>> message[0]    'H'    >>> type(message[0])    <class 'str'>    >>> type(message)    <class 'str'>

type(message[0]) andtype(message) print the same typestr. No difference.

In Python, whether you’re talking about a string, or you’re talking about a single character symbol, they are all represented by the sameclass,str.

message[100] throws anIndexError.

    >>> message[0]    'H'    >>> message[1]    'e'    >>> message[2]    'l'    >>> message[3]    'l'    >>> message[100]    IndexError: string index out of range

It says: “The given index is out of the range of the value of that specific string”.

Let’s say we would want to print all the characters in this string.

The way you could do that, is by saying:for ch in message: print(ch).

Summary

In this short step, we looked at the fact that there is no separate character class, or data type in Python. We also looked at how do we loop over a given string, and print all the characters present inside this string.

Step 04: Thestringmodule

In this step, we will introduce you to thestringmodule.

If we would want to use anything from a module in Python, you need to import that specificmodule into your program.

    >>> import string

If you do astring. and press , it would show the different things which are part of thestringmodule.

    >>> string.    string.Formatter(       string.ascii_uppercase  string.octdigits    string.Template(        string.capwords(        string.printable    string.ascii_letters    string.digits           string.punctuation    string.ascii_lowercase  string.hexdigits        string.whitespace

Let’s explore some of these.

    >>> string.ascii_letters    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'    >>> string.ascii_lowercase    'abcdefghijklmnopqrstuvwxyz'    >>> string.ascii_uppercase    'ABCDEFGHIJKLMNOPQRSTUVWXYZ'    >>> string.digits    '0123456789'    >>> string.hexdigits    '0123456789abcdefABCDEF'    >>> string.punctuation    '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'    >>> string.ascii_letters    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

You have a set of printable characters, punctuation characters and a lot more.

You can check a text value against any of these

    >>> 'a' in string.ascii_letters    True    >>> 'ab' in string.ascii_letters    True    >>> 'abc' in string.ascii_letters    True

in operation on a string, checks if a given string.

    >>> '1' in '13579'    True    >>> '2' in '13579'    False    >>> '4' in '13579'    False

Summary

In this step, we explored more exercises involving thestr module of Python.

Step 05: More Exercises With Thestr Module

Let’s start with an Exercise - find if a specific character is a vowel or not.

    >>> char = 'a'    >>> vowel_string = 'aeiouAEIOU'    >>> char in vowel_string    True    >>> char = 'b'    >>> char in vowel_string    False

he other thing you can do, is just have the capital vowels, or just the lowercase versions.

    >>> vowel_string = 'AEIOU'    >>> char.upper() in vowel_string    False    >>> char = 'a'    >>> char.upper() in vowel_string    True

Now let’s move on to the next one.

We want to find out and print all the capital alphabets, fromA toZ.

There was a small clue at the start of the previous step, regarding importing thestringmodule. We did thestringmodule, and we saw thatstringmodule contained a number of things.

    >>> string.ascii_uppercase    'ABCDEFGHIJKLMNOPQRSTUVWXYZ'    >>> for char in string.ascii_uppercase:    ...   print(char)    ...    A    B    C    D    E    F    G    H    I    J    K    L    M    N    O    P    Q    R    S    T    U    V    W    X    Y    Z

Try another easy exercise: print all the lower characters. Instead ofstring.ascii_uppercase, you havestring.ascii_lowercase.

    >>> for char in string.ascii_lowercase:    ...   print(char)    ...    a    b    c    d    e    f    g    h    i    j    k    l    m    n    o    p    q    r    s    t    u    v    w    x    y    z

An even easier exercise, would be to print all the digits.

    >>> for char in string.    string.Formatter(       string.ascii_uppercase  string.octdigits    string.Template(        string.capwords(        string.printable    string.ascii_letters    string.digits           string.punctuation    string.ascii_lowercase  string.hexdigits        string.whitespace    >>> for char in string.digits:    ...   print(char)    ...    0    1    2    3    4    5    6    7    8    9    >>>

The last exercise which we want to leave you with, is to check if something is a consonant.

A consonant is an alphabet which is not a vowel, so any alphabet which is not in'aeiou' is a consonant. The simplest way of doing this is to sayconsonant_string = 'bcdfghj...' and so on. Looks like a very long solution? There is an easier way out.

    >>> vowel_string = 'aeiou'    >>> char = 'b'    >>> char.isalpha() and char.lower() not in vowel_string    True

Step 06: More Exercises On Strings

In the step, let’s look at a few more puzzles and exercises related to strings. Let’s say we have a simple string,string_example, and this is contains an English sentence.'This is a great thing.'

Let’s try to to print each of the words present in this string, on a separate line.

So we would want to print'This','is','a','great' and'thing' on individual lines.

One of the clues we’ll give you is, try and dostring_example. <TAB>. There are a huge list of methods, which would come up if you do that.

    >>> string_example = "This is a great thing"    >>> string_example.    string_example.capitalize(    string_example.join(    string_example.casefold(      string_example.ljust(    string_example.center(        string_example.lower(    string_example.count(         string_example.lstrip(    string_example.encode(        string_example.maketrans(    string_example.endswith(      string_example.partition(    string_example.expandtabs(    string_example.replace(    string_example.find(          string_example.rfind(    string_example.format(        string_example.rindex(    string_example.format_map(    string_example.rjust(    string_example.index(         string_example.rpartition(    string_example.isalnum(       string_example.rsplit(    string_example.isalpha(       string_example.rstrip(    string_example.isdecimal(     string_example.split(    string_example.isdigit(       string_example.splitlines(    string_example.isidentifier(  string_example.startswith(    string_example.islower(       string_example.strip(    string_example.isnumeric(     string_example.swapcase(    string_example.isprintable(   string_example.title(    string_example.isspace(       string_example.translate(    string_example.istitle(       string_example.upper(    string_example.isupper(       string_example.zfill(

One of the methods in the list is thesplit() method.

    >>> string_example.split()    ['This', 'is', 'a', 'great', 'thing']    >>> for word in string_example.split():    ...    print(word)    ...    This    is    a    great    thing

split_lines() method looks for a'\n', and it divides the string based on it. If you have a string which contains newlines, and you would want to divide it into a number of strings with each line as a new element, the method you can use issplit_lines().

    >>> string_example = "This\nis\n\ngreat\nthing"    >>> print(string_example)    This    is    great    thing    >>> string_example = "This\nis\na\ngreat\nthing"    >>> print(string_example)    This    is    a    great    thing    >>> string_example.splitlines()    ['This', 'is', 'a', 'great', 'thing']    >>>

The last thing which we look at, isconcatenation operator.

    >>> 1 + 2    3    >>> "1" + "2"    '12'    >>> "1" + 1    TypeError: must be str, not int    >>> "ABC" + "DEF"    'ABCDEF'

In Python, you cannot do+ operator between two different types.+ with two strings is concatenation.+ with two numbers is addition.

One other interesting operator on strings is multiplication. If you do a'1' * 20, What do you think will be the output?

    >>> 1 * 20    20    >>> '1' * 20    '11111111111111111111'    >>> 'A' * 10    'AAAAAAAAAA'

If you multiply a string withnumber, the string value is concatenatednumber times.

The last thing which we look at in this step, is comparing strings.

Let’s say we have a string with a valuestr = 'test', and you have another string to with a valuestr1 = 'test1'.

We want to check whether both these strings are the same.

    >>> str = "test"    >>> str2 = "test1"    >>> str == str2    False    >>> str2 = "test"    >>> str == str2    True

You can compare strings using the== operator.

Summary

In this step, we explored a few exercises on strings, covering areas such as:

  • Splitting a given sentence into individual words
  • The concatenation operator,+
  • The string multiplication pattern,*
  • The use of the== operator to compare strings

Chapter 07 - Introducing Loops

Welcome to the section on Loops. In this section, we will look at a variety of loops that are available in Python. We will look mainly at thefor loop, and thewhile loop.

Step 01: Revisited: The for Loop

Let’s start with revising the basics of the for loop, we have learned in the previous steps.

We saw that afor loop helps us to loop around the same set of code statements, many times over.

Let’s look at a few simple examples, once again.

Snippet-01

The syntax of afor loop is very simple.

For example, this code snippet will tell you all about it:for i in range(1, 11): print(i).

What does this do? Very simple, it prints from1 to10.

In the call to therange() function, the second parameter is exclusive. We are actually looping from1 to10, and this piece of code,print(i), is being executed for different values ofi.

    >>> for i in range(1,11):    ...   print(i)    ...    1    2    3    4    5    6    7    8    9    10

for loop can also be used to loop round the characters in a string.

    >>> for ch in "Hello World":    ...   print(ch)    ...    H    e    l    l    o    W    o    r    l    d

for loop can be used to loop around all the words in a given sentence.

    >>> for word in "Hello World".split():    ...   print(word)    ...    Hello    World

for loop can be used to loop around a specific list of values.

    >>> for item in (3, 6, 9):    ...   print(item)    ...    3    6    9

Summary

In this step, we started with discussing and revising basic concepts about thefor loop

Step 02: Programming Exercise PE-LO-01

Welcome back to this step, where we would do a lot of exercises with thefor loop.

Exercises

  1. The first exercise is to find out if a number is prime. We want to write a method,is_prime(), which accepts an integer value as parameter, and returns whether it’s a prime. (Hint: A prime number is something which is only divisible by1 and itself).

    1. 5 is only divisible by1 and5. It is not divisible by any other number. Same is the case with7 and11.
    2. However,6 is divisible by1,2,3 and6. So it’s not a prime number.
  2. The second exercise is to write a method to calculate the sum up to a given integer, starting from1.Hint: If I would want to find that the sum up to6. what’s needed is1 + 2 + 3 + 4 + 5 + 6.

  3. The third exercise is to find that the sum of divisors of a given integer.Hint: Let’s say we want to find out the sum of the divisors of15. The divisors of15 are1,3,5 and15. So I would want to calculate1 + 3 + 5 + 15, and return that value.

  4. Fourth exercise is to print a numbered triangle, when given a specific integer.

Hint: Given an input5, we would want to print the number triangle of these kind:

11 21 2 31 2 3 41 2 3 4 5.

These are the exercises for thefor loop. We also test our skills, with creating method and executing them, in our IDE.

Solution 1

Let’s start with creating theis_prime() method, in a file namedfor_exercises.

We would want to accept anint parameter, and find out if it is prime, or not.

We need to check whether it’s divisible by any other number, other than1 and itself. If we are passed in a value of5, you want to see if it’s divisible by any of2,3 or4.

def is_prime(number):

We can use afor loop. We can structure it like this:for divisor in range(1, number): .... We would not want to divide it with1, but start with2 instead, and go up tonumber-1, which is4.

for divisor in range(2,number):

How can we check if thenumber is divisible bydivisor?

By using the% operator. Ifnumber is divisible bydivisor we returnFalse.

for divisor in range(2,number):    if number % divisor == 0:        return False

What happens if the code comes up to the end? It would mean we tried with2,3 and4, butnumber was not divisible by all of them. In that case,number would be prime, and we can safely returnTrue.

for divisor in range(2,number):    if number % divisor == 0:        return Falsereturn True

For1, the rules are a little different, as it is neither a prime or composite. We will add anif condition to check if the number is1.if(number < 2):

Thisif condition is called a guard check or a boundary check, to make sure that you are processing only the right input. Ifnumber has a value less than2, do nothing. OK, it’s not a prime.

Here is the entire code at one place, for your reference:

def is_prime(number):    if(number < 2):        return False    for divisor in range(2,number):        if number % divisor == 0:            return False    return Trueprint(is_prime(5));

Step 03: Continued - Programming Exercise PE-LO-01

In the previous step, we looked at solving theis_prime() exercise. In this step, let’s look at an implementation ofsum_up_to_n(). Here is the entire code for this exercise:

def sum_upto_n(number):    sum = 0    for i in range(1, number+1):        sum = sum + i    return sumprint(sum_upto_n(6))print(sum_upto_n(10))

Summary

In this step, we:

  • Wrote a Python function to compute the sum of all integers, from1, up to the input integern.

Step 04: Continued - Programming Exercise PE-LO-01

Let’s focus on the third exercise,sum_of_divisors.

One of the clues we can give you, is thatsum_of_divisors() is very similar tois_prime().

You want to find out if a number is dividing15, and if it’s dividing15, with the remainder of0, then you need to add that up.

def calculate_sum_of_divisors(number):    sum = 0    if(number < 2):        return sum    for divisor in range(1,number+1):        if number % divisor == 0:            sum = sum + divisor    return sumprint(calculate_sum_of_divisors(6))print(calculate_sum_of_divisors(15))

Step 05: Continued - Programming Exercise PE-LO-01

In this step, Let’s look at the last exercise -print_a_number_triangle.

For example, if we call such a function with input5, the output needs to be:

11 21 2 31 2 3 41 2 3 4 5

Let start with a simple thing. Let’s try and print1 2 3 4 5 first, and then we would look at how to print the rest of the output. Lets proceed with defining this method.

We can saydef print_a_number_triangle(number): ... that takes a number as an input. You want to print a sequence of integers starting from1, up to that specificnumber. How can you do that? Let’s try this:for i in range(1,number+1): print(i) What would happen? Let’s callprint_a_number_triangle(5) now. It prints:

    1    2    3    4    5

on individual lines.

To print this sequence on a single line, let’s delimit them with<SPACE> instead. Callprint() like this instead:for i in range(1,number+1): print(i, end=" ").

Let’s see what would happen now.1 2 3 4 5

To solve our exercise, we want to repeat this again and again.

Yes, we need another for loop around it!

for j in range(1, number+1):    for i in range(1, number + 1):        print(i, end=" ")

Make sure that you have the indentation right. This is calledloop within a loop.

The output of above program is

1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5

Let’s addprint("\n"), so we have a new line at the end of each outer loop iteration.

for j in range(1, number+1):    for i in range(1, number + 1):        print(i, end=" ")    print("\n")

Output

1 2 3 4 51 2 3 4 51 2 3 4 51 2 3 4 51 2 3 4 5

We are printing a square, not a triangle.

What we want to do is to print up to1 in first line, upto2 in second line and so on.

How can we do that? Think about it.

When you are inside this loop, you can see the variablej.

Instead ofnumber+1, let’s sayj + 1.

Whenj has a value of1,for will print from1 to1. Whenj has a value of2, print from1 to2, literally printing1 2. When j has a value of3, I’ll print from1 to3. Let’s try this and see what would happen.

for j in range(1, number+1):    for i in range(1, j + 1):        print(i, end=" ")    print("\n")

You can see that our number triangle is ready!

11 21 2 31 2 3 41 2 3 4 5

Here is the entire code for you:

def print_a_number_triangle(number):    for j in range(1, number + 1):        for i in range(1, j + 1):            print(i, end=' ')        print()print_a_number_triangle(6)

An important point to note is, a couple of these things can be done in a much simpler way. We will look at these options when we talk about functional programming.

Summary

In this step, we:

  • Presented a solution to the exercise for printing a number triangle.

Step 06: Introducing The while Loop

Let’s look at one of the other loops which is present in Python, called thewhile loop.

In thefor loop, we can specify the range of our iteration, by using therange() function.

In awhile loop, we specify a logical condition. While the condition is true, loop continues running.

Do you remember one place where we use the condition until now? It was in anif statement.

Let’s see how to use a simplewhile loop.

Snippet-01:

    >>> i = 5    >>> if i == 5:    ...   print("i is 5")    ...    i is 5

Let’s sayi has a value of0, and we then do:while i < 5: print(i).

    >>> i = 0    >>> while i < 5:    ...   print(i)    ...    0    0    0    0    0    0    0    0    ^CTraceback (most recent call last):      File "<stdin>", line 2, in <module>    KeyboardInterrupt    >>>    KeyboardInterrupt

If we leave it to run, you’d see that it continuously prints0 again, and again. Let’s do a<CTRL-C> or<COMMAND-C> to interrupt this.

What is happening here?

Initiallyi is0, and the conditioni < 5 isTrue, andprint(i) is executed. Next iteration, it checks the condition, it isTrue, and0 is printed. This continues to happen. What’s happening is aninfinite loop.

One of the important things to make sure in awhile loop, is to increment the value ofi. We need to say something likei = i + 1.

    >>> while i < 5:    ...   print(i)    ...   i = i + 1    ...    0    1    2    3    4

So how does it work? *i initially had a value of0. First the condition is checked. It’sTrue, so0 is printed and then the value ofi is incremented to1.

  • i is still less than5, so the loop continues to execute, and this happens until4 is printed.i again gets incremented to4 + 1, or5.
  • Then we check the conditioni < 5. This is nowFalse. Control goes out of thewhile loop, and terminates it.

When executing awhile, control flow is just based on a condition. As long as the condition isTrue, we keep executing the code. An important thing to remember, is to make sure the control variable is updated.

    >>> for i in range(0,5): print(i)    ...    0    1    2    3    4

Afor loop is much simpler to code than awhile. Withwhile, we have to write an expression statement, to increment the value.

The question you might have is - What are the situations when you should use a while?

We will look at that very soon.

Summary

In this video, we:

  • Were introduced to the concept of awhile loop in Python
  • Understood the importance of a control variable being incremented inside the loop
  • Observed differences between the working of awhile, and afor loop

Step 07: Programming Exercise PE-LO-02

In the previous step, we were introduced towhile loop. In this step, let’s look at a couple of exercises using thewhile loop.

Exercises

  1. print_squares_upto_limit(30): We need to print all the squares of numbers, up to a limit of30. The output needs to be1 4 9 16 25.

  2. print_cubes_upto_limit(30): We need to print all the cubes of numbers, up to a limit of30.The output needs to be 1 8 27.

Exercise 1: Solution

Here is the entire code for your reference:

def print_squares_upto_limit(limit):    i = 1    while i * i < limit:        print(i*i, end = " ")        i = i + 1

Now the next exercise, was to print cubes up to a limit.

The expression in thewhile condition should now bei*i*i < 30.

def print_cubes_upto_limit(limit):    i = 1    while i * i * i < limit:        print(i*i*i, end = " ")        i = i + 1print_cubes_upto_limit(80)

Could we have implemented above two examples withfor loop? It would’ve been a little more difficult.

Typically, we use afor loop when we know how many times the loop will be executed is clear at the start.

If we do not know, how many times a loop will run,while is a better option.

Step 08: While Example

Earlier we usedif statement to implement a solution for this:

  • Ask the User for input:
    • Enter two numbers
    • Choose the Option:
      • 1 - Add
      • 2 - Subtract
      • 3 - Multiply
      • 4 - Divide
  • Perform the Operation
  • Publish the Result

We would want to enhance it to execute in a loop multiple times, until the user chooses to exit. We will add an option 5 - Exit.

  • Ask the User for input:
    • Enter two numbers
    • Choose the Option:
      • 1 - Add
      • 2 - Subtract
      • 3 - Multiply
      • 4 - Divide
      • 5 - Exit
  • Perform the Operation
  • Publish the Result
  • Repeat until Option 5 is chosen.

Snippet-01 Explained

Here’s the earlier code we wrote with if:

number1 = int(input("Enter Number1: "))number2 = int(input("Enter Number2: "))print("\n\n1 - Add")print("2 - Subtract")print("3 - Divide")print("4 - Multiply")choice = int(input("Choose Operation: "))# print(number1 + number2)# print(choice)if choice==1:    result = number1 + number2elif choice==2:    result = number1 - number2elif choice==3:    result = number1 / number2elif choice==4:    result = number1 * number2else:    result = "Invalid Choice"print(result)

Let’s usewhile around theif. We cannot predict what choice the user enters. We’ll say:while choice != 5:... and at the end, we would want to ask the user for a choice. If your choice is anything other than5, we will give the output, and print the whole menu again.

number1 = int(input("Enter Number1: "))number2 = int(input("Enter Number2: "))print("\n\n1 - Add")print("2 - Subtract")print("3 - Divide")print("4 - Multiply")print("5 - Exit")choice = int(input("Choose Operation: "))while(choice != 5):    # print(number1 + number2)    # print(choice)    if choice==1:        result = number1 + number2    elif choice==2:        result = number1 - number2    elif choice==3:        result = number1 / number2    elif choice==4:        result = number1 * number2    else:        result = "Invalid Choice"    print(result)    choice = int(input("Choose Operation: "))print("Thank You")

These are the kind of situations wherewhile loop is good. W

Summary

In this step, we:

  • Enhanced the menu exercise done earlier, to allow the user to give operation choices repeatedly
  • Found that awhile loop was ideal to solve this exercise

Step 09 - Loops - Puzzles - break and continue

We would be discussing about a wide variety of puzzles related tofor loop, andwhile loop.

Snippet-01:

What would be the output of this script?

    for i in range(1,11,2):        print(i, end=' ')

Output :1 3 5 7 9

`range()function accept astepparameter. It starts with1, and at each step it increments by2.11is exclusive. So`11``` is not printed.

Let’s look at the next one.

for i in range(11,0,-1):    print(i,  end=' ')

Output :1 10 9 8 7 6 5 4 3 2 1

On to the next puzzle.

i = 5while i*i < 10:    print(i)print("done")

Output :done

On to the next puzzle.

i = 2while i * i < 10:  print(i, end=" ")print('done')

Output :222222222222....

It’s printing2 continuously. We forgot the increment. Let’s try and fix this.

 i = 2 while i*i < 10:     print(i,  end=' ')     i = i + 1 print("done")

Output :2 3 'done'.

Now, let’s look at a new puzzle, with a new key word,break.

for i in range(1,11):    if i==5:       break    print(i,  end=' ')print("done")

Output :1 2 3 4 'done'

break breaks out of the loop when executed. With5, the condition matchesif i==5.break is executed, and we get outside thefor loop.

Let’s look at the next puzzle:

for i in range(1,11):    if i%2:       break    print(i ,  end=' ')print("done")

Output :'done'

You don’t really see anything being printed from the for loop.

When you evaluate1 % 2, it returns1 as the remainder. Any non-zero number is considered to beTrue. We break out of the loop.

Next Puzzle:

for i in range(2,11):    if i%2:       break    print(i ,  end=' ')print("done")

It prints2, because2 % 2 is0, and0 isFalse, so the print is executed as thebreak is not called. However when it becomes3,3 % 2 is 1, which is considered to beTrue. Thebreak is executed, and we exit out of the loop.

Let’s look at a new keyword, calledcontinue. Look at the following code:

for i in range(1,11):   if i%2==0:     continue   print(i ,  end=' ')print("done")

It’s printing1 3 5 7 9 'done'

What do you think will be the output?

continue skips the code inside thefor loop for the current iteration, and then resumes the next one.

Lines aftercontinue in loop are skipped and you’d start the next iteration of the loop.

What would happen, if we remove thei%2 == 0, and only have condition asi%2?

for i in range(1,11):   if i%2:     continue   print(i ,  end=' ')print("done")

It prints even numbers only. For odd numbers,i%2 isTrue. They are skipped.

The last puzzle we’ll be looking at is exactly a modification of the earlier one. Instead of.i%2, we give the condition asi % 2 != 0.

for i in range(1,11):   if i%2!=0:     continue   print(i ,  end=' ')print("done")

What do you think will be the output? Yes you’re right. No change in output, becauseif i % 2 !=0 is the same as aif i % 2. That’s because ifi % 2 is0, theni % 2 will beFalse. Ifi % 2 is0, theni % 2 != 0 also will beFalse.

Chapter 08 - Python Tips

Tip 1 - Using Predefined Python Modules

There are a number of predefined modules in Python, providing a wide variety of features for use. In this step, let’s learn how to import a module, and how to use methods from specific modules.

Let’s talk about themathmodule to start off with. Import it by sayingimport math. If you domath. and press<TAB>, it shows all the functions that are defined in themathmodule.

    >>> import math    >>> math.    math.acos(       math.erf(        math.inf         math.pi    math.acosh(      math.erfc(       math.isclose(    math.pow(    math.asin(       math.exp(        math.isfinite(   math.radians(    math.asinh(      math.expm1(      math.isinf(      math.sin(    math.atan(       math.fabs(       math.isnan(      math.sinh(    math.atan2(      math.factorial(  math.ldexp(      math.sqrt(    math.atanh(      math.floor(      math.lgamma(     math.tan(    math.ceil(       math.fmod(       math.log(        math.tanh(    math.copysign(   math.frexp(      math.log10(      math.tau    math.cos(        math.fsum(       math.log1p(      math.trunc(    math.cosh(       math.gamma(      math.log2(    math.degrees(    math.gcd(        math.modf(    math.e           math.hypot(      math.nan

math.floor(4.5) gives you back4.

If you want to find out a little bit more about themath.floor(), sayhelp(math.floor).

This command would show you the documentation for thisfloor() function. It says “floor(x) returns the floor of x as an integer. This is the largest integer, which is less than or equal to x”.

    >>> math.floor(4.5)    4    >>> help(math.floor)    >>> help(math)

You can import all the members from the entire module by usingfrom math import *.

What would happen now, is all the functions which are present inmath, are visible in your namespace.

You can directly callfloor(5), without the need formath.floor().

You can dogcd(2, 4), wheregcd() finds the greatest common divisor of these two numbers.

For help, You can usehelp(gcd), and it responds with the documentation.

An important things to remember, is when you doimport * from math, you are importing everything from there. This means if you have any local variable with the names as these functions, they might get shadowed.

    >>> from math import *    >>> floor(5)    5    >>> gcd(34,56)    2

Typically it’s not really considered to be a good practice to import everything into the namespace.

If there are specific things that you would want to import and use them directly, Then you can import just that, by doing this:from math import floor. Alsofrom math import gcd.

    >>> from math import gcd    >>> gcd(56,68)    4

Step 74: Tip 2 - Getting Index Element

Let’s next look at a tip regarding loops. In certain scenarios with loops, you might want to access the index of the element. That’s what we would be looking at, in this specific tip.

Let’s say we have a listnumbers = [1, 4, 6, 3, 4]. Looping through this will be like this:for number in numbers: print(number), which will simply print the numbers. However, if you want to find the index of a specific element from within the loop, how would you do that?

    >>> numbers = [1,4,6,3,4]    >>> for number in numbers:    ...   print(number)    ...    1    4    6    3    4

You can achieve that by sayingfor index, number in enumerate(numbers): print(number).

enumerate() is a built-in Python method, which makes available both the index, and the number.

We can now print a formatted string, by accessing{index} and{number}.

    >>> for index,number in enumerate(numbers):    ...    print(f'{index} - {number}')    ...    0 - 1    1 - 4    2 - 6    3 - 3    4 - 4

This would also work for strings, consider'aeiou'. This contain all the vowel characters. Now if we loop around it:for index, vowel in enumerate (values): print(f'{index}{vowel}'). Nothing fancy in here. You can print the index, as well as the particular vowel character.

    >>> values = list('aeiou')    >>> values    ['a', 'e', 'i', 'o', 'u']    >>> for index, vowel in enumerate(values):    ...     print(f'{index} - {vowel}')    ...    0 - a    1 - e    2 - i    3 - o    4 - u

Short Hand If Statement

In this step, let’s look at a way in which you can make yourif statements, even simpler.

Let’s say you have a number,number = 5. You want to find out, if it’s even or not, and store it in a name callisEven. Typically, the way you can write that is really simple, isn’t it! You can useif number % 2 == 0: isEven = True else: isEven = False.However, there is even simpler way of doing this!

    >>> number = 5    >>> if(number%2==0):    ...   isEven = True    ... else:    ...   isEven = False    ...

You can useisEven = True if number % 2 == 0 else isEven = False . You can see what it contains.

    >>> isEven = True if number%2==0 else False    >>> isEven    False

Now let’s havenumber = 6, and do it again.

    >>> number = 6    >>> isEven = True if number%2==0 else False    >>> isEven    True

his is a shortcutif statement, which is very useful when you have simple condition, based on which you want to set the values.

Actually the even easier way of doing this, would have been to do this -isEven = number%2 == 0 .

If the return value is something like a string, what would you do?

Let’s say you want, instead ofTrue orFalse, a'yes' or'no' result. You can useisEven = 'yes' if number%2 == 0 else 'no'.

    >>> isEven = number%2==0    >>> isEven = "Yes" if number%2==0 else "No"    >>> isEven    'Yes'

In this step, we quickly took a look at shortcuts forif statement.

Tip 4 - Beginners Mistakes - Shadowing

In this step, we’ll talk about a mistake which a lot of beginners make.

Let’s talk about the built-insum() function. You can pass it lists of values, and it would add them up.

    >>> sum    <built-in function sum>    >>> sum([12,34,56])    102

Now let’s say you are trying to solve a problem, where you want to have two numbers:number = 10, andnumber2 = 20. During the validating logic,we have to add these up, so what we do issum = number1 + number2.

    >>> number1 = 10    >>> number2 = 20    >>> sum = number1 + number2    >>> sum    30

What would happen now if you call thissum([12,34,56])?

    >>> sum([12,34,56])    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: 'int' object is not callable

The compiler says “TypeError in object”. It’s not callable. Why is it coming up , is we are shadowing the global built-insum() function, with a local variable of our own.

The bad practice we’re doing in here is shadowing a global function with a local variable. And that’s not good.

The way we could have avoided that is by using a different name, maybe calling itsum_of_two_numbers, or even ` ``sum_```. This would prevent us from shadowing some built-in function.

    >>> sum_ = number1 + number2    >>> del sum    >>> sum    <built-in function sum>    >>> sum([12,34,56])    102

Summary

The best practice is to avoid having variables named with the same names as a building function.

Tip 3 - Python is Strongly Typed and Dynamic Language

In this step, we look at important concept about Python, that it isstrongly typed, but is also adynamically typed language.

What is the strongly typed property of Python? Let’s say a variablea has a value, soa = 1 . Can I do alen(1) ? Nope, it’s not allowed, because the type ofa does not allow it. What is thetype(1)? It is the type ofa here, which isint. On anint, an operation calledlen() is not really defined.

    >>> a = 1    >>> len(1)    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: object of type 'int' has no len()    >>> type(a)    <class 'int'>

Now consider the variablestr, that has the text'Value' stored inside it. On this variable , we would be able to saystr.upper(), and this would print'VALUE'.

    >>> str = "Value"    >>> str.upper()    'VALUE'

Will I be able to doa.upper(), in a similar fashion? Ina, a method calledupper() is not really defined. In Python, as we have already seen, everything is an object.

    >>> a.upper()    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    AttributeError: 'int' object has no attribute 'upper'

Even Considertype(1), it’s alwaysint.1.5 is always afloat,'value' was, ans is, astr.

    >>> type(1)    <class 'int'>    >>> type(1.5)    <class 'float'>    >>> type("1.5")    <class 'str'>

What aboutboolean values? It’sbool. So everything that you see in a Python program, including methods and the data values, are instances of someclass.

    >>> type(True)    <class 'bool'>    >>> type(str)    <class 'str'>

The two important things we have learned over here are:

  • Python is strongly typed. You cannot do anything that is not allowed by a specific type on an instance of that specific type. And if you do, so you would get an error.
  • The second thing which we looked at, was the fact that everything in Python is an object.

The other important concept over here is, we havestr binding to'value'. What is the value oftype(str) right now? It’s astr, a string.

However one can always say in Python,str = 1, that is reassignstr with1 .

What would be thetype(str) now? it’s of a typeint.

Type of thestr can change during the run-time of the program.

    >>> str = 1    >>> type(str)    <class 'int'>

It can be now aboolean, or and you can assign alist to it as well.

    >>> str = True    >>> type(str)    <class 'bool'>

What istype(str) right now? The type islist.

    >>> str = [1,2]    >>> type(str)    <class 'list'>

Step 79: Tip-6 - PEP8 Python Style Guide

In this quick step, we’ll talk aboutPEP 8. PEP stands for Python Enhancement Proposal, and PEP 8 Is the style guide for Python programs. If you search on Google for PEP 8, you’ll land up on with this document, and you can see it’s quite old. This was actually created in 2001, and the awesome thing is, it lays down all the guidelines on how you can write good Python code.

An important thing we love about Python, is the fact that it is very practical, and has a variety of resources surrounding it. While defining this style guide, one of the PEP 8 statements says: “Do not follow the PEP blindly. Think about it, and then follow the guidelines”. Guidelines may not be applicable to 100% of the code scenarios. Make sure that you’re using your judgment in the best way.

What are the different things that are discussed in this style guide?

You can find it out here -https://www.python.org/dev/peps/pep-0008/

Summary

As you get better with Python, spend more time with PEP8, so that you get a better understanding of good coding practices.

Step 80: Tip-7 - PEP20 Zen Of Python

In this quick tip, we look atPEP 20.

It’s also popularly called the “Zen of Python”. This document was created way back in 2004.

The Zen Of Python says: “Beautiful is better than ugly”, “Explicit is better than implicit” and “Simple is better than complex”.

This is how you should think, when you are writing your Python code. The Zen of Python tries to explain what are the code design decisions you should take while programming.

One of the things which it focuses a lot on, is expressing clarity. Your code should be simple to read, and easy to understand. As soon as you look at a piece of code, you should be able to understand what it is doing. You can see a phrase saying “Readability counts”, and “Flat is better than nested”.

If you have a lot of nested structure, the code is inherently difficult to understand. Rather than that approach, having a flat structure is considered to be better.

Making sure that what you are writing is explicit or clear to look at, is much more important than being implicit, because it makes code obscure.

“Never hide errors”. If there’s an error,and it can be handled, don’t try to suppress it. Make sure that you are trying to handle it, and that there is enough information for someone to look at, to handle at a later point in time.

PEP 20 also says “Keep the implementation easy to explain”.

If you are lazy like us, and you don’t want to go to Internet to read the Zen Of Python, all that you need to do is import this document, and this would print The Zen Of Python on your computer.

>>> import thisThe Zen of Python, by Tim PetersBeautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.Flat is better than nested.Sparse is better than dense.Readability counts.Special cases aren't special enough to break the rules.Although practicality beats purity.Errors should never pass silently.Unless explicitly silenced.In the face of ambiguity, refuse the temptation to guess.There should be one-- and preferably only one --obvious way to do it.Although that way may not be obvious at first unless you're Dutch.Now is better than never.Although never is often better than *right* now.If the implementation is hard to explain, it's a bad idea.If the implementation is easy to explain, it may be a good idea.Namespaces are one honking great idea -- let's do more of those!>>>

As a beginning programmer, a lot of these might not really make sense.

This is a document we would recommend you to visit, every once in a while to gain some insights. As you work and write more code, you will see that most of these start making sense.

An important thing to realize, is that the basic idea behind all these 19 principles is very simple. Whatever code you write, should be understandable for other programmers.

Chapter 09 - Introducing Object Oriented Programming

Welcome to section on object oriented programming. The way you think in structured or procedural programming, is completely different from how you would think inobject oriented programming, orOOP. In this chapter, you’ll be introduced to thinking in terms of objects. We will discuss about: what is a class, what is an object, what is state, what is behavior, and also discuss about a few basic and important OOP concepts, such as encapsulation and abstraction. Of course, we will use a lot of examples to discuss these aspects of OOP, and the different terminology which is used with respect to the same. We are excited to bring this section to you.

Step 01: OOP - The Basics

Object oriented programming is all about thinking in terms of objects. Before we get into depth with this, we’ll talk a little bit about structured programming.

If you have written programs in a language such as C or Pascal, you’d be doingprocedural orstructured programming. Such programming involves thinking in terms of procedures. These are also popularly known as methods or functions.

Let’s say you have a problem to solve. The first thing you would try and do, is to split the problem into multiple functions, or multiple procedures. You would start thinking in terms of: OK, what are the functions I would need to write? What are the different steps involved in doing this?

Humans think in a step by step process.

Let’s say I’ve to take a flight from London to New York. This is how I would think:

  • Take a cab to London Airport
  • Check in
  • Pass Security
  • Board the flight
  • Wish the Hostess
  • Take Off
  • Cruise
  • Land
  • Get off the plane
  • Take a cab to ..

Procedural programming is just a reflection of this thought process. A procedural program for above process would look something like this:

takeACabToLondonAirport();checkIn();passSecurity();boardPlane();wishHostess();takeOff();cruiseMode();land();getOffPlane();//...

Object Oriented Programming (OOP) brings in a new thought process around this.

How about thinking in terms of the different Actors? How about storing data related to each actor right beside itself? How about giving them some responsiblity and let them do their own actions?

Here’s how our program would look like when we think in terms of different actors and give them data and responsibilities

    Person        name        boardFlight(Plane flight), wishHostess (Hostess hostess), getOffFlight(Plane flight)    AirPlane        altitude, pilot, speed, flightMode        takeOff(), cruiseMode(), land()    Hostess        welcome()

Do not worry about the implementation details. Focus on the difference in approaches.

We haveencapsulated data and methods into these entities, which are now calledobjects. We have defined object boundaries, and what it can (and cannot) do.

An object has

  • State : Its data
  • Behavior : Its operations

Theposition of anAirplane can change over time. The operations that can be performed on anAirplane includetakeOff(),land() andcruiseMode(). Each of these actions can change itsposition. Therefore, an object’s behavior can affects its own state.

It’s now time to introduce you to some coreOOP terms, which will make our future discussions easier.

Step 02 - OOP Terminology

Let’s visit and enhance thePlanet example we had written a few sections ago. This time, let’s also explore the conceptual angle.

Planet

    class Planet        name, location, distanceFromSun // data / state / fields        rotate(), revolve() // actions / behavior / methods    earth : new Planet    venus : new Planet

Let’s look at someOOP terminology.

Aclass is a template. Anobject is an instance of a class. In above example,Planet is a class.earth andvenus are objects.

  • name,location anddistanceFromSun compose object state.
  • rotate() andrevolve() define object’s behavior.

Fields are the elements that make up the object state. Object behavior is implemented throughMethods.

Each Planet has its own state:

  • name: “Earth”, “Venus”
  • location : Each has its own orbit
  • distanceFromSun : They are at unique, different distances from the sun

Each has its own unique behavior:

  • rotate() : They rotate at different rates (and in fact, different directions!)
  • revolve() : They revolve round the sun in different orbits, at different speeds

Summary

In this step, we:

  • Understood how OOP is different from Prodedural Programming
  • Learned about a few basic OOP terms

Step 03: Programming Exercise PE-01

Exercises

In each of the following systems, identify the basic entities involved, and organize them using object oriented terminology:

  1. Online Shopping System
  2. Person

Solution-1: Online Shopping System

    Customer        name, address        login(), logout(), selectProduct(Product)    ShoppingCart        items        addItem(), removeItem()    Product        name, price, quantityAvailable        order(), changePrice()

Solution-2: Person

    Person        name, address, hobbies, work        walk(), run(), sleep(), eat(), drink()

Step 04: Classes And Objects

After hearing a lot of theory about OOP, it’s time to get our hands dirty.

Let’s get started, with trying to create aclass in Python.

The syntax is very simple. Let’s say you want to create aCountryclass,class Country. For now, you don’t want to do anything in this class, so we’ll saypass.

pass helps us to create an emptyclass.pass can also be used to create an empty method.class is the key word and colon is part of the syntax.Country is the name of theclass.

    >>> class Country:    ...     pass    ...

class acts as a template. It’s a blueprint, and based on this blueprint, we can create instances of theclass.

How can we create instances of class in Python?

india is the name of the instance, andCountry is the name of the class.

    >>> india = Country()    >>> usa = Country()    >>> netherlands = Country()

These instances are also called objects. We have created three objects of theCountryclass.

Each of these objects have their own state. Right now, the class does not provide any data elements, the state of these objects is empty.

Let’s add a little bit of state to these objects. How can you add state? By creating attributes.

Let’s use :india.name = ‘India’. We can also sayindia.capital = ‘New Delhi’.

    >>> india.name = 'India'    >>> india.capital = 'New Delhi'

What is the state of theindia object?

It has the name of ‘India’, the capital of ‘New Delhi’.

However the state ofusa, andnetherlands are still empty.

Let’s create some state for them as well.

    >>> usa.name = 'USA'    >>> usa.capital = 'Washington'    >>> netherlands.name = 'Netherlands'    >>> netherlands.capital = 'Amsterdam'

Now we have state in each of these objects.

Each of these objects have their own individual state. When we are changing the state ofnetherlands, or the state ofusa, the state ofindia does not change.

    >>> india.name    'India'

Step 05: TheMotorBike Class Example

In this step, Let’s create aclass in the IDE. We want to call the class asMotorbike. We create a few instances of the specificclass.

How can we define a class?

How do we create instances of the class? You just need to sayhonda =MotorBike() ,ducati =MotorBike().

We’ll go ahead, and print these objects,print(honda) andprint(ducati).

Let’s see what would happen when we run this code.

class MotorBike:passhonda = MotorBike()ducati = MotorBike()print(honda)print(ducati)

Output

<__main__.MotorBike object at 0x7fbceddd41d0><__main__.MotorBike object at 0x7fbceddd4278>

You can see that two objects are being printed.

We can also add a little bit of state to these motor bikes.

class MotorBike:passhonda = MotorBike()ducati = MotorBike()honda.speed = 50ducati.speed = 250print(honda)print(ducati)print(honda.speed)print(ducati.speed)

Output

<__main__.MotorBike object at 0x7fbceddd41d0><__main__.MotorBike object at 0x7fbceddd4278>50250

The state of an object can change during the lifetime of the object.

Time for an Exercise : Book class

Create a new class calledBook. Create three instances ofBook. Have you favorite books as the name of the object instances, let each of these instances have an attributename, and set the name of the book into that object. At the end, print the name of all three instances of the books.

Here’s the solution:

class Book: passthe_art_of_computer_programming = Book()learning_python = Book()learning_restful_services = Book()the_art_of_computer_programming.name = 'The Art of Computer Programming'learning_python.name = 'Learning Python'learning_restful_services.name =  'Learning Restful Services In 50 Steps'print(the_art_of_computer_programming.name)print(learning_python.name)print(learning_restful_services.name)

The initial versions of theMotorBike and theBook class we are creating here, are quite basic.

During the course of this section, will enhance these two classes to be having more functionality.

Step 06: Class And Objects: Puzzles

In this quick step, we will look at a few puzzles related to what we have learned about: classes and objects.

Let’s create a new class, and call itclass Planet, and we’ll have it as an empty class.

    >>> class Planet: pass    ...

How do you create instances of thePlanet class?

    >>> earth = Planet()

You cannot do anew Planet() - like in Java, for example.

    >>> earth = new Planet()      File "<stdin>", line 1        earth = new Planet()                         ^    SyntaxError: invalid syntax

We have just created an instance called earth. So what would happen now if we sayearth.name? The compiler says: ‘Planet object has no attributename’.

    >>> earth.name    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    AttributeError: 'Planet' object has no attribute 'name'

Let’s setearth.name = 'The Earth'. now if weprint(earth.name) what would happen?

    >>> earth.name = 'The Earth'    >>> earth.name    'The Earth'

It prints'The Earth'.

Now let’s create a new instance of thePlanet. Let’s call thisvenus. What happens if we dovenus.name? It does not have an attributename.

    >>> venus = Planet()    >>> venus.name    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    AttributeError: 'Planet' object has no attribute 'name'

An important thing to note is, each object has its own data, its own attributes. The fact we have set attributes onearth, does not mean the same attributes would exist onvenus.

What we need to do, is set the name forvenus as well. Now, You’d be able to usevenus.name.

    >>> venus.name = 'Venus'    >>> venus.name    'Venus'

The last thing we will be looking at, is the behavior. What would happen if we call a non-existent method?

    >>> venus.do_something()    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    AttributeError: 'Planet' object has no attribute 'do_something'

An interesting thing to note is that Python considersmethods, as well asdata, asattributes. In Python, you can add attributes dynamically. During the run-time of the program, you can add new data and methods, as attributes as well.

Step 07: A Constructor For TheMotorBike Class

How to set an initial state for an object when it is being created?

That’s where aconstructor comes into picture.

In this step, we will define a constructor for theMotorBikeclass.

How do you define a constructor for aMotorBike class? Once we decide to have a constructor, this cannot be an emptyclass anymore. We’ll removepass and define a method.

class MotorBike:    def __init__(self):        print("MotorBike instance created")honda = MotorBike()ducati = MotorBike()

A constructor is a special method. Syntax isdef __init__(self) .

For all the instance methods in a class, you need to pass in an attribute calledself. We’ll talk about a few puzzles related toself a little later. For now, it’s important that you follow this exact syntax.

When aMotorBike object is created, we might want to print a message. We can sayprint("MotorBike instance created").

MotorBike instance createdMotorBike instance created

'MotorBike instance created' is printed twice - once for each instance created,honda andducati.

Typically we do not use constructors to print statements. We use them to initialize data.

We want to set initial speed forhonda andducati.

honda = MotorBike(50)ducati = MotorBike(250)

We can addspeed as a parameter to the constructor.

Here’s the syntax -def __init__(self, speed)

class MotorBike:    def __init__(self, speed):        print(speed)honda = MotorBike(50)ducati = MotorBike(250)

Output

50250

How can we set the value into an instance of the object?

self.speed = speed whereself.speed represents aspeed attribute of theMotorBike instance. On the current object we would want to set an attribute calledspeed, with the value that is passed to this parameter.

class MotorBike:    def __init__(self, speed):        self.speed = speedhonda = MotorBike(50)ducati = MotorBike(250)print(honda.speed)print(ducati.speed)

If we print thespeed values ofhonda andducati, we get the following:honda.speed is50, andducati.speed is250.

Step 08: A Constructor ForBook Class

Let’s start with an exercise. Enhance the book class to have a constructor to enable create Book with a name -Book('Learning Python In 100 Steps')

class Book:    def __init__(self, name):        self.name = name    learning_python = Book('Learning Python In 100 Steps')    print(learning_python.name);

Step 09: Constructors - Puzzles

In this step, let’s look at a few puzzles related to constructors.

Let’s create thePlanetclass again, this time with a constructor. We’re not passing anything in here, and also sayingpass, so it’s an empty constructor.

    >>> class Planet:    ...    def __init__(): pass    ...

What would happen When we executePlanet()?

    >>> Planet()    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: __init__() takes 0 positional arguments but 1 was given

It says error! “init takes 0 positional arguments, but 1 was given”

What’s happening here?

All instance methods in a class need to haveself as a parameter.

Whenever you’re creating an object, we are calling the constructor and by default, Python would pass the current instance as an argument. Even though we are not passing any arguments in here, Python would pass one secretly. If we really want to actually create the right constructor, then we would need to haveself as the first parameter of the constructor method.

    >>> class Planet:    ...    def __init__(self): pass    ...    >>> Planet()    <__main__.Planet object at 0x10426bc88>

Now, in addition to the existing constructor, we want to create another constructor,def __init__(self, name), and let’s make it an empty method for now.

We’re creating two constructors, one with one parameter, and the other one with two parameters.

    >>> class Planet:    ...    def __init__(self, name): pass    ...    def __init__(self): pass    ...

Let’s createPlanet() andPlanet("Jupiter").

    >>> Planet()    <__main__.Planet object at 0x10426bdd8>    >>> Planet("Jupiter")    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: __init__() takes 1 positional argument but 2 were given

ForPlanet("Jupiter"), we got “TypeError:init() takes 1 positional argument but 2 were given”.

There are two constructors definitions but only the second one is available.

In Python, you can only have one constructor perclass.

When you define the class - whichever constructor comes last, is the one which is available.

Exercise : Try reversing the order of constructors and creating instances

What if I would want to be able to createPlanet instances usingPlanet() andPlanet("Jupiter")? Solution - default parameter values.

You can use,def __init__(self, name = 'Earth'). By default,Planet instance has a name of'Earth'.

    >>> class Planet:    ...    def __init__(self, name="Earth"): pass    ...    >>> Planet()    <__main__.Planet object at 0x10426beb8>    >>> Planet("Jupiter")    <__main__.Planet object at 0x10426bef0>

Let’s consider the code below: a real constructor

    >>> class Planet:    ...    def __init__(self, name="Earth"):    ...        self.speed = 10    ...        self.name = name    ...        self.distance_from_sun = 10000    ...

If we now create a new objectearth = Planet(), and executeearth.name, what would be the value?

    >>> earth = Planet()    >>> earth.name    'Earth'    >>> earth.speed    10    >>> earth.distance_from_sun    10000

Typically in Python, you will have your constructor define all the properties and set initial values to them.

Earlier we looked at naming variables.distance_from_sun is a variable. We used small case, and we use underscores to separate the words. We use the same convention, when we name methods as well.

However, when we name classes, typically CamelCase is used. That’s the reason why, when we named the class “MotorBike”.

The program would work even if the class is namedmotor_bike. But, what we are talking about are conventions followed across the world of Python programming.

Step 10: Class And Objects : Methods And Behavior

The state of an object changes with time.

Let’s say we want to increase thespeed ofhonda:honda.speed = honda.speed + 150. We can also do:ducati.speed += 25. We are modifying the state of the object, from outside the class.

In this step, we will talk about encapsulation, and how we can encapsulate this kind of behavior directly inside theclass.

Encapsulation is one of the most important object oriented principles, that says: all the data changes should be through methods, the behavior of aclass.

In the previous example, we are directly changing the value of an attribute. That is not considered to be a good practice, when it comes to object oriented programming. Ideally, the increase inspeed should happen through a method call, which is defined inside theMotorBikeclass.

Let’s look at how we could define a method, insideMotorBikeclass.

Note that this is at the same indentation level as the constructor.

Let’s name the method asincrease_speed(). For instance methods, we need to passself as one of the parameters.

def increase_speed(self, how_much):    self.speed += how_much

You can call this method on the instances, likehonda.increase_speed(150).

honda.increase_speed(150)ducati.increase_speed(25)

What if you want to decrease the speed? Let’s write a method calleddecrease_speed().

def decrease_speed(self, how_much):   self.speed -= how_much

Here is the full code for your reference:

class MotorBike:    def __init__(self, speed):        self.speed = speed #State    def increase_speed(self, how_much):        self.speed += how_much    def decrease_speed(self, how_much):        self.speed -= how_muchhonda = MotorBike(50)ducati = MotorBike(250)print(honda)print(ducati)honda.increase_speed(150)ducati.increase_speed(25)honda.decrease_speed(50)ducati.decrease_speed(25)honda.decrease_speed(350)print(honda.speed)print(ducati.speed)honda.speed = 150print(honda.speed)print(ducati.speed)

Step 11: Exercise -EnhancedBook Class With Copies

Let’s start with an exercise.

Enhance theBook class we created, to have a new property calledcopies, which says how many copies of the book are available. Have a method toincrease the copies, and one todecrease the copies as well. The other thing is to havecopies has a constructor argument.

In the constructor, we’ll set the default values ofcopies to0.

def __init__(self, name, copies=0):        self.name = name        self.copies = copies

We want to have a method calledincrease_copies(), which we define and call it aslearning_python.increase_copies().

def increase_copies(self, how_much):        self.copies += how_much

We also want a method to decrease thecopies, to be used aslearning_python.decrease_copies().

def decrease_copies(self, how_much):        self.copies -= how_much

This is how you can use all the methods we created earlier

learning_python = Book('Learning Python in 100 Steps', 100)learning_python.increase_copies(25)learning_python.decrease_copies(10)

Here is the code in full, for your perusal:

class Book:    def __init__(self, name, copies=0):        self.name = name        self.copies = copies    def increase_copies(self, how_much):        self.copies += how_much    def decrease_copies(self, how_much):        self.copies -= how_muchthe_art_of_computer_programming = Book('The Art of Computer Programming')learning_python = Book('Learning Python in 100 Steps', 100)learning_restful_services = Book('Learning RestFul Service in 50 Steps')print(the_art_of_computer_programming.name)print(learning_python.name)print(learning_restful_services.name)learning_python.increase_copies(25)learning_python.decrease_copies(10)learning_python.copies = 50print(learning_python.copies)

Step 12: Methods And Behavior - Puzzles Onself

In this step, let’s look at a few puzzles related to behavior, or the methods we create on aclass. Let’s get back to our favoritePlanetclass, and this time, let’s create a method.

Consider the steps below. What would be the result ofearth.revolve()?

    >>> class Planet:    ...    def revolve(): pass    ...    >>> earth = Planet()    >>> earth.revolve()

Here’s the result

    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: revolve() takes 0 positional arguments but 1 was given'

Rememberself. When we call a method on an instance of aclass, one parameter automatically gets passed, that’sself. We saw that when we were invoking the constructor. The same is the case with all the methods inside a class. So on all of the instance methods, you’d need to create a parameter calledself.

Let’s look at this code:

class Planet(object):    def rotate(self):        print("rotate")    def revolve(self):        print("revolve")

We want to create a method insidePlanet to call bothrotate andrevolve methods.

    def rotate_and_revolve(self):        rotate()        revolve()

Will this work? No.

You need to useself.

    def rotate_and_revolve(self):        self.rotate()        self.revolve()

You need to haveself to call a method on the same object -self.<specific-method>().

earth = Planet()earth.rotate_and_revolve()

Step 13: Advantages Of Encapsulation

An important question that a number of people ask about encapsulation, is do we really need it?

In this small step, We’ll give you an example of why we need encapsulation.

What we have with theMotorBikeclass, are methods to increase speed and decrease speed.

class MotorBike:    def __init__(self, speed):        self.speed = speed #State    def increase_speed(self, how_much):        self.speed += how_much    def decrease_speed(self, how_much):        self.speed -= how_muchhonda = MotorBike(50)honda.decrease_speed(350)print(honda.speed)

Consider above snippet. Shouldhonda.decrease_speed(350) be allowed? The initial speed ofhonda is50, and by saying decrease speed by350, it becomes-300. Negative Speed.

How do we prevent it?

To prevent it from happening, you can enhancedecrease_speed method.

    def decrease_speed(self, how_much):        if(self.speed-how_much>0):            self.speed -= how_much        else:            print("Get a life")

If you use behavior to change the state of the object, then you can add additional logic, such as validation, at a later point in time.

That’s one of the reasons why encapsulation is good.

Step 14: Everything Isobject In Python

In Python, everything is an object. What do we mean by ‘everything is an object’?

Let’s check type of some values. They all are instances of someclass.

    >>> 5    5    >>> type(5)    <class 'int'>    >>> type(True)    <class 'bool'>    >>> type('Hello')    <class 'str'>    >>> type(5.5)    <class 'float'>

You can call methods on these values as well.

    >>> 'Hello'.upper()    'HELLO'

This is possible because everything in Python is an object of some class!

The interesting part comes when we talk about methods. We have created methods earlier. Let’s saydef do_something(), an empty method.If you type indo_something() on the prompt, it says: ‘functiondo_something at’. a method is also an object.

    >>> def do_something(): pass    ...    >>> do_something    <function do_something at 0x104275488>

You can actually define a methoddo_something(), let’s sayprint('something') .do_something points to a new address.

    >>> def do_something():    ...    print("something")    ...    >>> do_something    <function do_something at 0x104275510>    >>> do_something()    something

Let’s trytest = do_something.

    >>> test = do_something    >>> test    <function do_something at 0x104275510>    >>> test()    something    >>>

test refers to the same function and you can run it usingtest().

This is possible, because even a function is an object in Python.

Summary

The most important thing to understand from this step, is in Python, everything is an object. The constant values that you create are objects of specific classes, and methods are objects as well.

Chapter 10 : Python Data Structures

Welcome to this section on data structures in Python. Here, we’ll discuss why we need data structures, and what are the important in-built data structures that Python provides.

Step 01: Why We Need Data Structures

In this step, let’s focus on the first question: “why do we need data structures?”

Suppose we have multiple values to store, like marks of different students in a course. Let’s say these are as follows:

  • first student:mark1 is45
  • second student:mark2 is54.(These are quite average students, maybe like me!)
  • and third student:mark3 is say,80. This guy is a very good student.

Let’s assume the professor asked: “What’s the sum, and what is the average?”.

    >>> mark1 = 45    >>> mark2 = 54    >>> mark3 = 80    >>> mark1 + mark2 + mark3    179    >>> (mark1 + mark2 + mark3)/3    59.666666666666664

The professor says: “There’s a new student”. What?

We would need to add a new student with this mark. Not just that, the formulas for calculating sum and average will also need to be changed.

    >>> mark4 = 43    >>> (mark1 + mark2 + mark3 + mark4)/3    74.0    >>> (mark1 + mark2 + mark3 + mark4)/4    55.5

When you have a list of marks, you’d rather store them in a specific data structure, that would allow easy manipulation. And that’s where the data structures in Python are useful.

Let’s look at a specific data structure in Python, called list, and how it helps us to solve the problem.

Creating data structures in Python is very simple. You don’t need to be even aware of whichclass our data structure belongs to. Let’s say we want to store the marks.

    >>> marks = [45, 54, 80]

We initializedmarks with these three values.

We want to find the sum and average.

    >>> sum(marks)    179    >>> sum(marks)/len(marks)    59.666666666666664

We get a new student.

    >>> marks.append(43)    >>> sum(marks)/len(marks)    55.5    >>> type(marks)    <class 'list'>

The code to find sum and average does not change.

Summary

In this step, we discussed the need for data structures in Python programs.

Step 02: Operations On List Data Structures

In this step, let’s look at thelist data structure.

How do you create a list structure?

All that do you need to do, is use the square brackets[] syntax, and put the elements you’d want to have in the list. So[23, 56, 67] is a list.

    >>> marks = [23,56,67]

Let’s look at the basic things you can do with a list.

We sawsum(marks). You can domax(marks),min(marks), andlen(marks). All these functions are very obvious, aren’t they!len() gives you how many elements are present,min() is the minimum,max() the maximum, andsum() returns the sum of the elements.

    >>> sum(marks)    146    >>> max(marks)    67    >>> min(marks)    23    >>> len(marks)    3

If you want to add more elements, you can domax.append(76).

    >>> marks.append(76)    >>> marks    [23, 56, 67, 76]

If you want to add element at a specific index, you can do that as well;marks.insert(...).

Let’s say you would want to insert60 in between56 and67. You would want to insert it at index2.

Indexes in a python list start at0, going through1,2, etc. Now if we domarks, you would see that60 is inserted in here.

    >>> marks.insert(2, 60)    >>> marks    [23, 56, 60, 67, 76]

You can remove a value frommarks as well. All you need to do is saymarks.remove(60).

    >>> marks.remove(60)

You can also check if a specific element is in the list or not. All that you need to do is,55 in marks, which returnsFalse.56 in marks returnsTrue .

    >>> 55 in marks    False    >>> 56 in marks    True

Also, you can search for a specific element; you domarks.index(...).

    >>> marks.index(67)    2    >>> marks    [23, 56, 67, 76]

Let’s trymarks.index(69), on a non-existing element69. What does it return? It returns an error, that says: “69 is not in list”.

    >>> marks.index(69)    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    ValueError: 69 is not in list

The next thing you can do, is loop around the elements in the list. You can usefor mark in marks: print(mark).

    >>> for mark in marks:    ...   print(mark)    ...    23    56    67    76

Summary

In this step, we looked some of the basic operations that you can perform on lists. We saw operations likesum(),max(),min(),len(), appending a new element, inserting a new element, removing a specific element, checking whether the element is in the list or not. We understood how to find a specific elements in the list, and how to loop around a list.

Step 03: An Exercise Withlist OfStudent

In this step, let’s look at an exercise using thelist we created earlier.

Create aStudentclass accepting a name, and a list of marks. We want to be able to perform all of these operations which are listed in here, on theStudentclass:

  • Find out how many number of marks are there,
  • Find out what the total sum of marks,
  • Determine the maximum mark,
  • Determine the minimum mark,
  • Calculate the average,
  • Add a new mark, as well as remove a mark, at a specific index.

Suppose the list is[23, 45, 56, 75], which are his marks in different subjects.

Let’s define a constructor:

def __init__(self, name, marks):        self.name = name        self.marks = marks

We need to define theget_number_of_marks() method, next up.

def get_number_of_marks(self):        return len(self.marks)

We can easily create the other methods as well.

def determine_maximum_mark(self):        return max(self.marks)def determine_minimum_mark(self):        return min(self.marks)

There is a statistic module in Python, which helps us with the average, but let’s keep things simple and directly use the methods we already have in here.

def determine_average(self):        return self.get_total_sum_of_marks()/self.get_number_of_marks()

The next one we would want to define isadd_number_of_marks(). How would you add a mark? We need a parameter, saynew_mark.

    def add_new_mark(self, new_mark):        self.marks.append(new_mark)

The last function we have, isremove_mark_at_index(5). The method which we looked at earlier,remove(), will only remove a specific value, and cannot be used to specify the element index.

    def remove_mark_at_index(self, index):        del self.marks[index]

The code to do what we need, would be:del self.marks[index] .

We’ll print out these values one by one to complete the program functionality.

One of the features you can make use of to print strings that have content split over distinct lines, is to use the triple quote""".

print(f"""Student[    number_of_marks-{number}    sum_of_marks-{sum_of_marks}    max-{maximum_mark}    min-{minimum_mark}    avg-{average} ] """)

What it allows us to do, is split the console output of the string into multiple lines.

Here is the code for your reference:

class Student:    def __init__(self, name, marks):        self.name = name        self.marks = marks    def get_number_of_marks(self):        return len(self.marks)    def get_total_sum_of_marks(self):        return sum(self.marks)    def determine_maximum_mark(self):        return max(self.marks)    def determine_minimum_mark(self):        return min(self.marks)    def determine_average(self):        return self.get_total_sum_of_marks()/self.get_number_of_marks()    def add_new_mark(self, new_mark):        self.marks.append(new_mark)    def remove_mark_at_index(self, index):        del self.marks[index]student = Student ("Ranga", [23, 45, 56, 75])number = student.get_number_of_marks()sum_of_marks = student.get_total_sum_of_marks()maximum_mark = student.determine_maximum_mark()minimum_mark = student.determine_minimum_mark()average = student.determine_average()student.add_new_mark(35)student.remove_mark_at_index(2)print(student.marks)print(f"""Student[    number_of_marks-{number}    sum_of_marks-{sum_of_marks}    max-{maximum_mark}    min-{minimum_mark}    avg-{average} ] """)

Output

[23, 45, 75, 35]Student[    number_of_marks-4    sum_of_marks-199    max-75    min-23    avg-49.75 ]

Summary

In this step, we explored an exercise on how to call methods on a list, to do basic arithmetic on its elements. We computed values such as number fo elements, sum, minimum, maximum, average. We also showed you how to add a new element to, or delete an existing element from, the list.

Step 04: Puzzles Withlist Of Strings

In this step, we will look at a few puzzles to help us understand lists even better.

Let’s create a simple list.

    >>> animals = ['Cat', 'Dog','Elephant']    >>> len(animals)    3

What wouldsum(animals) give?

    >>> sum(animals)    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: unsupported operand type(s) for +: 'int' and 'str'

Error, obviously! Becausesum() is not defined on astr.

Here are other basic list operations onstr.

    >>> animals.append('Fish')    >>> animals    ['Cat', 'Dog', 'Elephant', 'Fish']    >>> animals.remove('Dog')    >>> animals    ['Cat', 'Elephant', 'Fish']

You can use index to access elements from list.

animals[2] will print'Fish' , much to your surprise!

This is exactly the kind of the array-indexing, we use in C or Java programming.animals[1] returns'Elephant', andanimals[0] gives you'Cat' . But make sure you actually use an accurate index, because if you do things likeanimals[4], the compiler would throw anIndexError.

    >>> animals    ['Cat', 'Elephant', 'Fish']    >>> animals[2]    'Fish'    >>> animals[1]    'Elephant'    >>> animals[0]    'Cat'    >>> animals[4]    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    IndexError: list index out of range

Let’s look at difference betweenanimals.remove() anddel.

animals.remove() would remove the specified value from the list. When we dodel animals[2], we are specifying theindex.

If you dodel animals[2], the list contents goes down to['Cat', 'Elephant']. The last element which was at index 2,'Fish', got deleted.

    >>> del animals[2]    >>> animals    ['Cat', 'Elephant']

Let’s look at the difference betweenappend() andextend().

If you invoke theextend() method with'Fish', what would happen?

    >>> animals.extend('Fish')    >>> animals    ['Cat', 'Elephant', 'F', 'i', 's', 'h']

You can see that individual character symbols are being added in. So,'F', 'i', 's', 'h' are added in.

If you doanimals.append('Fish'), it would add an element called'Fish' to the list.

    >>> animals.append('Fish')    >>> animals    ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish']

animals.extend() is actually used to add a list of values. You can use['Giraffe', 'Horse'] (if we got the spelling right!) , You can see that the elements are added in.

    >>> animals.extend(['Giraffe', 'Horse'])    >>> animals    ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish', 'Giraffe', 'Horse']

There is another way you can actually do theextend().animals = animals + ['Jackal', 'Kangaroo'].

    >>> animals = animals + ['Jackal','Kangaroo']    >>> animals    ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish', 'Giraffe', 'Horse', 'Jackal',    'Kangaroo']

With a list, you can also use+= !animals += ['Lion', 'Monkey'] !

    >>> animals += ['Lion','Monkey']    >>> animals    ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish', 'Giraffe', 'Horse', 'Jackal',    'Kangaroo', 'Lion', 'Monkey']

In Python, is there is no restriction on what you can have in a list.

You can easily sayanimals.append(10), andanimals would have now include a value of10 . So there is no type restrictions on thelist.

    >>> animals.append(10)    >>> animals    ['Cat', 'Elephant', 'F', 'i', 's', 'h', 'Fish', 'Giraffe', 'Horse', 'Jackal',        'Kangaroo', 'Lion', 'Monkey', 10]

Step 05: List Slicing

In this step, we look at one of my favorite features in Python. It’s calledList slicing.

It’s a really powerful feature, which can help you to break lists into different kinds of values, without a lot of code.

Let’s look at what it is, with a simple example, of creating a list callednumbers. It has strings from'Zero' to'Nine'.

    >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']

How many elements does it have?len(numbers), or10, right? You want to find out what is the second element, or what is the element atindex2.numbers[2] gives you'Two'. The same index you used,2, can be used to get a subset of elements from this list.

    >>> len(numbers)    10    >>> numbers[2]    'Two'

How do we get elements from index2, to6?

Welcome List Slicing?

Syntax is very simple. Let’s trynumbers[2:6]

    >>> numbers[2:6]    ['Two', 'Three', 'Four', 'Five']

index6 is exclusive. We should donumbers[2:7]

There are multiple ways in which you can use lists slicing.

numbers[:6] doesn’t have a start index.0 is default.

    >>> numbers[:6]    ['Zero', 'One', 'Two', 'Three', 'Four', 'Five']

numbers[3:] doesn’t have end index. default is up to the end of the list.

    >>> numbers[3:]    ['Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']

Let’s make it even more powerful. What we can even do, is specify we want to start from index1, going up to index8, but only want to get every second element.

    >>> numbers[1:8:2]    ['One', 'Three', 'Five', 'Seven']

How to get every third element?

    >>> numbers[1:8:3]    ['One', 'Four', 'Seven']

numbers[::3]. You get'Zero'.'Three','Six','Nine'. Isn’t this awesome!

    >>> numbers[::3]    ['Zero', 'Three', 'Six', 'Nine']

You can also use slicing to access the list in reverse order.

Sonumbers[::-1] will return the list elements, but this time in the reverse order.

    >>> numbers[::-1]    ['Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three', 'Two', 'One', 'Zero']

When you saynumbers[::-3], it starts from the end of the list, and fetches every third element from the end, backwards.

    >>> numbers[::-3]    ['Nine', 'Six', 'Three', 'Zero']

A lot of programmers from other languages struggle with slicing, because when they first see this syntax::, they go mad!

What is it doing? What’s the:? What is it doing all over the place?[1:8:2]… Oh My God!

Python seems like a weird language to them.

Once you understand slicing well, then it makes your code much simpler.

You can use slicing to delete elements from a list.

Let’s say you want to delete all the elements starting from index3. You could dodel numbers[3:].

    >>> del numbers[3:]    >>> numbers    ['Zero', 'One', 'Two']

Let’s re-initialize the list, and try to delete numbers in the middle of the list, starting from index5 to7. The thing to remember, is7 here is exclusive.

    >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']    >>> del numbers[5:7]

Another important thing that you can do with slicing, is replace the values in the list.

    >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']    >>> numbers[3:7] = [3,4,5,6]    >>> numbers    ['Zero', 'One', 'Two', 3, 4, 5, 6, 'Seven', 'Eight', 'Nine']

We’ve replaced values'Three','Four','Five','Six' with3, 4, 5, 6.

Summary

In this step, we looked at how you can use slicing to retrieve values from a list, delete values from a list, and update values in a list. When you’re coming from other languages to Python, slicing is one of the important things that you need to understand very well.

Step 06:list - Sorting, Looping And Reversing

We have been talking about different features of lists, in the last few steps. And there are still a few more steps to come.

In this step, let’s focus on a few simple pieces of code tosort, toreverse, and also a few other tips related tolooping around a list, using anindex.

Let’s get started with initializingnumbers again. We allownumbers to have values from'Zero' to'Nine', so we have something to play with.

    >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']    >>> numbers.reverse()

The first thing we look at, is reversing the list, by doingnumbers.reverse(). It reverses the existing list.numbers.reverse() is anin-place reverse. That means, it is modifying the existing list directly.

    >>> numbers    ['Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three', 'Two', 'One', 'Zero']    >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']

However, if you’d want to loop through the list in a reverse direction, this is not necessary.

Let’s re-initializenumbers again, so we have the originallist back. If you don’t want to do an in-place reverse, but only access the elements in reverse order, then you can usereversed().reversed(numbers) would actually give you aniterator, that helps you access the elements in a reverse direction.

    >>> numbers    ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']    >>> reversed(numbers)    <list_reverseiterator object at 0x109560ba8>    >>> for number in reversed(numbers):    ...    print(number)    ...    Nine    Eight    Seven    Six    Five    Four    Three    Two    One    Zero

What is the difference betweenreverse() andreversed()?reverse() does an in-place reverse. So, the original list gets reversed. However, when want to access the elements in reverse without changing them, we can usereversed().

Let’s say we want to sort the list.numbers.sort() sorts strings in alphabetical order.

sort() does an in-place sort.

    >>> numbers    ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']    >>> numbers.sort()    >>> numbers    ['Eight', 'Five', 'Four', 'Nine', 'One', 'Seven', 'Six', 'Three', 'Two', 'Zero']

Let’s initializenumbers again. If you don’t want to do an in place sort, rather just access elements in a sorted order, there is something else for it. What you can do, is usesorted().

Iterating is simple:for number in sorted(numbers): print number.

    >>> numbers = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']    >>> for number in sorted(numbers):    ...   print(number)    ...    Eight    Five    Four    Nine    One    Seven    Six    Three    Two    Zero

Another interesting feature insorted(), is you can pass in a key to use.

We are passing inlen , length of the string, or the number of characters present in it. We will get the elements in the increasing order of their length.

    >>> numbers    ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']    >>> for number in sorted(numbers, key=len):    ...   print(number)    ...    One    Two    Six    Zero    Four    Five    Nine    Three    Seven    Eight

Another interesting feature of thesorted() method isreverse=True.

What would happen?

    >>> for number in sorted(numbers, key=len, reverse=True):    ...   print(number)    ...    Three    Seven    Eight    Zero    Four    Five    Nine    One    Two    Six

You are right,it starts printing elements in the reverse order of the length.

These are really powerful things that you can do with a key in here. You can also use aLambda Expression. We will look at it, when we talk about functional programming.

Instead ofsorted(), we can usenumbers.sort() function.

    >>> numbers.sort(key=len)    >>> numbers    ['One', 'Two', 'Six', 'Zero', 'Four', 'Five', 'Nine', 'Three', 'Seven', 'Eight']    >>> numbers.sort(key=len, reverse=True)    >>> numbers    ['Three', 'Seven', 'Eight', 'Zero', 'Four', 'Five', 'Nine', 'One', 'Two', 'Six']

Summary

In this step, we focused on two important features.sort() versussorted(), andreverse() versusreversed(). We saw that the basic methods on the list directly does an in-place change. If you callnumbers.sort() ornumbers.reverse(), then the original list get affected. However,sorted() andreversed() are returning iterators, which do not change the original list. We also looked at the fact we can pass in akey to the sorted(), indicating how we would want to sort it, what is the criteria based on how we would want to sort. And we can also pass in a parameter calledreverse, to indicate we would want to sort in reverse order. There’s a lot of stuff we learned in this specific step.

Step 07: Usinglist As Stack And Queue

In this step, we look at the features which a list provides, where it can act as astack, and aqueue.

First of all, what is a stack, and what is a queue?

Astack is typically called aLast In, First Out data structure. If you insert elements in the order123 and4, then to take out the elements from the stack, the first one which come out is4, the next one is3, Next one is2, and next to one is1. So it’s called Last In, First Out.

AQueue, as we all know, isfirst in, first out. If you insert elements in this order, to take out an element of the queue, you would get1 out first.

How can we use a list as stack, or a queue?

Let’s start with the stack.

Let’s create a simple list.

    >>> numbers = []    >>> numbers.append(1)    >>> numbers.append(2)    >>> numbers.append(3)    >>> numbers.append(4)

The way you can use a list as a stack is by sayingnumbers.pop().

    >>> numbers.pop()    4

pop() method retrieves the last inserted element as well as deletes it. If you look at numbers right now,4 is removed from the list.

You can look at the result of multiplepop operations below.

    >>> numbers    [1, 2, 3]    >>> numbers.pop()    3    >>> numbers    [1, 2]    >>> numbers.append(10)    >>> numbers.pop()    10    >>> numbers    [1, 2]

How do we use it as a queue?

Let’s create the list again.

    >>> numbers = []    >>> numbers.append(1)    >>> numbers.append(2)    >>> numbers.append(3)    >>> numbers.append(4)

numbers.pop(0) would take the first inserted element out of the list. If you look atnumbers, it would only have[2, 3, 4].

    >>> numbers.pop(0)    1    >>> numbers    [2, 3, 4]

Look at few more operations below:

    >>> numbers.pop(0)    2    >>> numbers    [3, 4]    >>> numbers.append(10)    >>> numbers.pop(0)    3    >>> numbers.pop(0)    4    >>> numbers.pop(0)    10    >>> numbers    []

Step 09:list With a customclass

In this step, let’s look at using instances of custom classes inside a list. Let’s create aclass Country.

from operator import attrgetterclass Country:    def __init__(self, name, population, area):        self.name = name        self.population = population        self.area = area    def __repr__(self):        return repr((self.name,self.population,self.area))countries = [Country('India',1200,100),             Country('China', 1400, 200),             Country('USA', 120, 300)]

Most of the class is self explanatory.

__repr__(self) method provides the string representation of a class. When you print an object of this class, the return value from this method is printed.

Some of the operations you can perform are shown below:

countries.append(Country('Russia',80,900))print(countries[0])print(countries[0:2])print(countries[2:])

Output

('India', 1200, 100)[('India', 1200, 100), ('China', 1400, 200)][('USA', 120, 300), ('Russia', 80, 900)]

Summary

In this step, we looked at how to create lists using custom classes in Python. In the next step, we would look at how to sort, and manipulate this list.

Step 10:list With a customclass - Part 2

In the previous step, we created aCountryclass, and we created a list of countries. In this step, Let’s focus on trying to find the:

  • country with the maximum population

  • country with the maximum area

  • country with the minimum area

  • sorted list of countries, in a specific order

    from operator import attrgetter

    class Country: definit(self, name, population, area): self.name = name self.population = population self.area = area defrepr(self): return repr((self.name,self.population,self.area))

    countries = [Country(‘India’,1200,100), Country(‘China’, 1400, 200), Country(‘USA’, 120, 300)]

    countries.append(Country(‘Russia’,80,900))

Now what we want to do is sort countries. Can we do this,countries.sort()? You get an error

Traceback (most recent call last):  File "main.py", line 15, in <module>    countries.sort()TypeError: '<' not supported between instances of 'Country' and 'Country'

If the values were numbers, or strings, then Python knows how to compare them. The values in this list belong to a user-definedclass. How do we help Python compare oneCountry with another?

Let’s say we want to sort bypopulation.

You can do it bycountries.sort(key=attrgetter('population')).attrgetter method needs to be imported in -from operator import attrgetter() .

Output

[('Russia', 80, 900), ('USA', 120, 300), ('India', 1200, 100), ('China', 1400, 200)]

Countries are sorted in the increasing order of population.

How can you sort them in the reverse order, in the decreasing order?

countries.sort(key=attrgetter('population'), reverse=True)

Output

[('China', 1400, 200), ('India', 1200, 100), ('USA', 120, 300), ('Russia', 80, 900)]

We can usemax(),min() and all the other stuff using the same approach.

>>> print(max(countries, key=attrgetter('population')))('China', 1400, 200)>>> print(min(countries, key=attrgetter('population')))('Russia', 80, 900)>>> print(min(countries, key=attrgetter('area')))('India', 1200, 100)>>> print(max(countries, key=attrgetter('area')))('Russia', 80, 900)

Here’s the complete program we wrote during this step.

from operator import attrgetterclass Country:    def __init__(self, name, population, area):        self.name = name        self.population = population        self.area = area    def __repr__(self):        return repr((self.name,self.population,self.area))countries = [Country('India',1200,100),             Country('China', 1400, 200),             Country('USA', 120, 300)]countries.append(Country('Russia',80,900))countries.sort(key=attrgetter('population'), reverse=True)print(max(countries, key=attrgetter('population')))print(min(countries, key=attrgetter('population')))print(min(countries, key=attrgetter('area')))print(max(countries, key=attrgetter('area')))print(countries)

Step 11:list Comprehension

We know we have been playing with lists a lot, and the final thing we talk about is list comprehension.

Why do we need list comprehension? Great question.

Let’s get back to thenumbers example.

We want filter elements that have length4.

Let’s look at the traditional approach:

    >>> numbers = ['Zero', 'One','Two','Three','Four','Five','Six','Seven', 'Eight','Nine']    >>> numbers_length_four=[]    >>> for number in numbers:    ...    if len(number)== 4:    ...      numbers_length_four.append(number)    ...

Lot of code. Isn’t it?

List comprehension allows you to do this in a much simpler way.

The basic syntax isnumbers_length_four = [number for number in numbers].

    >>> numbers_length_four = [ number for number in numbers  ]    >>> numbers_length_four    ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']

We are printing complete list again.

Let’s try something else, say[len(number) for number in numbers].

    >>> numbers_length_four = [ len(number) for number in numbers  ]    >>> numbers_length_four    [4, 3, 3, 5, 4, 4, 3, 5, 5, 4]

Interesting. We created a list with lengths of each element.

Let’s get back to the problem we wanted to solve, where we only wanted to get the ones of length 4.

We can add anif condition between the[...]:[number for numbers in numbers if len(number) == 4].

    >>> numbers_length_four = [ number for number in numbers if len(number)==4 ]    >>> numbers_length_four    ['Zero', 'Four', 'Five', 'Nine']

Isn’t that cool? You can see thatnumbers_length_four contains'Zero','Four','Five','Nine'.

Now let’s create another list,values = [3, 6, 9, 1, 4, 15, ...], which can have duplicates as well. so it might have6 twice, even thrice. You want to create another list namedvalues_even filtering only the even numbers.

values_even = [value for value in values if value %2 == 0] will do the job for us.

    >>> values = [3, 6, 9, 1, 4, 15, 6, 3]    >>> values_even = [ value for value in values if value%2==0]    >>> values_even    [6, 4, 6]

To extract only the odd numbers instead, use the conditionvalue % 2 == 1.

    >>> values_odd = [ value for value in values if value%2==1]    >>> values_odd    [3, 9, 1, 15, 3]

Step 12: Introduction Toset

Alist can contain duplicates. So if we create alistnumbers = [1, 2, 3, 2, 1], it is a validlist. A list is more based on the index, or position of elements. So innumbers, atindex[0] is element 1, the element atindex[1] is2,and so on. Alist is apositional data structure. You can add things at the end, or anywhere in-between.

A set, on the other hand, does not contain duplicates.

You can create a set from a listnumbers, byset(numbers).

    >>> numbers = [1,2,3,2,1]    >>> numbers    [1, 2, 3, 2, 1]    >>> numbers_set = set(numbers)    >>> numbers_set    {1, 2, 3}

You can see that thenumbers_set is printed using{,} as delimiters. It does not have duplicates.

You can add a number to a set. Let’s add an element already present in the set. No change. No duplicates.

    >>> numbers_set.add(3)    >>> numbers_set    {1, 2, 3}

If we add a fresh element , it would be added to the set.

    >>> numbers_set.add(4)    >>> numbers_set    {1, 2, 3, 4}    >>> numbers_set.add(0)    >>> numbers_set    {0, 1, 2, 3, 4}

When you donumbers_set.remove(0),0 is deleted.

    >>> numbers_set.remove(0)    >>> numbers_set    {1, 2, 3, 4}

Set does not support access using index. So you cannot saynumbers_set[0] and try to access the first element in the set.

    >>> numbers_set[0]    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: 'set' object does not support indexing

You can check if an element is in a set, or not. You can use1 in numbers_set, to get a boolean result.

    >>> 1 in numbers_set    True    >>> 5 in numbers_set    False

You can do aggregate operations -min,max,sum andlen.

    >>> min(numbers_set)    1    >>> max(numbers_set)    4    >>> sum(numbers_set)    10    >>> len(numbers_set)    4

In a set, you can perform operations likeintersection, union and disjoint.

Let’s create a new setnumbers_1_to_5_set, to hold the set{1, 2, 3, 4, 5}. We want to have a setnumbers_4_to_10_set to have the set{4, 5, 6, 7, 8, 9, 10}.

    >>> numbers_1_to_5_set = set(range(1,6))    >>> numbers_1_to_5_set    {1, 2, 3, 4, 5}    >>> numbers_4_to_10_set = set(range(4,11))    >>> numbers_4_to_10_set    {4, 5, 6, 7, 8, 9, 10}

Now, if you donumbers_1_to_5_set + numbers_4_to_10_set, what would happen?

    >>> numbers_1_to_5_set + numbers_4_to_10_set    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: unsupported operand type(s) for +: 'set' and 'set'

It says ‘unsupported operation’.

Union can be done using|. The union of two sets combines the set elements, and finds the unique ones among them. So it returns{1, 2, 3, 4, 5, 6, 9, 10}.

    >>> numbers_1_to_5_set | numbers_4_to_10_set    {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Intersection is doing using the ‘&’ operator. It returns elements which are present in both these sets,{4, 5}.

    >>> numbers_1_to_5_set & numbers_4_to_10_set    {4, 5}

The other operation you can do is subtraction represented by-. This would return the elements in first set, but not present in the second set.

    >>> numbers_1_to_5_set - numbers_4_to_10_set    {1, 2, 3}    >>> numbers_4_to_10_set - numbers_1_to_5_set    {6, 7, 8, 9, 10}

Step 13: Introduction Todict

In this step, let’s look at dictionary - represented by theclassdict. Dictionary represent key-value pairs.

Let’s say we have a sentence, and we would want to find out how many times each character occurred in that sentence. In those kind of situations, you can use a dictionary. Suppose'a' occurred10 times,'b' occurred15 times,'c' occurred’25 times. If you are familiar with Java, then this is like aHashMap, where it stores a key and its value. The key can be any object, and the value can be any object as well.

Let’s create a dictionary. Syntax isoccurrances = dict(a=5, b=6, c=8).

    >>> occurances = dict(a=5,b=6,c=8)    >>> occurances    {'a': 5, 'b': 6, 'c': 8}    >>> type(occurances)    <class 'dict'>

A dictionary allows us to access values, using a key, something likeoccurrences['d'] = 15.

    >>> occurances['d'] = 15    >>> occurances    {'a': 5, 'b': 6, 'c': 8, 'd': 15}    >>> occurances['d'] = 10    >>> occurances    {'a': 5, 'b': 6, 'c': 8, 'd': 10}

In a list, the index used was a number. However, in a dictionary, the index can be anything. It can be any object, and over here, we are using a string.

You can also print the value ofoccurrences['d'].

    >>> occurances['d']    10

You should be cautious when using the approach. If the key does not exist, you get aKeyError.

    >>> occurances['e']    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    KeyError: 'e'

A better way, without throwing an exception, would beget().

    >>> occurances.get('d')    10    >>> occurances.get('e')

You can useoccurrances.get('e', 10) to provide a default value. If keye is not present, it returns10 back.

    >>> occurances.get('e', 10)    10

There are a number of useful methods which are present in a dictionary. Let’s look at some of them.

    >>> occurances    {'a': 5, 'b': 6, 'c': 8, 'd': 10}    >>> occurances.keys()    dict_keys(['a', 'b', 'c', 'd'])    >>> occurances.values()    dict_values([5, 6, 8, 10])

occurrances.items() returns the key-value pairs, in the format of atuple. Each tuple has key as the first element, and value as the second element. You can loop around all the items, by using this way.

    >>> occurances.items()    dict_items([('a', 5), ('b', 6), ('c', 8), ('d', 10)])    >>> for (key,value) in occurances.items():    ...    print(f"{key} {value}")    ...    a 5    b 6    c 8    d 10

You can also delete a specific key -del occurances['a'].

    >>> occurances    {'a': 0, 'b': 6, 'c': 8, 'd': 10}    >>> del occurances['a']    >>> occurances    {'b': 6, 'c': 8, 'd': 10}

Step 14: An Exercise Withdict

In this step, let’s do a simple exercise with a dictionary. We have a simple string for you here:

"This is an awesome question. This has never happened before This is your first time learning Python. Hopefully this has never happened before."

With this string, we want to do two things:

  • Compute how many times has each word is present in the string.
  • Find out how many times each character is present in this string.

Solution 1

str = "This is an awesome occasion. This has never happened before."# key:valuechar_occurances = {} #[]for char in str:    char_occurances[char] = char_occurances.get(char, 0) + 1print(char_occurances)

Output

{'T': 2, 'h': 4, 'i': 4, 's': 6, ' ': 9, 'a': 5, 'n': 4, 'w': 1, 'e': 8, 'o': 4, 'm': 1, 'c': 2, '.': 2, 'v': 1, 'r': 2, 'p': 2, 'd': 1, 'b': 1, 'f': 1}

What this does is

  • It checks thechar_occurrances to see how many timeschar is present.
  • If it’s not present, then return0.
  • The first time you findchar, the value which would be set to0 + 1, or1.
  • The second time you’ll find the character, you’ll have1 in the dictionary, add1 to it, and store and return a2.

Solution 2

str = "This is an awesome occasion. This has never happened before."word_occurances = {} #[]for word in str.split():    word_occurances[word] = word_occurances.get(word, 0) + 1print(word_occurances)

Output

{'This': 2, 'is': 1, 'an': 1, 'awesome': 1, 'occasion.': 1, 'has': 1, 'never': 1, 'happened': 1, 'before.': 1}

Step 15: Puzzles With Data Structures

In this step on data structures, we look at a number of puzzles related to set, lists and dictionary.

We want to create a simple list which has the squares of the first10 numbers. How do you do that? The simplest way to do that in Python, would be to use list comprehension.

    >>> squares_first_ten_numbers = [  i*i for i in range(1,11) ]    >>> type(squares_first_ten_numbers)    <class 'list'>

We would want to create a set, with the same values. We can use set comprehension. Use braces{} instead of square brackets[] -squares_first_ten_numbers_set = { i*i for i in range(1,11) }. If you do atype(squares_first_ten_numbers_set), you get a'set'.

    >>> squares_first_ten_numbers_set = set(squares_of_first_10_numbers)    >>> squares_first_ten_numbers_set = { i*i for i in range(1,11)}    >>> type(squares_first_ten_numbers_set)    <class 'set'>

Square brackets[] denotelist. Braces{}, denotesset or adict.

To create a dictionary, you need a key and a value pair -{ i : i*i for i in range(1,11)}.i : i*i iskey : value pair.

    >>> squares_first_ten_numbers_dict = { i:i*i for i in range(1,11)}    >>> type(squares_first_ten_numbers_dict)    <class 'dict'>    >>> squares_first_ten_numbers_dict    {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

type([]) islist andtype({}) isdict. If you want to create an empty set, you can use theset() function.

    >>> type([])    <class 'list'>    >>> type({})    <class 'dict'>    >>> type(set())    <class 'set'>

The other way you can create a set, by actually having an element -type({1}).

    >>> type({1})    <class 'set'>

However if you actually make it a key-value pair… ? It would be of type ‘dict’.

    >>> type({'A':5})    <class 'dict'>

You can createtuple by using(), We will look attuple in the next step.

    >>> type(())    <class 'tuple'>    >>> type((1,2,3))    <class 'tuple'>    >>>

Summary

These are all pretty nuanced but these are powerful things you would need to understand to make complete use of the power of Python. I think understanding all the things we are discussing in this specific step, are key to making great use of all Python data structures.

() represents tuples,[] represents a list, and{} might be a set or a dictionary. If{} does not contain anything it’s a dictionary. If the{] contain a set of elements, it’s a set. If the{} contains key-value pairs, then it’s a dictionary.Make sure that you understand every word of this.

Step 16: Introducingtuple

In this quick tip, we would be looking at interesting data type in Python, called thetuple. Now what does that mean, how do you use it, and how is it different from a list?

Let’s look at it right now. Let’s define a method calledcreate_ranga(), and let’s return'Ranga', followed by the date of birth1981, as well as the country,'India'.

Is this really allowed? Of course!

    >>> def create_ranga():    ...    return 'Ranga',1981,'India'

We are returning multiple values from above method.

Let’s call this method:ranga = create_ranga().

    >>> ranga = create_ranga()

What’s the return type? It’s of typetuple.

    >>> type(ranga)    <class 'tuple'>    >>> ranga    ('Ranga', 1981, 'India')

Atuple is nothing but a sequence of values, separated by a comma.

Let’s say you want to takeranga, and assign values to three different variables.name, year, country = ranga.

    >>> name, year, country = ranga    >>> name    'Ranga'    >>> year    1981    >>> country    'India'

name, year, country = ranga is calleddestructing. We are assigning the values from the tuple, to three different variables.

On the tuple, you can do a number of operations. For example, you can do alen(ranga), which returns3. You can use an index to retrieve the values of a tuple, as inranga[1], andranga[2].

    >>> len(ranga)    3    >>> ranga[0]    'Ranga'    >>> ranga[1]    1981    >>> ranga[2]    'India'

Now let’s try and change a value. Supposeranga was not born in1981. We would want to reduce his age.

    >>> ranga[1] = 1991    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: 'tuple' object does not support item assignment

It does not allow you to do that, because a tuple is by definition, immutable. The values in a tuple cannot change. For that reason, in certain situations, tuples might be more efficient to use than a list.

Typically, a list is a collection of different values or objects of same type - a list of persons, a list of numbers etc. Typically, a tuple is a set of related attributes - details of a person.

A tuple typically stores details about a specific thing and the list stores a number of things.

Let’s look at a few simple tips regarding usage of tuples.

You an create a tuple by usingperson = ('Ranga', 1981, 'India') orperson = 'Ranga', 5, 'India'. And once you have it, you can destruct it.

    >>> person = ('Ranga', 5, 'India')    >>> person = 'Ranga', 5, 'India'    >>> type(person)    <class 'tuple'>    >>> name, age, country = person

What would happen, if we have only two variables on the left hand side? Obviously, it would throw an error!

    >>> name, age = person    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    ValueError: too many values to unpack (expected 2)

Tuples make swapping very easy.

Let’s have two valuesx = 0,y = 1. You want to swap values.

    >>> x = 0    >>> y = 1

Swap is easy.

    >>> x, y = 0, 1    >>> x, y = y, x    >>> x    1    >>> y    0

R.H.S ofx, y = y, x is a tuple(y, x) and it is destructed to the L.H.S variables.

We could’ve done both assignments together.

    >>> x, y = 0, 1

An interesting thing is related to how do you create a tuple with one element. Considerx = (0), what would happen? What would be the type ofx? It’s ofclassint.

    >>> x = (0)    >>> type(x)    <class 'int'>

How do you create a tuple with just one value? The way you can do that, is by putting a comma. So you can dox = 1,, and it is actually a tuple .

    >>> x = (0,)    >>> x = 1,    >>> type(x)    <class 'tuple'>

It’s typically an interesting piece of code, for people who come from other languages. They would be worrying:Oh!! what does it really mean? Time for Python programmers to have some fun!

Chapter 11 - Object Oriented Programming Revisited

Welcome to this section, a continuation on Object-Oriented Programming. In an earlier section, we understood the basics of object oriented programming.

In this section, we will focus on more advanced stuff related to object oriented programming, such as:

  • Object composition
  • Inheritance
  • Abstract classes, and class design

Recommended Video

Step 01: OOP Basics Revised

In this first step, we will revise the concepts we learned earlier:class,object,state andbehavior. As We understood earlier, a class is a template. TheMotorBike class hence is atemplate, for all the objects of its kind.honda is an object or instance, and so isducati.honda has a specific state at this point: it has a value of50 for its speed. The state of an object is represented by the values of its properties, or member members.speed is a property and a member variable. We change the state of an object through the behavior of an object. Here we haveincrease_speed() anddecrease_speed() as the methods to change thespeed of the object. We saw that the state of the object can change during the lifetime of the program.

Step 02: Designing AFan Class

In the previous step, we talked about a few important questions that you need to ask when you are talking about your classes:

  • What is the state? That means, what are the member variables you need to have.
  • How do you want to allow creation of a specific object? That is, what is the kind of constructor that you want to allow?
  • What is what is the behavior you want? That would be the member method definitions.

Let’s consider the example of a ceiling fan. For thisFanclass, you can think about the different elements that represent the state of a specificFan object. You can think about how you want to allow construction of aFan object, and how to define its behavior. In other words, what kind of changes you want to allow in the state of aFan class.

The state we’re looking at ismake (manufacturer),radius (wing radius),color,isOn (abool, representing whether it’s on), andspeed. It’s now time to represent theFan class in our code. Above are the different things that make up the state of aFan.

An important thing you need to take care of, when you’re designing the behavior of a class, is to think about the consumers. Think about who’s going to use your class, and how they would like to see it. When we talk about a fan, the typical behavior is:

  • Switch it on
  • Switch it off
  • Increase the speed
  • Decrease the speed

This is the typical behavior that might be expected by consumers, who would use our class. Even when you’re not really designing classes to be consumed by others, we would recommend you to think about what kind of behavior you would want, and get an outside in perspective.

All that theory aside, Python is all about getting things done, as fast as possible. Let’s try and keep this analysis to a bare minimum. Let’s get down to business.

Let’s create the constructor first.

When we’re creating a fan all we will need to decide is the make, radius and the color. Therefore, we want to pass inmake,radius,color to this constructor.

class Fan:    def __init__(self, make, radius, color):        self.make = make        self.radius = radius        self.color = color        self.speed = 0        self.is_on = False

Let’s define the representation method so that we can see the content of the object.

    def __repr__(self):        return repr((self.make,self.radius,self.color,self.speed,self.is_on))

When we run this code:

fan = Fan('Manufacturer 1', 5, 'Green')print(fan)

We get('Manufacturer 1', 5, 'Green', 0, False)

Now let’s go ahead and represent the behavior we wanted to have, for this specific class.

switch_on starts the fan and gives a initialspeed value.

    def switch_on(self):        self.is_on = True        self.speed = 3

switch_off stops the fan and makesspeed0.

    def switch_off(self):        self.is_on = False        self.speed = 0

Here is the full code so far, for your reference:

class Fan:    def __init__(self, make, radius, color):        self.make = make        self.radius = radius        self.color = color        self.speed = 0        self.is_on = False    def __repr__(self):        return repr((self.make,self.radius,self.color,self.speed,self.is_on))    def switch_on(self):        self.is_on = True        self.speed = 3    def switch_off(self):        self.is_on = False        self.speed = 0fan = Fan('Manufacturer 1', 5, 'Green')fan.switch_on()print(fan)fan.switch_off()print(fan)

We leave it as an exercise, to implement theincreased_speed() and thedecrease_speed(). It should be very easy. All that you need to do, is and given the speed, increment and decrement the speed variables.

Step 03: Object Composition -Book AndReviews

In this step, we want to do a simple exercise on object composition.

First of all, what is object composition?

Up until now, we stored simple elements inside our object, soid is a number,name is a string,author is a string. In a class, you can use instances of other classes as well. Earlier we used instances of the predefined classes in Python.

In this step, we’ll create a custom class calledReview. In theBook class, we will have alist ofReviews. This is calledobject composition.

Let’s look at the solution.

Let’s have a constructor, as in:def __init__(self, id, name, author). Let’s define arepr method as well.

class Book(object):    def __init__(self, id, name, author):        self.id = id        self.name = name        self.author = author        self.reviews = []    def __repr__(self):        return repr((self.id,self.name,self.author,self.reviews))

Let’s create aninstance of theBook, read the book as well. You’re able to see the content of the book, but the reviews are still empty.

book = Book(123, 'Object Oriented Programming with Python', 'Ranga')print(book)

Output

(123, 'Object Oriented Programming with Python', 'Ranga', [])

How do we add reviews?

Before we are able to add reviews, we need to have aclass calledReview.

In Python, You can have multiple classes in the same file.

Let’s start with this

class Review:    def __init__(self, id, description, rating):        self.id = id        self.description = description        self.rating = rating    def __repr__(self):        return repr((self.id,self.description,self.rating))

Let’s create a Review and print it as well.

review = Review(10, "Great Book", 5)print(review)

Output

(10, 'Great Book', 5)

There is no relationship between theBook andReview. Let’s fix it by creating anadd_review() method. Let’s add this toBook class.

    def add_review(self, review):        self.reviews.append(review)

Let’s use this to add a couple of reviews:

book.add_review(Review(10, "Great Book", 5))book.add_review(Review(101, "Awesome", 5))print(book)

Output

(123, 'Object Oriented Programming with Python', 'Ranga', [(10, 'Great Book', 5), (101, 'Awesome', 5)])

Here’s the complete code we have until now.

class Book(object):    def __init__(self, id, name, author):        self.id = id        self.name = name        self.author = author        self.reviews = []    def __repr__(self):        return repr((self.id,self.name,self.author,self.reviews))    def add_review(self, review):        self.reviews.append(review)class Review:    def __init__(self, id, description, rating):        self.id = id        self.description = description        self.rating = rating    def __repr__(self):        return repr((self.id,self.description,self.rating))book = Book(123, 'Object Oriented Programming with Python', 'Ranga')# book.add_review()book.add_review(Review(10, "Great Book", 5))book.add_review(Review(101, "Awesome", 5))print(book)

Output

(123, 'Object Oriented Programming with Python', 'Ranga', [(10, 'Great Book', 5), (101, 'Awesome', 5)])

Summary

We created aBookclass, aReviewclass, and added behavior to theBook so we can add Reviews to it. The relationship betweenBook andReview is called composition. ABook instance consists of instances of Review.

In the next step, we would look at on the relationship called inheritance.

Step 04: Why Do We Need Inheritance

In this step, let’s look at why we needinheritance. We consider a simple example involving anAnimal and aPet, and understand its importance.

Let’s create a simple class calledAnimal with a methodbark and create an instance of it.

    >>> class Animal:    ...   def bark(self):    ...     print("bark")    >>> animal = Animal()    >>> animal.bark()    bark

We want to create another classPet with ability tobark andgroom.

    >>> class Pet:    ...   def bark(self):    ...     print("bark")    ...   def groom(self):    ...     print("groom")    >>> pet = Pet()    >>> pet.bark()    bark    >>> pet.groom()    groom

In above classes, there is an unnecessary repetition ofbark(). Why can’tPet inherit the behavior fromAnimal? That’s whereinheritance comes in.

Let’s see how can how we can do that.

Look at this class definition:class Pet(Animal) indicates thatPet extendsAnimal class.

    >>> class Pet(Animal):    ...   def groom(self):    ...     print("groom")    ...    >>> dog = Pet()

You can obviously dopet.groom() on thePet.

But the interesting thing is you would be able to even dopet.bark(), even though pet does not containbark(). It inherits the behavior from theAnimalclass.

    >>> dog.bark()    >>> bark

Animal class is called a super-class, andPet is called asubclass. The subclass inherits the behavior and properties of the super-class.

Inheritance is a powerful concept. One of the most important things to understand, is to use inheritance only when there is anis-a relationship. Over here,Pet is-a Animal.

Sometimes, inheritance is misused in situations where there is no is-a relationship, and that can lead to problems.

Step 05: All Classes In Python 3 Inherit Fromobject

object is a base for all classes in Python.

It has the methods that are common to all instances of Python classes

Let’s define Book class, create an instance and print it

class Book(): passbook = Book()print(book)

Output is<__main__.Book object at 0x7f78e7fe1588>.

Where is the output coming from?

Book class inherits fromobject class.

The default implementation ofrepr method return the value shown in the output.

Let’s override therepr method.

class Book():  def __repr__(self):     return repr('new book')book = Book()print(book)

Output is'new book'.

We are now overriding the defaultrepr implementation fromobject class.

Step 06: Multiple Inheritance

In this step, let’s look at an interesting feature which is supported by Python. It’s called multiple inheritance. It means a singleclass can inherit from multiple classes.

We will create two classes -LandAnimal andWaterAnimal.

class LandAnimal: passclass WaterAnimal: pass

We want to createAmphibian class extending bothWaterAnimal andLandAnimal.

class Amphibian(WaterAnimal, LandAnimal): passamphibian = Amphibian()

What we are doing in here is calledmultipleinheritance.

TheAmphibianclass is inheriting fromWaterAnimal and theLandAnimal. If these classes have any methods, then theAmphibian class will also inherit those.

Let’s add constructors to these classes.

First thing we do is we’ll delegate to the superclass constructor -super().__init__().

We will add awalking_speed toLandAnimal andswimming_speed toWaterAnimal.

class LandAnimal:    def __init__(self):        super().__init__()        self.walking_speed = 5class WaterAnimal:    def __init__(self):        super().__init__()        self.swimming_speed = 10class Amphibian(WaterAnimal, LandAnimal):    def __init__(self):        super().__init__()amphibian = Amphibian()print(amphibian.swimming_speed)print(amphibian.walking_speed)

Output

105

You can see thatamphibian object inherits properties from both super classes.

Let’s add behavior as well : methodincrease_walking_speed inLandAnimal and methodincrease_swimming_speed inWaterAnimal.

class LandAnimal:    def __init__(self):        super().__init__()        self.walking_speed = 5    def increase_walking_speed(self, how_much):        self.walking_speed += how_muchclass WaterAnimal:    def __init__(self):        super().__init__()        self.swimming_speed = 10    def increase_swimming_speed(self, how_much):        self.swimming_speed += how_muchclass Amphibian(WaterAnimal, LandAnimal):    def __init__(self):        super().__init__()amphibian = Amphibian()amphibian.increase_swimming_speed(25)amphibian.increase_walking_speed(50)print(amphibian.swimming_speed)print(amphibian.walking_speed)

Output

3555

You can see that we are successfully able to call super class methods on theamphibian object.

Summary

In Python, you can have multiple inheritance. We saw how you can inherit from two classes.Amphibianclass inherit data and behavior from the two super-classes.

Step 07: Creating And Using An Abstract Class

In this step let’s look at an important feature in related to object oriented programming calledabstractclass. We’ll understand how you can create abstract classes, and also see where you can use abstract classes.

What do we mean by an abstract class?

Let’s say we have a class calledAnimal. It’s an emptyclass. Typically, you’ll be able to create instances of this class.

There might be certain situations where we don’t know what the code inside a method should be. However, you want the sub-classes to define how this method should behave.

When we createdAnimal, it might not know how tobark. We would want to leave the definition of the method to sub-classes. In such situations, we go for an abstract class.

An abstract class might have severalabstract methods.

Let’s defineAbstractAnimal class with abstract methodbark.

We would need to extend a class calledABC - Abstract Base Class. We need add a decorator on abstract method -@abstractmethod.

from abc import ABC, abstractmethodclass AbstractAnimal(ABC):    @abstractmethod    def bark(self): pass

We cannot create an instance of abstract class.

animal = AbstractAnimal()

Error from above code -TypeError: Can't instantiate abstract class AbstractAnimal with abstract methods bark

You can create a sub class implementing the abstract methods in the abstract class.

class Dog(AbstractAnimal):    def bark(self):        print("Bow Bow")print(Dog().bark())

This prints'Bow Bow'

Let’s look at more related to abstract classes in the next step.

Step 08: Template Method Pattern WithRecipe Class

In the previous step, we looked at the basics of abstract class.

In this step. Let’s look at a real world example of how you can use an abstract class.

Let’s create a class calledRecipe. Typically when we cook something, there are typically three steps involved.

  • The first one is to prepare. You’d want to make sure, that you have all the raw materials ready, you have clean vessels, and the dishes are done and ready for use.
  • The second one, is to execute the recipe, so you need to follow the instructions.
  • The last step is to do a clean up. Make sure that you clean and things like that.

Let’s say now, you’re creating aclass to represent aRecipe, and you want to make sure that each of the sub-classes follow these three steps.

How do we do that?

One of the solutions we can use, is to use abstract class.

Let’s create the classAbstractRecipe.

It has three abstract methods -prepare andrecipe andcleanup. Sub classes can implement these methods.

Theexecute method calls these three steps.

from abc import ABC, abstractmethodclass AbstractRecipe(ABC):    def execute(self):        self.prepare()        self.recipe()        self.cleanup()    @abstractmethod    def prepare(self): pass    @abstractmethod    def recipe(self): pass    @abstractmethod    def cleanup(self): pass

What we are saying is, we don’t know what are the steps which are involved in the preparation, recipe or cleanup. However, we want to ensure that these three steps are defined by all the sub-classes. And when we execute something, we would want to follow these steps in that order.

We are defining an algorithm, and leaving the implementation of individual steps to the sub-classes. This design pattern is also called aTemplate Method design pattern.

Let’s createRecipe1 .

class Recipe1(AbstractRecipe):    def prepare(self):        print('do the dishes')        print('get raw materials')    def recipe(self):        print('execute the steps')    def cleanup(self): pass

When you run this:

Recipe1().execute()

You get

do the dishesget raw materialsexecute the steps

Let’s create another recipe -MicrowaveRecipe.

class MicrowaveRecipe(AbstractRecipe):    def prepare(self):        print('do the dishes')        print('get raw materials')        print('switch on microwave')    def recipe(self):        print('execute the steps')    def cleanup(self):        print('switch off microwave')

When you run this:

MicrowaveRecipe().execute()

You get

do the dishesget raw materialsswitch on microwaveexecute the stepsswitch off microwave

Step 09: A Quick Revision

In this section, we looked at a wide variety of object oriented concepts.

  • We started with revising the basic concepts - classes, objects - state and behavior. We created a couple of simple object oriented programming examples. We designed a Fan and Book classes with state and behavior.
  • We looked at object composition. We created a Book class having a number of Reviews.
  • We looked at inheritance. We created multiple examples of inheritance, and we looked at an example of multiple inheritance as well. Inheritance helps us to design a class hierarchy, and to use properties from the super-class.
  • We looked at a specific type of a class called abstract class, for which you’ll not be able to create instances. We looked at examples where abstract classes are really useful.
  • We looked at the Template Method design pattern, where you define a template, and leave specific implementation details to the subclass. We saw how abstract classes help us to implement Template Method design pattern.

Chapter 12 - Error Handling

Step 01: Introduction To Error Handling - Your Thought Process

Welcome to this section, where we’ll focus on all the important things concerned withexception handling. We’ll discuss how to handle exceptions, and how a programmer’s thought process needs to be when implementing exception handling.

An important things to note is, it’s not just the bad programmers who cause exceptions. Even code written by good programmers can have exceptions. Exceptions can occur because of bad code. Exceptions can also occur when your expectations about the environment did not match. Maybe you were expecting a directory to be there on the system, or a folder structure was not present on your deployment environment. You could be expecting some configuration to be done on a database, which was not done.

What are the keys to exception handling?

The most important thing is, if something that goes wrong is in your system, you should give a good message to the end user. You should tell him what are the next steps he can take. If let’s say, your system expects a file to be there, and the file was not, you should tell the user: “Hey! The file was not there, That’s the reason why the program terminated”.

If the exception happened due to a programming error, you should not just gobble up the exception. You should give enough information to the debugging team to debug the problem. Try and make sure that that information is logged, to help the person who is going to debug the problem.

Summary

In this step, we looked at the fact that both good and bad programmers cause exceptions. But the great programmers are the ones who implement exception handling properly, so that there’s a friendly message to the end user, as well as there is enough information logged for someone to debug the problem.

Step 02: Basics Of Exception Hierarchy

Let’s look at a variety of exceptions.

Let’s do1/0. What do you think will happen?

    >>> 1/0    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    ZeroDivisionError: division by zero    >>> i = 0    >>> j = 10/i    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    ZeroDivisionError: division by zero

The result of this is undefined, and that’s why an error isthrown:ZeroDivisionError.

Earlier we looked at this one as well:'2' + 2.

We are trying to add a string'2', to a number2. What would happen?

    >>> 2 + '2'    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: unsupported operand type(s) for +: 'int' and 'str'

It says “TypeError: I don’t know how to add'int' to a'str'”.

Let’s create a simplelist of numbers:values = [1, '2'],

and we dosum(values), what would happen? Again, the same error:TypeError.

    >>> values = [1,'2']    >>> sum(values)    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: unsupported operand type(s) for +: 'int' and 'str''

Let’s try to access a variable, which is not defined. What would happen?

    >>> value    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    NameError: name 'value' is not defined

It says “NameError! The name ‘value’ is not defined yet”.

Earlier we created a list calledvalues, so on that, let’s call an attribute which is does not exist.

    >>> values.non_existing    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    AttributeError: 'list' object has no attribute 'non_existing'

If we try to sayvalues.<non-existing> ,what would happen? It throwsAttributeError, that says: "list does not have an attributenon_existing’.

The same thing happens, If you try to call a non-existing method.

    >>> values.non_existing()    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    AttributeError: 'list' object has no attribute 'non_existing'

ZeroDivisionError,TypeError,NameError andAttributeError: all are different kinds of exceptions that are defined in Python.

If you want to see the complete list of exceptions, you can import thebuiltinsmodule, and dohelp(builtins).

You would see at the top are classes, and you’d see later a class calledBaseException, from whichException inherits. And after that is a set of errors. The one which we looked at earlier, isZeroDivisionError:

    >>> import builtins    >>> help(builtins)    Help on built-in module builtins:    NAME        builtins - Built-in functions, exceptions, and other objects.    DESCRIPTION        Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.    CLASSES        object            BaseException                Exception                    ArithmeticError                        FloatingPointError                        OverflowError                        ZeroDivisionError                    AssertionError                    AttributeError                    BufferError                    EOFError                    ImportError                        ModuleNotFoundError                    LookupError                        IndexError

You can see thatZeroDivisionError inherits fromArithmeticError, which inherits fromException, which inherits fromBaseExeption, which inherit fromObject.

You also haveIndentationError:

    >>>     values = [1,'1']      File "<stdin>", line 1        values = [1,'1']        ^    IndentationError: unexpected indent    >>>     sum(values)      File "<stdin>", line 1        sum(values)        ^    IndentationError: unexpected indent

In this step, we looked at a high level hierarchy of exceptions. We’ll talk about this a little more in the subsequent step.

Step 03: Basics Of Error- Handling -try-except

In this step, let’s get started with understanding how tohandleexceptions.

We know that1/0 throws an error.

1/0

Output

Traceback (most recent call last):  File "main.py", line 1, in <module>    1/0ZeroDivisionError: division by zero

You can see that the line which throws the error is also printed.

Consider this piece of code. Will j be printed?

i = 0j = 10/iprint(j)

Nope it will not be.

When an exception occurs, program execution terminates, then and there. Unless, you handle the exception.

Even if we had a hundred lines of code right below it, not one of those would get executed. And that’s why you would want to handle exceptions.

We would want to make sure that if an exception happens here, we can give a default value toj.

How can you do that? That’s where thetryblock comes in.

try except has a simple syntax. You put the code you want to look out for exceptions intry. You would write the code to handle the exception inexcept block.

try:    i = 0    j = 10/iexcept:    print("Exception")    j = 0print(j)

Output

Exception0

You can see thatj is assigned a value 0 and theprint method is also called.

Summary

In this step, we looked at the basics of exception handling. We learned that if an exception is not handled, then the subsequent lines of code are not executed. We used atry block to protect our code and we created anexcept block to say what should happen, if an exception is thrown.

At the end, we saw we were able to handle the exception, and continue with the rest of the code.

Step 04: Handling Multiple Errors With Multipleexcept- Blocks

In this we do let’s dig deeper and try to learn more about thetry- exceptblock.

When we run the code, what would happen?

try:    i = 0    j = 10/iexcept:    print("Exception")    j = 0print(j)print("End")

It would print

Exception0End

What would result, if the exception did not occur? Let’s sayi had a value of1 or2.

try:    i = 1    j = 10/iexcept:    print("Exception")    j = 0print(j)print("End")

It would print

10.0End

You can see that'Exception' is not printed.

The code inexcept block is executed, only when there is an exception. If there is no exception, allexcept blocks are skipped.

Let’s look at code below: We are doing asum on list with different types of values.

try:    i = 1    j = 10/i    values = [1, '1']    print(sum(values))except:    print("Exception")    j = 0print(j)print("End")

Output

Exception0End

It prints an exception,Exception. But it does not give us a clue as to what went wrong?

You might be thinking, “What if I want to handle these two exceptions differently?” You might want to be able to say: “For this one, I want to handle and assign a different value to the name. However, if a divide by zero exception happened, then I would want to do something different.” How do you do that?

You can specify what kind of exceptions you would want to handle, is by saying something likeexcept: TypeError.

If you only want the handleTypeErrors, and have code specific to that, as inprint('Type Error'). What would this do? If aTypeError happens, it prints'Type Error', assigns a value of0 toj, and the code continues execution as expected.

try:    i = 1    j = 10/i    values = [1, '1']    print(sum(values))except TypeError:    print("TypeError")    j = 0print(j)print("End")

Output

TypeError0End

If a divide by zero exception happens, it is not handled, and will get thrown out.

The block saysOK! I only know how to handle aTypeError. I don’t know how to handle theZeroDivisionError.

How can you handle this?

We can defineanotherexcept block.

try:    i = 0    j = 10/i    values = [1, '1']    print(sum(values))except TypeError:    print("TypeError")    j = 0except ZeroDivisionError:    print("ZeroDivisionError")    j = 0print(j)print("End")

Output

ZeroDivisionError0End

In this step, we looked at two basic things.

We saw that if no exception happens, then the code inexcept is not executed.

The second thing we learnt, is You can have specific exception blocks, tailored to handle specific exceptions. So if we sayexcept TypeError, then I would only handleTypeError.except ZeroDivisionError would only matchZeroDivisionError.

Step 05: Error Handling Puzzles And Exception Details

In this step, we will be talking about a number of puzzles related to exception handling.

Now let’s start with a very basic example.

What will be the output for this? Think about it.

try:    10/0except TypeError:    print("TypeError")except ZeroDivisionError:    print("ZeroDivisionError")print("End")

You run the code, and the output isZeroDivisionError, and'End'.

Now let’s look at the next one. We want to do10/0. Also, you know thatobject is the super-class of all the classes in Python.

try:    10/0except object:    print("ZeroDivisionError")# catching classes that do not inherit from BaseException is not allowedprint("End")

You’ll see that it throws an error: “catching classes that do not inherit fromBaseException is not allowed”. Even thoughobject is a valid Pythonclass, you cannot catch it. You can only catch those classes which inherit fromBaseException.

What will be the output?

Code is throwing a divide by zero error, handlingException.

try:    10/0except Exception:    print("Exception")

Output -Exception

Exception will match all its sub classes as well. One of which isZeroDivisionError.

Here’s the hierarchy

BaseException    Exception        ArithmeticError            FloatingPointError            OverflowError            ZeroDivisionError

To handleZeroDivisionError, you can handleZeroDivisionError or any of its super classes -ArithmeticError,Exception orBaseException

Now let’s look at the next puzzle.

You can also handle multiple errors in the sameexcept block.

try:    sum([1, '1'])except (ZeroDivisionError, TypeError):    print("Exception")print("End")

Output is'Exception'

The last puzzle shows how you can print the exception details. You would want to get the details of the error, and print them out.

try:    sum([1,'1'])except TypeError as error:    print(error)print("End")

Output

unsupported operand type(s) for +: 'int' and 'str'End

You can see the error details. So, you can handle it better.

Summary

These were a few interesting puzzles related to exception handling. There are two new things we learned in this step. One is, you can handle multiple exceptions in a single except block. The second thing we learned was you can get the error details as well.

Step 06: Error Handling -finally Andelse

We looked attry andexcept. The other two things which are typically part of atry-except block areelse andfinally.

We keep this example very simple for now. Let’s see what would happen, if we run the code as it is:

try:    # Business Logic to read    i = 1 # Not hardcoded, getting a input from user    j = 10/iexcept Exception as error:    print(error)    j = 0else:    print("Else")finally:    # Close    print("Finally")print(j)print("End")

Output

ElseFinally10.0End

Exception is not thrown. So,else andfinally are executed.except is not executed.

What if an error is thrown?

Let’s changei to 0.

    i = 0 # Not hardcoded, getting a input from user

Output

division by zeroFinally0End

Exception is thrown. So,except andfinally are executed.else is not executed.

Here’s the summary:

  • except is called when exception is thrown and exception matches.
  • else is executed only when an exception is not thrown.
  • finally is always executed

Step 07: Error Handling Again

In this step, let’s look at a few more things related to exception handling blocks. We have atry block,except block,else block andfinally block. What are the allowed combinations?

  • With atry, you can have multipleexcept blocks.
  • You cannot have anelse withoutexcept blocks.
  • You can have atry with justfinally - If there is an exception, code in finally is executed.

Step 08: Raising Exceptions

In the previous steps, we looked at how to handle exceptions. But you might be writing code which might throw exceptions as well. So how do you throw exceptions?

Let’s get started with creating a simple example, about currencies. Let’s say we have20 USD, and you would want to be able to add30 USD to it. What would be the result?50 USD.

We want to develop a simple program, which allows us to add currencies.

Think of a scenario where you have to addINR 500 toUSD 50.

Let’s say the first version of the program we write, we don’t support the exchange feature. When different kinds of currencies are passed, we want to throw an exception.

Let’s see how to do that.

Let’s create aCurrencyclass with a constructor andrepr.

class Currency:    def __init__(self, currency, amount):        self.currency = currency        self.amount = amount    def __repr__(self):        return repr((self.currency,self.amount))

All simple stuff.

Let’s create a couple of instances and try to add them.

value1 = Currency("USD", 20)value2 = Currency("INR", 30)print(value1 + value2)

Output

Traceback (most recent call last):  File "main.py", line 11, in <module>    print(value1 + value2)TypeError: unsupported operand type(s) for +: 'Currency' and 'Currency'

You cannot add two currencies. How can we support adding currencies?

We can dooperator overloading, so you can give a new meaning for+ operator for theCurrency class.

We will implement the__add__() method.

    def __add__(self, other):        total_amount = self.amount + other.amount        return Currency(self.currency, total_amount)

If we are doingvalue1 + value2,self would bevalue1, andother would bevalue2. Let’s assume for the time being that the both of them have the same currency.

Let’s run this program.

Output -('USD', 50)

We are assuming that both currencies have the same type. We need to have a check if the currencies are the same. If not, throw an exception.

How do we do that?

You can do that in Python, by sayingraise, and mentionException class, by passing in a text message such as'currencies do not match'.

    def __add__(self, other):        if self.currency != other.currency:            raise Exception("Currencies Do Not Match")        total_amount = self.amount + other.amount        return Currency(self.currency, total_amount)

Let’s create currencies that have different currencies and add them.

value1 = Currency("USD", 20)value2 = Currency("INR", 30)print(value1 + value2)

You can see that"Currencies Do Not Match" is thrown.

Output

Traceback (most recent call last):  File "main.py", line 17, in <module>    print(value1 + value2)  File "main.py", line 11, in __add__    raise Exception("Currencies Do Not Match")Exception: Currencies Do Not Match

Here is the entire code of the program, for your reference:

class Currency:    def __init__(self, currency, amount):        self.currency = currency        self.amount = amount    def __repr__(self):        return repr((self.currency,self.amount))    def __add__(self, other):        if self.currency != other.currency:            raise Exception("Currencies Do Not Match")        total_amount = self.amount + other.amount        return Currency(self.currency, total_amount)value1 = Currency("USD", 20)value2 = Currency("INR", 30)print(value1 + value2)

Step 09: Creating a Custom Exception class

In the previous step, we looked at how to raise an exception. In this step, create a new exceptio type and raise it.

Just like theExceptionclass, we would want to create our ownCurrenciesDoNotMatchError.

Let’s get started withCurrenciesDoNotMatchError

class CurrenciesDoNotMatchError: pass

Can youraise this?

What do you think will happen if we sayraise CurrenciesDoNotMatchError("currencies do not match")?

Error - “exceptions should drive fromBaseException

Whenever you create a custom exception, you need to extendBaseException, or a subclass ofBaseException. Let us choose to extendException.

Let’s add a constructor accepting a message.

class CurrenciesDoNotMatchError(Exception):    def __init__(self,message):        super().__init__(message)

You can also pass in the values ofself.currency andother.currency, so that it’s clear why the exception happened.

raise CurrenciesDoNotMatchError(self.currency + " " + other.currency)

Here is the entire code for your reference:

class CurrenciesDoNotMatchError(Exception):    def __init__(self,message):        super().__init__(message)class Currency:    def __init__(self, currency, amount):        self.currency = currency        self.amount = amount    def __repr__(self):        return repr((self.currency,self.amount))    def __add__(self, other):        if self.currency != other.currency:            raise CurrenciesDoNotMatchError(self.currency + " " + other.currency)        total_amount = self.amount + other.amount        return Currency(self.currency, total_amount)value1 = Currency("USD", 20)value2 = Currency("INR", 30)print(value1 + value2)

Output

Traceback (most recent call last):  File "main.py", line 20, in <module>    print(value1 + value2)  File "main.py", line 14, in __add__    raise CurrenciesDoNotMatchError(self.currency + " " + other.currency)__main__.CurrenciesDoNotMatchError: USD INR

Step 10: Exception Handling Best Practices

Let’s review some of the important exception handling best practices, from our experience.

So what’s the first best practice?

Never hide exceptions. If an exception happens, put the entire stack trace into your logs. In the example which we saw, We understood ‘currencies do not match’. And we also listed what currencies did not match. So that kind of context really helps somebody from outside your team, who’s trying to handle the exception. The moment you start hiding the exceptions, the guy who’s trying to solve it, does not know where to start. He knows something is going wrong, but he does not know which line of code threw the exception.

The second thing is - do not use exception handling for flow control. You cannot have exception handling to redirect the way logic flows in a program, like anif-else. Exception handling is very expensive.

The most important thing about exception handling, is think about your user. If an exception happens, what does your end user want to see, and what can he do about it? As long as you are thinking about it, then you are doing very well.

The other thing is, plan on supporting the guy who’s going to handle the call from your end user. What kind of information does he need to solve the error? The support team might also include the developer, who might want to have a lot of information in the log.

Also, think about the calling method. If you’re designing an API, think about what the calling method can do about this exception.

Last one is have global exception handling. Make sure that you have something sitting on top of everything which is like the global exception handling, so that no exceptions actually go to the end user. It should always be a proper exception message that end user sees, which should tell him what he can do about it. Remember that na end user will not be able to do anything with the stack trace.

We know some of these are not easy to implement, but the most important thing is for you to keep thinking about this.

Once you have the attitude of to think about the end user, your support team, and the calling method, that’s all you would need to make sure that you have some exception handling.

Chapter 13 - More Python Tips

Tip-1:math Module AndDecimal Class

In this quick step, we look at how you can do mathematical calculations accurately, and also at a few important contents of themath module.

floatclass is not really that accurate. If you do4.5 - 3.2 , the value that get is something like1.29999.....999998.

    >>> print(4.5 - 3.2)    1.2999999999999998

That’s where the Decimal class steps in.

    >>> value1 = Decimal('4.5')    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    NameError: name 'Decimal' is not defined

decimal module needs to be imported. Make sure that you createDecimal instances using string constructors.value1 - value2 is printed as1.3 - which is accurate.

    >>> import decimal    >>> from decimal import Decimal    >>> value1 = Decimal('4.5')    >>> value2 = Decimal('3.2')    >>> value1 - value2    Decimal('1.3')

Let’s look more closely at themath module, and other components present within it.

    >>> import math    >>> math.    math.acos(       math.erf(        math.inf         math.pi    math.acosh(      math.erfc(       math.isclose(    math.pow(    math.asin(       math.exp(        math.isfinite(   math.radians(    math.asinh(      math.expm1(      math.isinf(      math.sin(    math.atan(       math.fabs(       math.isnan(      math.sinh(    math.atan2(      math.factorial(  math.ldexp(      math.sqrt(    math.atanh(      math.floor(      math.lgamma(     math.tan(    math.ceil(       math.fmod(       math.log(        math.tanh(    math.copysign(   math.frexp(      math.log10(      math.tau    math.cos(        math.fsum(       math.log1p(      math.trunc(    math.cosh(       math.gamma(      math.log2(    math.degrees(    math.gcd(        math.modf(    math.e           math.hypot(      math.nan

You can also find out the value ofmath.pi, which a constant, andmath.e.

    >>> math.pi    3.141592653589793    >>> math.e    2.718281828459045

If you want to do any mathematical operation, like those involving trigonometry, logarithms, mathematical conversions (degrees to radians, for example), this is your go to module.

Tip-02:None

In this quick tip, we will be talking aboutNone. What isNone? Where do you use it? What are the best practices with it?

The way you think aboutNone is very similar to how you think aboutNULL inSQL. InSQL, if we say something isNULL, it means that it does not have a value. Java programmers would be familiar with that concept as well. When a variable object isnull, that means it’s not referring to anything.

In Python,None is very similar, except for the fact thatNone actually is an instance of a class. If you look attype(None), it isNoneType.None is the only instance of this class.

    >>> None    >>> type(None)    <class 'NoneType'>

Let’s look at a simple example usingNone.

Let’s create a simple method, and call itemail(). We would put thesubject,content,to,cc,bcc as parameters to this method. Let’s say this is the definition ofemail, and it’s just simply print everything in the body, using a formatted string. We are printing upto{cc} among the parameters.

    >>> def email(subject, content, to , cc , bcc):    ...    print(f" {subject}, {content}, {to}, {cc}, "    ... )    ...

Let’s call the method as shown below:

    >>> email("subject", "great work", "in28minutes@gmail.com")    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: email() missing 2 required positional arguments: 'cc' and 'bcc'

You can to see thatemail is missing required positional arguments, which arecc andbcc. But ifcc andbcc are not relevant to my particular email, what to do? Is there a way we can assign default values to them? The default should be something that means “nothing is to be used”.

The solution is: setcc = None andbcc = None. Also, print thecc andbcc inside the method for display.

    >>> def email(subject, content, to , cc=None , bcc=None):    ...    print(f" {subject}, {content}, {to}, {cc}, {bcc}");    ...

We can now call the method again. This time we see the right result.

    >>> email("subject", "great work", "in28minutes@gmail.com")     subject, great work, in28minutes@gmail.com, None, None

If you want to indicate that you don’t want to have asubject, specify thesubject asNone.

    >>> email(None, "great work", "in28minutes@gmail.com", None, None)     None, great work, in28minutes@gmail.com, None, None

UsingNone is considered to be good programming practice, because you can compare variables against it.

Here’s an example:

    >>> var = "123"    >>> if var is None : print ("do something");    ...    >>> var = None    >>> if var is None : print ("do something");    ...    do something    >>>

Tip-2:statistics Module - Find Mean And Median

In this step, let’s try and understand thestatistics module within Python.

Let’s create a simple list, and play around with a few of the functions which are present in theStatisticsclass.

    >>> import statistics    >>> statistics.    statistics.Decimal(          statistics.mean(    statistics.Fraction(         statistics.median(    statistics.StatisticsError(  statistics.median_grouped(    statistics.bisect_left(      statistics.median_high(    statistics.bisect_right(     statistics.median_low(    statistics.chain(            statistics.mode(    statistics.collections       statistics.numbers    statistics.decimal           statistics.pstdev(    statistics.groupby(          statistics.pvariance(    statistics.harmonic_mean(    statistics.stdev(    statistics.math              statistics.variance(

Let’s say we havemarks, having entries[1, 6, 9, 23, 2]. Let’s say you want to find the average mark in the list. What is the average called in statistics? It’s called mean.

    >>> marks = [1, 6, 9, 23, 2]    >>> statistics.mean(marks)    8.2

There are other statistical functions which are present in here. Let’s say you want to find the median ofmarks. The median of a list is the entry that is placed in the middle, when you arrange the numbers in sorted order. Over here, the median seems to be6. If there are even number of numbers (suppose there was a7 also inmarks)median(marks) returns the average of the two values in the center,6 and7. The result is6.5.

    >>> statistics.median(marks)    6    >>> marks = [1, 6, 9, 23, 2, 7]    >>> statistics.median(marks)    6.5

If you want to get the higher of those, you can usemedian_high(), which will return 7. For the lower one, usemedian_low(), which gives back6.

    >>> statistics.median_high(marks)    7    >>> statistics.median_low(marks)    6

The other interesting function isvariance(), which gives an estimate of how much these values vary.

    >>> statistics.variance(marks)    63.2

Tip-3:collections Module -deque For Queue And Stack

In one of the previous tips, we understood the fact that a list can be used both as a queue and a stack. List is not the most efficient representation of a stack.

The best data structure to represent them is adeque. It’ a double-ended queue. That means you can remove values from the start, or at the end.

You can create a simple queue, by using adeque and passing it alist.

    >>> from collections import deque    >>> queue = deque(['Zero','One','Two'])    >>> queue.pop()    'Two'

If you wanted to start using values from the right, doqueue.pop(). You could also append a new value, by doingqueue.append('Three'). If you look at the queue right now, it would have entries['Zero', 'One', 'Three'].

    >>> queue.append('Three')    >>> queue    deque(['Zero', 'One', 'Three'])    >>> queue.append('Four')    >>> queue.append('Five')

You can even append at the start of the queue. The way you can do it is to callappendleft(). Now if you print the contents ofqueue,"Minus One" would be the one at the start of the queue.

    >>> queue.appendLeft('Minus One')    Traceback (most recent call last):      File "<stdin>", line 1, in <module>    AttributeError: 'collections.deque' object has no attribute 'appendLeft'    >>> queue.append    queue.append(      queue.appendleft(    >>> queue.appendleft('Minus One')    >>> queue

The other operation is topopleft(), which returns the first value inside the queue, starting from the left.

    deque(['Minus One', 'Zero', 'One', 'Three', 'Four', 'Five'])    >>> queue.pop()    'Five'    >>> queue.popleft()    'Minus One'

Tip-4:date Module

In this quick tip, we look at how to handle dates in Python.

Let’s get started with importing thedatetime module, which has most of the date and time features.

Let’s say we would want to get the value of today’s date.

How do you do that?datetime.datetime.today()

    >>> import datetime    >>> datetime.datetime.today()    datetime.datetime(2018, 5, 21, 9, 59, 57, 450683)

Let’s take this into a variable:today_date = datetime.datetime.today(). The structure is very simple, it’s year, month, day of the month, followed by hour, minute, second, and micro-seconds.

    >>> today_date = datetime.datetime.today()    >>> today_date    datetime.datetime(2018, 5, 21, 10, 0, 39, 732463)

How do you get information from this structure?

To get year -today_date.year.

Few more examples:

    >>> today_date.year    2018    >>> today_date.month    5    >>> today_date.day    21    >>> today_date.hour    10    >>> today_date.minute    0    >>> today_date.second    39

How do you create a specific date?

    >>> some_date = datetime.datetime(2019, 5, 27)    >>> some_date    datetime.datetime(2019, 5, 27, 0, 0)

You can also create a date with time by adding additional time attributes.

    >>> some_date = datetime.datetime(2019, 5, 27, 9, 5,25)    >>> some_date    datetime.datetime(2019, 5, 27, 9, 5, 25)    >>> some_date = datetime.datetime(2019, 5, 27, 9, 5,25, 234567)    >>> some_date    datetime.datetime(2019, 5, 27, 9, 5, 25, 234567)    >>> some_date.time()    datetime.time(9, 5, 25, 234567)

Now we looked at some of the basic things you can do withdatetime, we’ll look at a few operations to manipulate the date.

We have a date, that is currently2019, 5, 27.

    >>> day = some_date    >>> day    datetime.datetime(2019, 5, 27, 9, 5, 25, 234567)

We want to add to this, a specific number of days, or weeks, or things like that. How to do that?

That’s where a concept calledtimedelta is used.

We have a day variable which contains the value of the date. To this date, you can add a time delta, or remove a time delta.

    >>> day + datetime.timedelta(days=90)    datetime.datetime(2019, 8, 25, 9, 5, 25, 234567)

An important thing to note, is that the original value ofday is not modified.

    >>> day    datetime.datetime(2019, 5, 27, 9, 5, 25, 234567)

You can add weeks and number of hours.

    >>> day + datetime.timedelta(days=90)    datetime.datetime(2019, 8, 25, 9, 5, 25, 234567)    >>> day + datetime.timedelta(weeks=3)    datetime.datetime(2019, 6, 17, 9, 5, 25, 234567)    >>> day + datetime.timedelta(hours=48)    datetime.datetime(2019, 5, 29, 9, 5, 25, 234567)

Tip-5: Methods And Arguments - The Basics

Methods in Python are very very powerful. There are a variety of things that you can pass to them. In this specific step, let’s focus on understanding all the different things that you can pass to a method:normal arguments, default argument, variable arguments, and keyword arguments.

Let’s create a very very simple method, and call thisexample_method().

def example_method(mandatory_parameter, default_parameter="Default"                   , *args, **kwargs):    print(f"""        mandatory_parameter = {mandatory_parameter} {type(mandatory_parameter)}        default_parameter = {default_parameter} {type(default_parameter)}        args = {args} {type(args)}        kwargs = {kwargs} {type(kwargs)}        """)

*args represents variable arguments.**kwargs is calledkeyword argument. All we do in this method, is print all the values out.

Let’s look at how we can call this method. The idea behind what we do, is to understand all these parameters being passed in, how can you call this method with certain order of values, and what get passed to this method, in different ways.

What would happen if we just sayexample_method()?

example_method() #example_method() missing 1 required positional argument

It says “it’s missing one required positional argument”. You should definitely pass a value tomandatory_parameter.

Let’s say you call this with a value, say15. What does it do?

example_method(15)

Output

    mandatory_parameter = 15 <class 'int'>    default_parameter = Default <class 'str'>    args = () <class 'tuple'>    kwargs = {} <class 'dict'>

You can also use the named parameter to get the same result.

example_method(mandatory_parameter=15)

Let’s pass two parameters.

example_method(25,"Some String")

Output

        mandatory_parameter = 25 <class 'int'>        default_parameter = Some String <class 'str'>        args = () <class 'tuple'>        kwargs = {} <class 'dict'>

Instead of the default values,default_parameter gets theSome String value.

Let’s say you want to pass more values.

example_method(25,"String 1","String 2","String 3")

Output

  mandatory_parameter = 25 <class 'int'>        default_parameter = String 1 <class 'str'>        args = ('String 2', 'String 3') <class 'tuple'>        kwargs = {} <class 'dict'>

Additional arguments are passed as variable arguments intoargs.

What if we have even more arguments?

example_method(25,"String 1","String 2","String 3","String 4","String 5")

Output

        mandatory_parameter = 25 <class 'int'>        default_parameter = String 1 <class 'str'>        args = ('String 2', 'String 3', 'String 4', 'String 5') <class 'tuple'>        kwargs = {} <class 'dict'>

Same result : All additional arguments are passed as variable arguments intoargs.

Tip-6: Methods And Arguments - Keyword Arguments

In this step, let’s focus on the last argument:kwargs or keyword arguments.

def example_method(mandatory_parameter, default_parameter="Default"                   , *args, **kwargs):

Let’s pass a few key-value pairs to the method.

example_method(25,"String 1","String 2","String 3",key1='a', key2='b')

Output

        mandatory_parameter = 25 <class 'int'>        default_parameter = String 1 <class 'str'>        args = ('String 2', 'String 3') <class 'tuple'>        kwargs = {'key1': 'a', 'key2': 'b'} <class 'dict'>

You can see the key value pairs are now part of keyword arguments -kwargs.

Let’s see what would happen if we don’t pass in any of the variable arguments.

example_method(25,"String 1",key1='a', key2='b')

Output

        mandatory_parameter = 25 <class 'int'>        default_parameter = String 1 <class 'str'>        args = () <class 'tuple'>        kwargs = {'key1': 'a', 'key2': 'b'} <class 'dict'>

As expected, the variable arguments paramargs is empty.

You can also use named parameters: Result does not change.

example_method(key1='a', key2='b',mandatory_parameter=25,default_parameter="String 1")

One of the things we would recommend you to do, is now that you have this method, play around with it. Try to understand the different ways of calling it. Make sure that you are trying different combinations, and understand what is happening in the background.

I think having a good understanding of what are the possibilities, that you can do with your method signatures, is one of the most important things to be a good Python programmer.

Tip-7: Methods And Arguments - Unpacking Lists And Dictionaries

Welcome to another very useful tip about how to pass values to a method in Python.

Let’s say we have a simple list of values,example_list = [1,2,3]. We want to use the values from this list, as parameters to call a method. How can I do that?

example_list = [1,2,3]example_method(example_list[0],example_list[1],example_list[2])

Output

        mandatory_parameter = 1 <class 'int'>        default_parameter = 2 <class 'int'>        args = (3,) <class 'tuple'>        kwargs = {} <class 'dict'>

Is there a simpler way? Code below give you same result.

example_method(*example_list)

This cool concept is calledunpacking. When you say*example_list, all the elements in the list are passed as individual arguments.

Let’s say you have keyword arguments to pass in, but they are all defined in a dictionary. You can use**example_dict.

example_list = [1,2,3]example_dict = {'a':'1', 'b':'2'}example_method(*example_list, **example_dict)

Output

        mandatory_parameter = 1 <class 'int'>        default_parameter = 2 <class 'int'>        args = (3,) <class 'tuple'>        kwargs = {'a': '1', 'b': '2'} <class 'dict'>

You can see that values inexample_dict are picked by argumentkwargs.

Summary

In this step, we learned that unpacking of data structures is a very useful feature in Python. When you have the parameter values that you would want to pass, in a list or a dictionary, you can use unpacking.

Tip-8: Creating Custom Modules

In this specific step, we will try and understand the concept of amodule.

Let’s create a new Python filemodule_1.

A python file can contain methods and classes.

#module_1.pydef method_1():    print("method 1")class ClassA:    def class_method_1(self):        print("class_method_1 method 1")method_1()ClassA().class_method_1()

If you’re coming from an object oriented programming language like Java, where eachclass is defined in its own source file, you need to change how you think about it. When it comes to Python, a single source file can contain multiple classes.

The way you organize a module in Python, would be to have all of the things which are related to it in a single file. So if you have a group of classes which are related, you take them and put them in a single file.

Whatever code you have directly outside the boundary of aclass or a method would automatically get executed. Here,method1() will be executed.ClassA().class_method_1() will be executed next.

You canreuse one module in another. We’re going to create a new filemodule_2.

And over here, you would want to start using the code frommodule_1.

The first thing to do is toimport it, by sayingimport module_1 . Now, you can use all the features available inmodule_1, by doing things such asmodule_1.method_one(), ormodule_1.ClassA() . And on thatClassA() instance, you can callclass_method_1().

#module_2.pyimport module_1module_1.method_1()module_1.ClassA().class_method_1()

When this code is run, you would see that the messages are shown twice.

  • Once from module_1 import
  • Once from module_2 execution

If you have any code that’s not within a class or a method, then that code is executed automatically.

How can we prevent code outside a class or a method from executing when it is imported?

You can update module_1 with an if condition

if __name__ == '__main__':    method_1()    ClassA().class_method_1()

Tip-9: Defining Equality For Classes

In this tip, we will be looking at how to compare objects in Python.

Let’s create a simple class,Student, and and let’s say it’s an empty class. Let’s create a couple of instances of it,student1 andstudent2. Are these twoStudents equal?

    >>> class Student: pass    ...    >>> student1 = Student()    >>> student2 = Student()

id(student1) gives you an indication of where it is stored in memory.

    >>> id(student1)    4554811768    >>> id(student2)    4554811992

These two are different objects with different values returned byid.

You can useis to compare objects. Withstudent1 is student2 , what we’re really comparing is where they are stored. Is it the same location? Isstudent1 the same object asstudent2?

    >>> student1 is student2    False

The answer is No.

Let’s create a new variablestudent3 as shown below. You can see thatstudent3 andstudent1 are referring to the same location.student1 is student3 returnsTrue.

    >>> student3 = student1    >>> id(student3)    4554811768    >>> id(student1)    4554811768    >>> student1 is student3    True

In Python, you can use== to check equality. The default implementation of== uses'is'.

    >>> student1 == student2    False    >>> student1 == student3    True

Let’s create theStudentclass again, but this time with a constructor. We are creating a simple class, which can have in it, a constructor accepting anid. We have also added in an implementation ofdef __eq__(self, other) comparing the id’s.

    >>> class Student:    ...    def __init__(self, id):    ...       self.id = id    ...    def __eq__(self, other):    ...       return self.id == other.id    ...

Let’s update the definitions of our students. If you look at these objects,student4 andstudent1 are referring to the same object, aren’t they!

    >>> student1 = Student(1)    >>> student2 = Student(2)    >>> student3 = Student(1)    >>> student4 = student1

All statements except forstudent1 is student4 returnFalse.

    >>> student1 is student4    True    >>> student1 is student2    False    >>> student1 is student3    False    >>> student1 == student3    False

Arestudent4 andstudent1 equal? They are pointing to the same object. They are definitely equal.

    >>> student4 == student1    True

Isstudent2 ==student1?False, because they have differentids.

    >>> student2 == student1    False

Let’s see ifstudent3 == student1 Interesting to note, because we have now provided our own implementation of==.

    >>> student3 == student1    True

If you are defining a class, and you would want equality for that class to be looking at the content of the class, then we would need to override the__eq__ method. When you compare objects using== , the__eq__ method would be called.

Releases

No releases published

Packages

No packages published

Contributors3

  •  
  •  
  •  

Languages


[8]ページ先頭

©2009-2025 Movatter.jp