name
can hold the value of John Smith.
Several rules need to be considered when declaring variable names. For starters, a variable name cannot begin with a number. 2name = incorrect #incorrect
name = correct #correct
Variable names are case sensitive. This means that the variable school
is not the same as School
. Variables can hold different data types. This includes strings, integers, Booleans, long, lists, and arrays. In Python, we do not need to declare the data type while writing a variable. This is because the code is compiled and interpreted later. The compiler will throw an error in case there is a mismatch in the data types. Let’s talk about the different data types. 1. Strings Strings are usually presented in a text format. We will declare a string variable, as shown below. print(name)
, the output will be john
. 1. Integers These variables hold numeric values, as shown below. 260
. A TypeError is thrown when you try to add a string to an integer, as shwon below. var1
and var2
by converting var1
to an integer using the int()
function. The following code will execute successfully. Make sure that the variable stores a value that can be converted to an integer before using the int() method. 1. Booleans There are only two Boolean values:True
andFalse
. In other words, something can either be true or false. We declare these values, as shown below. Please note that Python is case sensitive. 1isOn = TrueisChecked = FalseCopied! Abool()
method can help convert a value to a boolean. The code snippets below showcase how abool()
function can be used. 1print(bool("abc")) #returns Trueprint(bool(0)) #returns FalseCopied! Thebool()
function returns False when there are no parameters. 1. Float This data type consists of numbers that have a decimal place. A perfect example of a float variable is highlighted below. 1Bmi = 45.7Copied!Understanding lists Lists allow us to store numerous elements in a particular variable. For instance, we can have a list that stores all the student names in a class. We use[]
to define a list. 1students = [] #list exampleCopied! Elements in a list are usually separated by a comma, as shown below. 1students = [“john”, “Mary Thomas”, “John Smith”]Copied! Each element in the abovestudents
list has an index. By default, the first index is 0. So the item at index [0] isjohn
, while the value at index1
isMary Thomas
. A list of integers will look as follows. 1student_marks = [90, 78, 90, 78]Copied! We can access different list functionalities using built-in functions. For instance, to add a value to thestudent_marks
list, we use theappend
function. 1student_marks.append("Guardian Angel")print(student_marks)Copied! The above function addsGuardian Angel
at the end of thestudent_marks
list. When we print the list it shows: 1#output[90, 78, 90, 78, 'Guardian Angel']Copied! We uselen(student_marks)
to determine the length of the list. We use theremove()
function to delete something from the list. For instance, we can remove90
from thestudent_mark
list as shown below. 1student_marks.remove(90)print(student_marks)Copied! In lists, negative indices allow us to count elements starting from the last one. For instance, the element with an index of-1
in the abovestudent_marks
list is"Guardian Angel"
. The second last element78
has an index of-2
. Understanding functions or methods Methods are quite critical in programming. They help store reusable code. This means that a person can call already declared methods rather than writing statements from scratch repeatedly. This saves significant time, that can be invested in other productive activities. In Python, we use thedef
keyword to declare a function. An example of a python method is shown below. 1def readData(): print('success')Copied! The above function printssuccess
when it’s invoked. We can also pass data to a method, perform some calculations, and return the results. This is demonstrated in the code snippet below. 1def calculateTotal(chem, bio): return chem+bioprint(calculateTotal(90,80))Copied! ThecalculateTotal
method takes in two parameters (chem, bio). The function then returns the sum of the two values. It is important to take note of the data types when passing parameters. For instance, thecalculateTotal
method will not work when we pass in a string as a parameter. This is because the program cannot sum up an integer and a string. As shown above, we can call thecalculateTotal
method directly from our print statement. 1print(calculateTotal(90,80))Copied! Thereturn
keyword ensures that the method returns a result after execution. Note that a function can also call another method. This is illustrated below. 1def readData(chem, bio): return chem+biodef getTotal(): print(readData(90,80)) #calls the readData methodgetTotal()Copied!Understanding loops Loops are critical because they allow us to iterate through lists, check for different conditions, and continuously execute various statements. The main loops arefor
andwhile
. 1. For loops As noted, we can use a for loop to iterate through a list, as shown below: 1student_list = [“John Doore”,”Matu Smith”]for x in student_list: print(x)Copied! Thefor
loop above will print every item in the student_list. 1. While loops A while loop can help us check for a particular condition. For instance, while something is true specific statements can be executed. Here is an example of a while loop in action. 1isChecked = falsewhile isChecked == true: print('Hallo there')Copied! Note that the while loop above will be executed indefinitely until isChecked is set to false. You can press ctrl+c to stop the loop. Classes Classes are a vital component of object-oriented programming. When creating a class, you must use theclass
keyword. Other elements are then nested in the class. Here is an example of a Python class. 1class Farmer: # a class with the name farmer name = "John" # A variable produce = "1000kgs" # A variablefarmer = Farmer() #instatiating the class as an object. print(farmer.name) # accessing the properties of the Farmer class.Copied! Classes can help as group things with similar characteristics. We can also assign values to class variables using theinit
function. 1class Farmer: def __init__(self, farmername, produce): self.farmername = farmername self.produce = producefarmer = Farmer("Carry Sminson", "10,000kgs")print(farmer.farmername, farmer.produce)Copied! In the aboveFarmer
class, theself
keyword represents an instance of an object. In other words, it allows us to access the different methods and attributes defined in the class. You can also declare a method in a class and use it later, as shown below. 1class Farmer: def __init__(self, farmername, produce): self.farmername = farmername self.produce = produce def printDetails(self): # Method print(self.farmername, self.produce)farmer = Farmer("Carry Sminson", "10,000kgs")farmer.printDetails()Copied!
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 a python 3 repl, and call it Hello World. Now you have a blank file called main.py. Now let us write our first line of code: helloworld.py 1print('Hello world!')Copied! 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, which obviously 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. 1Python 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?>Copied! 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 1# Write some comments!Copied! If you have a huge comment, do not 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 1'''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')Copied! Unlike many other languages, there is novar
,let
, orconst
to declare a variable in python. You simply goname = 'value'
. vars1.py 1x = 5y = 7z = x*y # 35print(z) # => 35Copied! 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 1x = 5x = str(x)b = '5'b = int(b)print('x = ', x, '; b = ', str(b), ';') # => x = 5; b = 5;Copied! 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.py1x = 4a = x + 1a = x - 1a = x * 2a = x / 2Copied!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.py1a += 1a -= 1a *= 2a /= 2Copied!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.Like the title? Anyways, a'
and a"
both indicate a string, but do not combine them!quotes.py1x = 'hello' # Goodx = "hello" # Goodx = "hello' # ERRORRR!!!Copied!slicing.pyString SlicingYou 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.1x = 'Hello everybody!'x[1] # 'e'x[-1] # '!'x[5] # ' 'x[1:] # 'ello everybody!'x[:-1] # 'Hello everybod'x[2:-3] # 'llo everyb'Copied!Methods and FunctionsHere 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.py1x = " Testing, testing, testing, testing "print(x.strip())print(len(x))print(x.lower())print(x.upper())print(x.replace('test', 'runn'))print(x.split(','))Copied!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.py1print('Type something: ')x = input()print('Here is what you said: ', x)Copied!If you wanted to make it smaller, and look neater to the user, you could do…inp2.py1print('Here is what you said: ', input('Type something: '))Copied!Running: inp.py1Type something:Hello WorldHere is what you said: Hello WorldCopied!inp2.py1Type something: Hello WorldHere is what you said: Hello WorldCopied!Python has created a lot of functions that are located in other .py files. You need to import these modules 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.py1import randomCopied!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.py1import randomprint(random.randint(3,5)) # Prints a random number between 3 and 5Copied!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 LoopThe 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.py1from time import sleepfor i in range(100): print('Hello') sleep(.3)Copied!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.py1import timefor number in range(100): print(number) time.sleep(.1)Copied!while LoopThe 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.py1while True: # Runs forever print('Hello World!')Copied!Or you could do:while2.py1import randomposition = '<placeholder>'while position != 1: # will run at least once position = random.randint(1, 10) print(position)Copied!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 executes only once. An if statement is written:if.py1import 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!')Copied!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.py1import 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')Copied!Now, you may wonder how to run code if none work. Well, there is a simple statement calledelse:
else.py1import 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')Copied!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: 389nofunc.py1import 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')Copied!Now with functions, you can seriously lower the amount of characters:Characters: 254functions.py1import 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')Copied!Chapter 01 - Getting Ready with PythonInstalling Python 3, And Launching Python ShellThis video should help you get up and running with Python 3 Installing Python is really a cakewalk. Search for “Python download” on www.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 ProgrammingMost programmers find programming a lot of fun, and besides, it also gets their work done.Programming mainly involves problem 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.SummaryIn this step, we: Were introduced to the concept of problem solving Understood how good programmers approach problem solvingStep 01: Our First Programming ChallengeOur first programming 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:The Print Multiplication Table Challenge (PMT-Challenge) Compute the multiplication table for5
, with entries from1
to10
. Display this table.The display needs to be:5 * 1 = 55 * 2 = 105 * 3 = 155 * 4 = 205 * 5 = 255 * 6 = 305 * 7 = 355 * 8 = 405 * 9 = 455 * 10 = 50This is the challenge. For convenience, let’s give it a label, say PMT-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 MethodsIn 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 to PMT-Challenge.SummaryIn this step, we: Stated our first programming challenge Identified what programming concepts we need to learn, to solve this challengeStep 02: Breaking Down PMT-ChallengeTypically 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 solutionThe PMT-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
5 * 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.SummaryIn this step, we: Learned that breaking down a problem into sub-problems is a great help Found a way to break down the PMT-Challenge problemStep 03: Introducing Operators And ExpressionsLet’s focus on solving the first sub-problem of PMT-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 OperatorsLaunch up Python shell. We want to calculate5 * 5
. How do we do that?Using our knowledge of school math, let’s try5 X 5
.1>> 5 X 5 File "< stdin >", line 1 5 X 5 ^ SyntaxError: invalid syntaxCopied!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 valid operator 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
.1>> 5 * 6 30Copied!There are a wide range of other operators in Python:5 + 6
gives a result of11
.5 - 6
leads to-1
.1>> 5 + 611>>> 5 - 6-1Copied!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
.1>> 10 / 2 5.0 >>> 10 ** 3 1000Copied!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 called expressions. So,5 * 5
,5 * 6
and5 - 6
are all expressions. An expression is composed of operators and operands. In the expression5 * 6
, the two values5
and6
are called operands, and the*
operator operates on them. The values5
and6
are literals, 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
.1>> 5 + 5 + 5 15 >>> 5 + 5 * 5 30Copied!Try and play around with the expressions, and understand the output which results.SummaryIn 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 expressionsStep 04: Programming Exercise IN-PE-01At 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 Write an expression to calculate the number of minutes in a day. Write an expression to calculate the number of seconds in a day.NoteYou 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.SolutionsSolution 11>> 24 * 60 1440Copied!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 21>> 24 * 60 * 60 86400Copied!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
.SummaryIn this step, we: Solved a Programming Exercise involving common scenarios, using Python code involving:
Expressions Operators LiteralsStep 05: Puzzles On ExpressionsLet’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 ExpressionsThink 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
.1>> 5 $ 2 File "< stdin >", line 1 5 $ 2 ^ SyntaxError: invalid syntax >>> 5$2 File "< stdin >", line 1 5 $ 2 ^ SyntaxError: invalid syntaxCopied!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!1>> 5+6+10 21Copied!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
.1>> 5/2 2.5Copied!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
?1>> 5 + 5 * 6 35Copied!The correct result is35
.Python decides this is based on the precedence 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
.1>> 5 - 2 * 2 1Copied!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.1>> (5 - 2) * 2 6 >>> 5 - ( 2 * 2 ) 1Copied!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.SummaryIn 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 parenthesesStep 06: Printing TextIn 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 TextHow 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.1>> 5 * 6 = 30 File "<stdin>", line 1 SyntaxError: can't assign to operatorCopied!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.1>> Hello Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'Hello' is not definedCopied!Only expressions work that way, andHello
is not really an expression."Hello"
is typically called a string, 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
?1>> print Hello File "<stdin>", line 1 print Hello ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print(Hello)?Copied!The Python compiler gives you an error, that says “missing parentheses”.Willprint(Hello)
work?1>> print (Hello) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'Hello' is not definedCopied!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")
1>> print ("Hello") Hello >>> print("Hello") HelloCopied!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 a statement, a simple piece of code to execute. As part of this statement, we are calling a function, namedprint()
.What exactly are we trying to print?The text"Hello"
, which is called a parameter or argument, 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.1>> print("5 * 6 = 30") 5 * 6 = 30Copied!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 called hard-coding.In a later step, we will look at how to actually calculate the value and pass it in.SummaryIn 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 stringStep 07: Puzzles On Utility Methods, And StringsIn 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?1>> print("5*6") 5*6 >>> print('5*6') 5*6Copied!It just prints the string"5 * 6"
.Let’s say we try the codeprint(5 * 6)
,1>> print(5*6) 30Copied!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
.1>> abs 10.5 File "<stdin>", line 1 abs 10.5 ^ SyntaxError: invalid syntax >>> abs(10.5) 10.5Copied!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”.1>> abs("10.5") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: bad operand type for abs(): 'str'Copied!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.1>> 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) 32Copied!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.1>> pow(10, 3) 1000 >>> 10 ** 3 1000Copied!max()
returns maximum in a set of numbers.min()
function returns the minimum value.1>> max(34, 45, 67) 67 >>> min(34, 45, 67) 34Copied!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.1>> pow(2,5) 32 >>> Pow(2,5) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'Pow' is not definedCopied!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'
.1>> print("Hello") Hello >>> print("hello") hello >>> print("hellO") hellO >>> print ( "hellO" ) hellOCopied!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.1>> print ( "hellO World" ) hellO World >>> print ( "hellO World" ) hellO WorldCopied!The last thing we want to look at, is an escape 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!1>> print("Hello"") File "<stdin>", line 1 print("Hello"") ^ SyntaxError: EOL while scanning string literalCopied!If you want to print a"
inside a string, use an escape sequence. In Python, the symbol'\'
is used as an escape character. On using'\'
adjacent to the"
, it printsHello"
(notice the trailing"
). We have used the'\'
to escape the"
, by forming an escape sequence\"
.1>> print("Hello\"")Hello">>>Copied!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.1>> print("Hello\nWorld") Hello WorldCopied!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"
.1>> print("Hello\tWorld") Hello WorldCopied!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:"\\\"
.1>> print("Hello\\World") Hello\World >>> print("Hello\\\\\\World") Hello\\\WorldCopied!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')
.1>> print('Hello"') Hello" >>> print("Hello'World") Hello'World >>> print("Hello\"World") Hello"World >>> print("Hello\"World") Hello"WorldCopied!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.SummaryIn 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 sequencesStep 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 Outputformat()
method can be used to print formatted text.Let’s see an example:1>> print("VALUE".format(5*2)) VALUECopied!We were expecting10
to be printed, but it’s actually printingVALUE
.How do we get10
to be printed then?1>> print("VALUE {0}".format(5*2)) VALUE 10Copied!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
.1>> 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 30Copied!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
.1>> print("5 * 6 = 30".format(5,6,5*6)) 5 * 6 = 30Copied!Let replace"5 * 6 = 30"
with"5 * 6 = {2}"
.2
is the index of parameter value5*6
.1>> print("5 * 6 = {2}".format(5,6,5*6)) 5 * 6 = 30Copied!Cool! Progress made.Let’s replace5 * 6
with the right indices -{0} * {1}
.1>> print("{0} * {1} = {2}".format(5,6,5*6)) 5 * 6 = 30Copied!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.1>> 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 = 40Copied!SummaryIn 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 codeStep 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() PuzzlesLet’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?1>> print("{0} * {1} = {2}".format(5,8,5*8,5*9,5*10)) 5 * 8 = 40Copied!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?1>> print("{0} * {1} = {4}".format(5,8,5*8,5*9,5*10)) 5 * 8 = 50Copied!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?1>> print("{0} * {1} = {4}".format(5,8)) Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: tuple index out of rangeCopied!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.1>> print("{0} * {1} = {2}".format(2.5,2,2.5*2)) 2.5 * 2 = 5.0Copied!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?1>> print("My name is {0}".format("Ranga")) My name is RangaCopied!Index0
will be replaced with the first parameter toformat()
.SummaryIn 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 stringStep 10: Introducing VariablesWe 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?1>> 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 = 15Copied!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?1>> index = 2Copied!Aha! This compiles.1>> print("{0} * {1} = {2}".format(5,index,5*index)) 5 * 2 = 10Copied!And this statement is printing5 * 2 = 10
.Let’s try something else. Let’s makeindex = 3
. What would happen?1>> index = 3 >>> print("{0} * {1} = {2}".format(5,index,5*index)) 5 * 3 = 15Copied!The same statement on being run, prints5 * 3 = 15
.How can you check the value thatindex
has? Just type inindex
.1>> index 3 >>> print("{0} * {1} = {2}".format(5,index,5*index)) 5 * 3 = 15Copied!Theindex
symbol we have used here, is what is called a variable.In Python, it’s also called a name.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.1>> 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 = 15Copied!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 VariablesLet’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")
.1>> 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 = 18Copied!The way you can do that is with code like this:print("{0} + {1} + {2} = {3}".format(a,b,c,a+b+c))
.1>> print("{0} + {1} + {2} = {3}".format(a,b,c,a+b+c)) 5 + 6 + 7 = 18Copied!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.1>> a = 6 >>> b = 7 >>> c = 8 >>> print("{0} + {1} + {2} = {3}".format(a,b,c,a+b+c)) 6 + 7 + 8 = 21Copied!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.SummaryIn this step, we: Were introduced to variables, or names, in Python Observed how we could pass in values of variables to theformat()
functionStep 11: Puzzles On VariablesIn 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 VariablesWhat if I try to refer to a variable which is not yet created?1>> 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 definedCopied!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.1>> count = 4 >>> print(count) 4Copied!The statementcount = 4
where we are creating a variable namedcount
for the first time, is called a variable 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.1>> Count Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'Count' is not defined >>> count 4Copied!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.1>> 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 syntaxCopied!After the first symbol, you can also use a numeral in variable names.1>> c12345 = 5Copied!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.SummaryIn 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 variablesStep 12: Introducing AssignmentIn this step, we will look at an important concept in Python, called assignment. In previous steps, we created variables, likei = 5
.Snippet-01: Introducing AssignmentYou can create other variables using whatever valuei
is referring to. If we sayj = i
, what would happen?1>> i = 5 >>> j = i >>> j 5Copied!j
would start referring to the same value thati
is referring to. This statement is called an assignment.Let’s tryj = 2 * i
.1>> j = 2 * i >>> j 10Copied!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”!1>> 5 = j File "<stdin>", line 1 SyntaxError: can't assign to literalCopied!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
.1>> num1 = 5 >>> num2 = 3 >>> sum = num1 + num2 >>> sum 8Copied!Create 3 variablesa
,b
andc
with different values and calculate their sum.1>> a = 5 >>> b = 6 >>> c = 7 >>> sum = a + b + c >>> sum 18Copied!We have just seen the mechanics of how assignment works in Python.SummaryIn 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(=
) operatorStep 13: Introducing Formatted PrintingUntil 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.1>> a = 1 >>> b = 2 >>> c = 3 >>> sum = a + b + c >>> print("{0} + {1} + {2} = {3}".format(a, b, c ,sum)) 1 + 2 + 3 = 6Copied!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.1>> 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 2Copied!The variable within braces is replaced by its value.You can use expressions in a formatted string. Example below uses{a+b}
.1>> print(f"sum of a and b is {a + b}") sum of a and b is 3Copied!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.1>> print(f"{a} + {b} + {c} = {sum}") 1 + 2 + 3 = 6Copied!You can see how easy it turns out to be!Step 14: The PMT-Challenge RevisitedWe 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:1>> 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 = 20Copied!Can we do something, to make sure that the code remains the same all the time, but theindex
value gets updated?1>> 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 = 35Copied!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 the for 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.1>> range(1,10) range(1, 10)Copied!The syntax of thefor
loop is:for i in range(1, 10): ...
. Here,i
is the name of the control variable. In Python, you need to put a colon, ‘:
’, and in the next line give indentation.1>> for i in range(1,10): ... print(i) ... 1 2 3 4 5 6 7 8 9Copied!You would see that it prints from1
to9
.When we run a loop inrange(1, 10)
,1
is inclusive and10
is exclusive.The loop runs from1
to the value before10
, which is9
.The leading whitespace beforeprint(i)
is called indentation. We’ll talk about indentation later, when we talk about puzzles related to thefor
loop.How can you extend this concept to solving our PMT-Challenge problem?1>> print(f"{5} * {index} = {5*index}") 5 * 7 = 35Copied!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.1>> for i in range(1,11): ... print(f"{i}") ... 1 2 3 4 5 6 7 8 9 10Copied!print(f"{i}")
prints the value of i.Now, how do we get it to print5 * 1 = 5
to5 * 10 = 50
?1>> 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 1000Copied!print(f"5 * {i} = {5 * i}")
prints a specific multiple of 5.Step 15: LoopsIn 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:1for i in range(1, 10): print(i)Copied!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?1>> for i in range(1,10) File "<stdin>", line 1 for i in range(1,10) ^ SyntaxError: invalid syntaxCopied!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).1>> for i in range(1,10): ... print(i) File "<stdin>", line 2 print(i) ^ IndentationError: expected an indented blockCopied!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>
.1>> for i in range(1,10): ... print(i) ... 1 2 3 4 5 6 7 8 9Copied!How do we execute two lines of code as part of thefor
loop?1>> 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 18Copied!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:
1>> for i in range(2,5): print(i) ... 2 3 4Copied!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.1>> for i in range(2,5): ... print(i) ... 2 3 4Copied!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.1>> for i in range (1,11,2): ... print(i) ... 1 3 5 7 9Copied!Infor i in range(1, 11, 2)
, we pass in a third argument, called a step. After each iteration, the value ofi
is increment bystep
.SummaryIn 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()
functionStep 16: Programming Exercise PE-BA-02In 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 Print the even numbers up to 10. We would want to print 2 4 6 8 10, using a for loop. Print the first 10 numbers in reverse Print the first 10 even numbers in reverse Print the squares of the first 10 numbers Print the squares of the first 10 numbers, in reverse Print the squares of the even numbersSolution 1Instead 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.1>> for i in range (2,11,2): ... print(i) ... 2 4 6 8 10Copied!Solution 2We 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
.1>> for i in range (10,0,-1): ... print(i) ... 10 9 8 7 6 5 4 3 2 1Copied!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 3Now, let’s print the first10
even numbers in reverse.1>> for i in range (20,0,-2): ... print(i) ... 20 18 16 14 12 10 8 6 4 2Copied!Solution 4Next, we would want to print the squares of the first 10 numbers.1>> for i in range (1,11): ... print(i * i) ... 1 4 9 16 25 36 49 64 81 100Copied!Solution 5Let’s print the squares in the reverse order.1>> for i in range (10,0,-1): ... print(i*i) ... 100 81 64 49 36 25 16 9 4 1Copied!Solution 6Print the squares of the even numbers. How to do that?1>> for i in range (10,0,-2): ... print(i*i) ... 100 64 36 16 4Copied!The key part is using a step of-2
We leave it as an exercise for you, to print squares of odd numbers.SummaryIn 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 the PMT-Challenge problem.Step 17: Review: The Basics Of PythonIt 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 MethodsIn the last section, we introduced you to the basics of python. We learned those concepts by applying them to solve the PMT-Challenge problem. The code below is what we ended up with as we solved that chellenge.Snippet-01: Current Solution To PMT-Challenge1>> for i in range (1,11): ... print(f"8 * {i} = {8 * i}")Copied!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.1>> for i in range (1,11): ... print(f"7 * {i} = {7 * i}")Copied!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:1>> 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 definedCopied!Similarly,print_multiplication_table(8)
, could print the multiplication table for8
!To be able to do this, we need to create a method, or a function. Creating a method makes the code reusable, and we can invoke that method very easily by passing arguments.In this section, we take an in-depth look at methods.Step 01: Defining Your First MethodMethods 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()
.1>> print("Hello World") Hello World >>> print("Hello World") Hello WorldCopied!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).1>> def print_hello_world_twice():... print("Hello World")... print("Hello World")...Copied!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
?1>> print_hello_world_twice <function print_hello_world_twice at 0x10a71ef28>Copied!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,()
!1>> print_hello_world_twice() Hello World Hello World >>> print_hello_world_twice() Hello World Hello WorldCopied!Now, we are able to run the method.SummaryIn 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 writeStep 02: Programming Exercise PE-MD-01We will now leave you with two exercises, based on what we have learned about methods so far.Exercises Write a method calledprint_hello_world_thrice()
. It should print"Hello World"
thrice to the output. Define this method, and also invoke it. 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.SolutionsSolution 11>> def print_hello_world_thrice(): ... print("Hello World") ... print("Hello World") ... print("Hello World") ... >>> print_hello_world_thrice() Hello World Hello World Hello WorldCopied!Solution 21>> 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")Copied!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?1>> def print_your_progress(): ... print("Statement 1\nStatement 2\nStatement 3\nStatement 4") ... >>> print_your_progress() Statement 1 Statement 2 Statement 3 Statement 4Copied!We are using the newline character .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.SummaryIn 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 twoStep 03: Passing Parameters To MethodsIn the previous step,we created methods. We definedprint_hello_world_twice()
, and this printed"Hello World"
twice. In this step, let’s talk about method arguments, or parameters.Snippet-01:1>> print_hello_world_twice() Hello World Hello World >>> print_hello_world_thrice() Hello World Hello World Hello WorldCopied!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 an argument.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.1>> def print_hello_world(no_of_times): ... print("Hello World") ... print(no_of_times) ...Copied!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()
?1>> 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'Copied!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
.1>> print_hello_world(5) Hello World 5 >>> print_hello_world(10) Hello World 10 >>> print_hello_world(100) Hello World 100Copied!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.1>> 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 WorldCopied!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.1>> 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 WorldCopied!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.1>> 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 WorldCopied!Great, it’s now printing the message5
times!1>> print_hello_world(7) Hello World Hello World Hello World Hello World Hello World Hello World Hello WorldCopied!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.SummaryIn 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 bodyStep 04: Classroom Exercise CE-MD-01In this step, Let’s look at a few exercises related to the method parameter.Exercises Write a method calledprint_numbers()
, that would print all successive integers from1
ton
. The second one is to write a method calledprint_squares_of_numbers()
, that prints squares of all successive integers from1
ton
.SolutionsSolution 11>> def print_numbers(n): ... for i in range(1, n+1): ... print(i) ... >>> print_numbers(5) 1 2 3 4 5 >>>Copied!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 2Let’s defineprint_squares_of_numbers()
. This would be very similar toprint_numbers()
, working with the same range. Only, we need to sayprint(i*i)
.1>> 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 25Copied!How is a parameter different from an argument? Inside the definition of the method, the name within parentheses is referred to as a parameter. 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 an argument. Don’t worry too much about it. Just follow this convention for now:
In the method call, call it an argument. In a method definition, call it a parameter.SummaryIn this step, we looked at a few simple exercises related to passing method argumentsStep 05: Methods With Multiple ParametersIn 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.1>> def print_hello_world(no_of_times): ... for i in range(1,no_of_times+1): ... print("Hello World") ...Copied!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.1>> 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 WorldCopied!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”.1>> 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'Copied!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.1>> def print_string(str="Hello World", no_of_times=5): ... for i in range(1,no_of_times+1): ... print(str) ...Copied!Now you can callprint_string()
, and"Hello World"
is displayed5
times.1>> print_string() Hello World Hello World Hello World Hello World Hello WorldCopied!If it’sprint_string("Welcome To Python")
, what does it do? It prints"Welcome To Python"
,5
times.1>> print_string("Welcome to Python") Welcome to Python Welcome to Python Welcome to Python Welcome to Python Welcome to PythonCopied!Considerprint_string("Welcome to Python", 8)
, it would print that string8
times.1>> 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 PythonCopied!Isn’t that cool!SummaryIn 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 parametersStep 06: Back To Multiplication Table - Using MethodsLet’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:1>> for i in range (1,11): ... print(f"7 * {i} = {7 * i}")Copied!Let’s define a method calledprint_multiplication_table()
, and pass in a parameter to it.1>> 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 = 70Copied!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?1>> 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 = 42Copied!Simple! Define those range limits as additional parameters!The other thing we can obviously do, is have default values for thestart
, and theend
.1>> 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 = 70Copied!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!SummaryIn 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 tableStep 07: Indentation Is KingIn 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:1>> 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 10Copied!Consider the code below:print(5)
is indented at the same level asfor loop
.1>> def method_to_understand_indentation(): ... for i in range(1,11) : ... print(i) ... print(5) ...Copied!You can see thatprint(5)
is called only once. It is not part of thefor loop
.1>> method_to_understand_indentation() 1 2 3 4 5 6 7 8 9 10 5Copied!Let’s change the code in this method a bit.print(5)
is indented the same way asprint(i)
1>> def method_to_understand_indentation(): ... for i in range(1,11) : ... print(i) ... print(5) ...Copied!print(5)
is part of the for loop. It is executed 10 times.1>> method_to_understand_indentation() 1 5 2 5 3 5 4 5 5 5 6 5 7 5 8 5 9 5 10 5Copied!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.SummaryIn this step, we: Ran through a few examples to see how indentation works in PythonStep 08: Puzzles on Methods - Named ParametersIn 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?1>> 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 WorldCopied!Will it work if we call the method as in:print_string(6)
?1>> print_string(6) 6 6 6 6 6Copied!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 using named 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)
:1>> print_string(no_of_times=6) Hello World Hello World Hello World Hello World Hello World Hello WorldCopied!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?1>> print_string(7, 8) 7 7 7 7 7 7 7 7Copied!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
.1>> print_string(7.5, 8) 7.5 7.5 7.5 7.5 7.5 7.5 7.5 7.5Copied!What would be the result of this -print_string(7.5, "eight")
?1>> 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 intCopied!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.1>> def 1_print(): File "<stdin>", line 1 def 1_print(): ^ SyntaxError: invalid tokenCopied!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:1```for i in range(1, 11): print(i)```...Copied!for
is a keywordin
is a keyworddef
is a keyword.Later we will look at a few other keywords, such aswhile
,return
,if
,else
,elif
, and many more.1>> 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 syntaxCopied!