Hi! Great day! Welcome to this course. Thank you for taking an interest in this course. Learning from this course will help you become adept at it.

Lesson 1 How does a computer store data

Lesson 2 and 3: Decimal to Binary Conversion

Performing Short Division by Two with Remainder

1
Set up the problem. For this example, let’s convert the decimal number 15610 to binary. Write the decimal number as the dividend inside an upside-down “long division” symbol. Write the base of the destination system (in our case, “2” for binary) as the divisor outside the curve of the division symbol.[2]
This method is much easier to understand when visualized on paper, and is much easier for beginners, as it relies only on division by two.
To avoid confusion before and after conversion, write the number of the base system that you are working with as a subscript of each number. In this case, the decimal number will have a subscript of 10 and the binary equivalent will have a subscript of 2.

2
Divide. Write the integer answer (quotient) under the long division symbol, and write the remainder (0 or 1) to the right of the dividend.[3]
Since we are dividing by 2, when the dividend is even the binary remainder will be 0, and when the dividend is odd the binary remainder will be 1.

3
Continue to divide until you reach 0. Continue downwards, dividing each new quotient by two and writing the remainders to the right of each dividend. Stop when the quotient is 0.

4
Write out the new, binary number. Starting with the bottom remainder, read the sequence of remainders upwards to the top. For this example, you should have 10011100. This is the binary equivalent of the decimal number 156. Or, written with base subscripts: 15610 = 100111002[5]
This method can be modified to convert from decimal to any base. The divisor is 2 because the desired destination is base 2 (binary). If the desired destination is a different base, replace the 2 in the method with the desired base. For example, if the desired destination is base 9, replace the 2 with 9. The final result will then be in the desired base.

Lesson 4: Binary to Decimal Conversion

Using Positional Notation

1
Write down the binary number and list the powers of 2 from right to left. Let’s say we want to convert the binary number 100110112 to decimal. First, write it down. Then, write down the powers of two from right to left. Start at 20, evaluating it as “1”. Increment the exponent by one for each power. Stop when the amount of elements in the list is equal to the amount of digits in the binary number. The example number, 10011011, has eight digits, so the list, with eight elements, would look like this: 128, 64, 32, 16, 8, 4, 2, 1

2
Write the digits of the binary number below their corresponding powers of two. Now, just write 10011011 below the numbers 128, 64, 32, 16, 8, 4, 2, and 1 so that each binary digit corresponds with its power of two. The “1” to the right of the binary number should correspond with the “1” on the right of the listed powers of two, and so on. You can also write the binary digits above the powers of two, if you prefer it that way. What’s important is that they match up.

3
Connect the digits in the binary number with their corresponding powers of two. Draw lines, starting from the right, connecting each consecutive digit of the binary number to the power of two that is next in the list above it. Begin by drawing a line from the first digit of the binary number to the first power of two in the list above it. Then, draw a line from the second digit of the binary number to the second power of two in the list. Continue connecting each digit with its corresponding power of two. This will help you visually see the relationship between the two sets of numbers.

4
Write down the final value of each power of two. Move through each digit of the binary number. If the digit is a 1, write its corresponding power of two below the line, under the digit. If the digit is a 0, write a 0 below the line, under the digit.
Since “1” corresponds with “1”, it becomes a “1.” Since “2” corresponds with “1,” it becomes a “2.” Since “4” corresponds with “0,” it becomes “0.” Since “8” corresponds with “1”, it becomes “8,” and since “16” corresponds with “1” it becomes “16.” “32” corresponds with “0” and becomes “0” and “64” corresponds with “0” and therefore becomes “0” while “128” corresponds with “1” and becomes 128.

5
Add the final values. Now, add up the numbers written below the line. Here’s what you do: 128 + 0 + 0 + 16 + 8 + 0 + 2 + 1 = 155. This is the decimal equivalent of the binary number 10011011.

6
Write the answer along with its base subscript. Now, all you have to do is write 15510, to show that you are working with a decimal answer, which must be operating in powers of 10. The more you get used to converting from binary to decimal, the more easy it will be for you to memorize the powers of two, and you’ll be able to complete the task more quickly.

7
Use this method to convert a binary number with a decimal point to decimal form. You can use this method even when you want to covert a binary number such as 1.12 to decimal. All you have to do is know that the number on the left side of the decimal is in the units position, like normal, while the number on the right side of the decimal is in the “halves” position, or 1 x (1/2).
The “1” to the left of the decimal point is equal to 20, or 1. The 1 to the right of the decimal is equal to 2-1, or .5. Add up 1 and .5 and you get 1.5, which is 1.12 in decimal notation.

Lesson 6: Input -> Process -> Output

Note: From this point forward, the programming language to be used is Python.

Input: “Hello, World!” using Computer Keyboard

Process: Using computer and a programming language in a development environment

Output: Computer Display

The code is like this -> print(“Hello, World!”)

Another formatting way to be used in input->process->output flow:

Introduction
As strings are often made up of written text, there are many instances when we may want to have greater control over how strings look to make them more readable for humans through punctuation, line breaks, and indentation.

In this tutorial, we’ll go over some of the ways we can work with Python strings to make sure that all output text is formatted correctly.

String Literals
Let’s first differentiate between a string literal and a string value. A string literal is what we see in the source code of a computer program, including the quotation marks. A string value is what we see when we call the print() function and run the program.

In the “Hello, World!” program, the string literal is “Hello, World!” while the string value is Hello, World! without the quotation marks. The string value is what we see as the output in a terminal window when we run a Python program.

But some string values may need to include quotation marks, like when we are quoting a source. Because string literals and string values are not equivalent, it is often necessary to add additional formatting to string literals to ensure that string values are displayed the way in which we intend.

Quotes and Apostrophes
Because we can use single quotes or double quotes within Python, it is simple to embed quotes within a string by using double quotes within a string enclosed by single quotes:

‘Sammy says, “Hello!”‘
Or, to use a possessive apostrophe in a string enclosed by double quotes:

“Sammy’s balloon is red.”
In the way we combine single and double quotes, we can control the display of quotation marks and apostrophes within our strings.

Multiple Lines
Printing strings on multiple lines can make text more readable to humans. With multiple lines, strings can be grouped into clean and orderly text, formatted as a letter, or used to maintain the linebreaks of a poem or song lyrics.

To create strings that span multiple lines, triple single quotes ”’ or triple double quotes “”” are used to enclose the string.

”’
This string is on
multiple lines
within three single
quotes on either side.
”’
“””
This string is on
multiple lines
within three double
quotes on either side.
“””
With triple quotes, you can print strings on multiple lines to make text, especially lengthy text, easier to read.

Escape Characters
Another way to format strings is to use an escape character. Escape characters all start with the backslash key ( \ ) combined with another character within a string to format the given string a certain way.

Here is a list of several of the common escape characters:

Escape character How it formats
\ New line in a multi-line string
\ Backslash
‘ Apostrophe or single quote
” Double quote
\n Line break
\t Tab (horizontal indentation)
Let’s use an escape character to add the quotation marks to the example on quotation marks above, but this time we’ll use double quotes:

print(“Sammy says, \”Hello!\””)
Output
Sammy says, “Hello!”
By using the escape character \” we are able to use double quotes to enclose a string that includes text quoted between double quotes.

Similarly, we can use the escape character \’ to add an apostrophe in a string that is enclosed in single quotes:

print(‘Sammy\’s balloon is red.’)
Output
Sammy’s balloon is red.
Because we are now using the escape character we can have an apostrophe within a string that uses single quotes.

When we use triple quotes like we did above, we will see that there is a space at the top and bottom when we print the string. We can remove those spaces by using the \ escape key at the top of our string and again at the end of the string while keeping the text within the program very readable.

“””\
This multi-line string
has no space at the
top or the bottom
when it prints.\
“””
Similarly, we can use the \n escape character to break lines without hitting the enter or return key:

print(“This string\nspans multiple\nlines.”)
Output
This string
spans multiple
lines.
We can combine escape characters, too. Let’s print a multi-line string and include tab spacing for an itemized list, for example:

print(“1.\tShark\n2.\tShrimp\n10.\tSquid”)
Output

  1. Shark
  2. Shrimp
  3. Squid
    The horizontal indentation provided with the \t escape character ensures alignment within the second column in the example above, making the output extremely readable for humans.

Though the \n escape character works well for short string literals, it is important to ensure that source code is also readable to humans. In the case of lengthy strings, the triple quote approach to multi-line strings is often preferable.

Escape characters are used to add additional formatting to strings that may be difficult or impossible to achieve. Without escape characters, how would you construct the string Sammy says, “The balloon’s color is red.”?

Raw Strings
What if we don’t want special formatting within our strings? For example, we may need to compare or evaluate strings of computer code that use the backslash on purpose, so we won’t want Python to use it as an escape character.

A raw string tells Python to ignore all formatting within a string, including escape characters.

We create a raw string by putting an r in front of the string, right before the beginning quotation mark:

print(r”Sammy says,\”The balloon\’s color is red.\””)
Output
Sammy says,\”The balloon\’s color is red.\”
By constructing a raw string by using r in front of a given string, we can retain backslashes and other characters that are used as escape characters.

Conclusion
This tutorial went over several ways to format text in Python 3 through working with strings. By using techniques such as escape characters or raw strings, we are able to ensure that the strings of our program are rendered correctly on-screen so that the end user is able to easily read all of the output text.

Lesson 7: Decision Structures and Boolean Logic

Operators are used to perform operations on values and variables. Operators can manipulate individual items and returns a result. The data items are referred as operands or arguments. Operators are either represented by keywords or special characters. For example, for identity operators we use keyword “is” and “is not”.

Arithmetic Operators
Arithmetic Operators perform various arithmetic calculations like addition, subtraction, multiplication, division, %modulus, exponent, etc. There are various methods for arithmetic calculation in Python like you can use the eval function, declare variable & calculate, or call functions.

Example: For arithmetic operators we will take simple example of addition where we will add two-digit 4+5=9

x= 4
y= 5
print(x + y)
Similarly, you can use other arithmetic operators like for multiplication(*), division (/), substraction (-), etc.

Comparison Operators
These operators compare the values on either side of the operand and determine the relation between them. It is also referred as relational operators. Various comparison operators are ( ==, != , <>, >,<=, etc)

Example: For comparison operators we will compare the value of x to the value of y and print the result in true or false. Here in example, our value of x = 4 which is smaller than y = 5, so when we print the value as x>y, it actually compares the value of x to y and since it is not correct, it returns false.

x = 4
y = 5
print((‘x > y is’,x>y))
Likewise, you can try other comparison operators (x < y, x==y, x!=y, etc.)

Python Assignment Operators
Python assignment operators are used for assigning the value of the right operand to the left operand. Various assignment operators used in Python are (+=, – = , *=, /= , etc.)

Example: Python assignment operators is simply to assign the value, for example

num1 = 4
num2 = 5
print((“Line 1 – Value of num1 : “, num1))
print((“Line 2 – Value of num2 : “, num2))
Example of compound assignment operator

We can also use a compound assignment operator, where you can add, subtract, multiply right operand to left and assign addition (or any other arithmetic function) to the left operand.

Step 1: Assign value to num1 and num2
Step 2: Add value of num1 and num2 (4+5=9)
Step 3: To this result add num1 to the output of Step 2 ( 9+4)
Step 4: It will print the final result as 13
num1 = 4
num2 = 5
res = num1 + num2
res += num1
print((“Line 1 – Result of + is “, res))
Logical Operators
Logical operators in Python are used for conditional statements are true or false. Logical operators in Python are AND, OR and NOT. For logical operators following condition are applied.

For AND operator – It returns TRUE if both the operands (right side and left side) are true
For OR operator- It returns TRUE if either of the operand (right side or left side) is true
For NOT operator- returns TRUE if operand is false
Example: Here in example we get true or false based on the value of a and b

a = True
b = False
print((‘a and b is’,a and b))
print((‘a or b is’,a or b))
print((‘not a is’,not a))
Membership Operators
These operators test for membership in a sequence such as lists, strings or tuples. There are two membership operators that are used in Python. (in, not in). It gives the result based on the variable present in specified sequence or string

Example: For example here we check whether the value of x=4 and value of y=8 is available in list or not, by using in and not in operators.

x = 4
y = 8
list = [1, 2, 3, 4, 5 ];
if ( x in list ):
print(“Line 1 – x is available in the given list”)
else:
print(“Line 1 – x is not available in the given list”)
if ( y not in list ):
print(“Line 2 – y is not available in the given list”)
else:
print(“Line 2 – y is available in the given list”)
Declare the value for x and y
Declare the value of list
Use the “in” operator in code with if statement to check the value of x existing in the list and print the result accordingly
Use the “not in” operator in code with if statement to check the value of y exist in the list and print the result accordingly
Run the code- When the code run it gives the desired output
Identity Operators
To compare the memory location of two objects, Identity Operators are used. The two identify operators used in Python are (is, is not).

Operator is: It returns true if two variables point the same object and false otherwise
Operator is not: It returns false if two variables point the same object and true otherwise
Following operands are in decreasing order of precedence.

Operators in the same box evaluate left to right

Operators (Decreasing order of precedence) Meaning
** Exponent
*, /, //, % Multiplication, Division, Floor division, Modulus
+, – Addition, Subtraction
<= < > >= Comparison operators
= %= /= //= -= += *= **= Assignment Operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
Example:

x = 20
y = 20
if ( x is y ):
print(“x & y SAME identity”)
y=30
if ( x is not y ):
print(“x & y have DIFFERENT identity”)
Declare the value for variable x and y
Use the operator “is” in code to check if value of x is same as y
Next we use the operator “is not” in code if value of x is not same as y
Run the code- The output of the result is as expected
Operator precedence
The operator precedence determines which operators need to be evaluated first. To avoid ambiguity in values, precedence operators are necessary. Just like in normal multiplication method, multiplication has a higher precedence than addition. For example in 3+ 45, the answer is 23, to change the order of precedence we use a parentheses (3+4)5, now the answer is 35. Precedence operator used in Python are (unary + – ~, **, * / %, + – , &) etc.

v = 4
w = 5
x = 8
y = 2
z = 0
z = (v+w) * x / y;
print(“Value of (v+w) * x/ y is “, z)
Declare the value of variable v,w…z
Now apply the formula and run the code
The code will execute and calculate the variable with higher precedence and will give the output
Python 2 Example
Above examples are Python 3 codes, if you want to use Python 2, please consider following codes

Arithmetic Operators

x= 4
y= 5
print x + y

Comparison Operators

x = 4
y = 5
print(‘x > y is’,x>y)

Assignment Operators

num1 = 4
num2 = 5
print (“Line 1 – Value of num1 : “, num1)
print (“Line 2 – Value of num2 : “, num2)

compound assignment operator

num1 = 4
num2 = 5
res = num1 + num2
res += num1
print (“Line 1 – Result of + is “, res)

Logical Operators

a = True
b = False
print(‘a and b is’,a and b)
print(‘a or b is’,a or b)
print(‘not a is’,not a)

Membership Operators

x = 4
y = 8
list = [1, 2, 3, 4, 5 ];
if ( x in list ):
print “Line 1 – x is available in the given list”
else:
print “Line 1 – x is not available in the given list”
if ( y not in list ):
print “Line 2 – y is not available in the given list”
else:
print “Line 2 – y is available in the given list”

Identity Operators

x = 20
y = 20
if ( x is y ):
print “x & y SAME identity”
y=30
if ( x is not y ):
print “x & y have DIFFERENT identity”

Operator precedence

v = 4
w = 5
x = 8
y = 2
z = 0
z = (v+w) * x / y;
print “Value of (v+w) * x/ y is “, z
Summary:
Operators in a programming language are used to perform various operations on values and variables. In Python, you can use operators like

There are various methods for arithmetic calculation in Python as you can use the eval function, declare variable & calculate, or call functions
Comparison operators often referred as relational operators are used to compare the values on either side of them and determine the relation between them
Python assignment operators are simply to assign the value to variable
Python also allows you to use a compound assignment operator, in a complicated arithmetic calculation, where you can assign the result of one operand to the other
For AND operator – It returns TRUE if both the operands (right side and left side) are true
For OR operator- It returns TRUE if either of the operand (right side or left side) is true
For NOT operator- returns TRUE if operand is false
There are two membership operators that are used in Python. (in, not in).
It gives the result based on the variable present in specified sequence or string
The two identify operators used in Python are (is, is not)
It returns true if two variables point the same object and false otherwise
Precedence operator can be useful when you have to set priority for which calculation need to be done first in a complex calculation.

Lesson 8: Repetition Structures

Python comment line

Single-line comments are created simply by beginning a line with the hash (#) character, and they are automatically terminated by the end of line. Comments that span multiple lines – used to explain things in more detail – are created by adding a delimiter (“””) on each end of the comment.

What are Conditional Statements?
Conditional Statement in Python perform different computations or actions depending on whether a specific Boolean constraint evaluates to true or false. Conditional statements are handled by IF statements in Python.

What is If Statement? How to Use it?
In Python, If Statement is used for decision making. It will run the body of code only when IF statement is true.

When you want to justify one condition while the other condition is not true, then you use “if statement”.

Syntax:

if expression
Statement
else
Statement
Let see an example-

#

#Example file for working with conditional statement

#
def main():
x,y =2,8

if(x < y):
    st= "x is less than y"
print(st)

if name == “main“:
main()
Code Line 5: We define two variables x, y = 2, 8
Code Line 7: The if Statement checks for condition x<y which is True in this case
Code Line 8: The variable st is set to “x is less than y.”
Code Line 9: The line print st will output the value of variable st which is “x is less than y”,

What happen when “if condition” does not meet

In this step, we will see what happens when your “if condition” does not meet.

Code Line 5: We define two variables x, y = 8, 4
Code Line 7: The if Statement checks for condition x<y which is False in this case
Code Line 8: The variable st is NOT set to “x is less than y.”
Code Line 9: The line print st – is trying to print the value of a variable that was never declared. Hence, we get an error.

How to use “else condition”

The “else condition” is usually used when you have to judge one statement on the basis of other. If one condition goes wrong, then there should be another condition that should justify the statement or logic.

Example:

#

Example file for working with conditional statement

#
def main():
x,y =8,4

if(x < y):
    st= "x is less than y"
else:
    st= "x is greater than y"
print (st)

if name == “main“:
main()
Code Line 5: We define two variables x, y = 8, 4
Code Line 7: The if Statement checks for condition x<y which is False in this case
Code Line 9: The flow of program control goes to else condition
Code Line 10: The variable st is set to “x is greater than y.”
Code Line 11: The line print st will output the value of variable st which is “x is greater than y”,

When “else condition” does not work

There might be many instances when your “else condition” won’t give you the desired result. It will print out the wrong result as there is a mistake in program logic. In most cases, this happens when you have to justify more than two statement or condition in a program.

An example will better help you to understand this concept.

Here both the variables are same (8,8) and the program output is “x is greater than y”, which is WRONG. This is because it checks the first condition (if condition), and if it fails, then it prints out the second condition (else condition) as default. In next step, we will see how we can correct this error.

#

Example file for working with conditional statement

#
def main():
x,y =8,8

if(x < y):
    st= "x is less than y"
else:
    st= "x is greater than y"
print(st)

if name == “main“:
main()

How to use “elif” condition

To correct the previous error made by “else condition”, we can use “elif” statement. By using “elif” condition, you are telling the program to print out the third condition or possibility when the other condition goes wrong or incorrect.

Example

#

Example file for working with conditional statement

#
def main():
x,y =8,8

if(x < y):
    st= "x is less than y"
 
elif (x == y):
    st= "x is same as y"
 
else:
    st="x is greater than y"
print(st)

if name == “main“:
main()
Code Line 5: We define two variables x, y = 8, 8
Code Line 7: The if Statement checks for condition x<y which is False in this case
Code Line 10: The flow of program control goes to the elseif condition. It checks whether x==y which is true
Code Line 11: The variable st is set to “x is same as y.”
Code Line 15: The flow of program control exits the if Statement (it will not get to the else Statement). And print the variable st. The output is “x is same as y” which is correct

How to execute conditional statement with minimal code

In this step, we will see how we can condense out the conditional statement. Instead of executing code for each condition separately, we can use them with a single code.

Syntax

A If B else C

Example:

def main():
x,y = 10,8
st = “x is less than y” if (x < y) else “x is greater than or equal to y”
print(st)

if name == “main“:
main()
Code Line 2: We define two variables x, y = 10, 8
Code Line 3: Variable st is set to “x is less than y “if xy variable st is set to “x is greater than or equal to y.”
Code Line 4: Prints the value of st and gives the correct output
Instead of writing long code for conditional statements, Python gives you the freedom to write code in a short and concise way.

Nested IF Statement

Following example demonstrates nested if Statement

total = 100

#country = “US”

country = “AU”
if country == “US”:
if total <= 50:
print(“Shipping Cost is $50”)
elif total <= 100:
print(“Shipping Cost is $25”)
elif total <= 150:
print(“Shipping Costs $5”)
else:
print(“FREE”)
if country == “AU”:
if total <= 50:
print(“Shipping Cost is $100”)
else:
print(“FREE”)
Uncomment Line 2 in above code and comment Line 3 and run the code again

Switch Statement

What is switch statement?

A switch statement is a multiway branch statement that compares the value of a variable to the values specified in case statements.

Python language doesn’t have a switch statement.

Python uses dictionary mapping to implement switch statement in Python

Example

function(argument){
switch(argument) {
case 0:
return “This is Case Zero”;
case 1:
return ” This is Case One”;
case 2:
return ” This is Case Two “;
default:
return “nothing”;
};
};

For the above switch statement Alternative in Python

def SwitchExample(argument):
switcher = {
0: ” This is Case Zero “,
1: ” This is Case One “,
2: ” This is Case Two “,
}
return switcher.get(argument, “nothing”)

if name == “main“:
argument = 1
print (SwitchExample(argument))

Python 2 Example

Above codes are Python 3 examples, If you want to run in Python 2 please consider following code.

#If Statement

#Example file for working with conditional statement

#
def main():
x,y =2,8

if(x < y):
    st= "x is less than y"
print st

if name == “main“:
main()

How to use “else condition”

Example file for working with conditional statement

#
def main():
x,y =8,4

if(x < y):
    st= "x is less than y"
else:
    st= "x is greater than y"
print st

if name == “main“:
main()

When “else condition” does not work

Example file for working with conditional statement

#
def main():
x,y =8,8

if(x < y):
    st= "x is less than y"
else:
    st= "x is greater than y"
print st

if name == “main“:
main()

How to use “elif” condition

Example file for working with conditional statement

#
def main():
x,y =8,8

if(x < y):
    st= "x is less than y"
 
elif (x == y):
    st= "x is same as y"
 
else:
    st="x is greater than y"
print st

if name == “main“:
main()

How to execute conditional statement with minimal code

def main():
x,y = 10,8
st = “x is less than y” if (x < y) else “x is greater than or equal to y”
print st

if name == “main“:
main()

Nested IF Statement

total = 100

#country = “US”

country = “AU”
if country == “US”:
if total <= 50:
print “Shipping Cost is $50”
elif total <= 100:
print “Shipping Cost is $25”
elif total <= 150:
print “Shipping Costs $5”
else:
print “FREE”
if country == “AU”:
if total <= 50:
print “Shipping Cost is $100”
else:
print “FREE”

#Switch Statement

def SwitchExample(argument):
switcher = {
0: ” This is Case Zero “,
1: ” This is Case One “,
2: ” This is Case Two “,
}
return switcher.get(argument, “nothing”)

if name == “main“:
argument = 1
print SwitchExample(argument)

What is Loop?
Loops can execute a block of code number of times until a certain condition is met. Their usage is fairly common in programming. Unlike other programming language that have For Loop, while loop, dowhile, etc.

What is For Loop?
For loop is used to iterate over elements of a sequence. It is often used when you have a piece of code which you want to repeat “n” number of time.

What is While Loop?
While Loop is used to repeat a block of code. Instead of running the code block once, It executes the code block multiple times until a certain condition is met.

How to use “While Loop”
While loop does the exactly same thing what “if statement” does, but instead of running the code block once, they jump back to the point where it began the code and repeats the whole process again.

Syntax

while expression
Statement
Example:

#

Example file for working with loops

#
x=0

define a while loop

while(x <4):
print(x)
x = x+1
Output

0
1
2
3
Code Line 4: Variable x is set to 0
Code Line 7: While loop checks for condition x<4. The current value of x is 0. Condition is true. Flow of control enters into while Loop
Code Line 8: Value of x is printed
Code Line 9: x is incremented by 1. Flow of control goes back to line 7. Now the value of x is 1 which is less than 4. The condition is true, and again the while loop is executed. This continues till x becomes 4, and the while condition becomes false.
How to use “For Loop”
In Python, “for loops” are called iterators.

Just like while loop, “For Loop” is also used to repeat the program.

But unlike while loop which depends on condition true or false. “For Loop” depends on the elements it has to iterate.

Example:

#

Example file for working with loops

#
x=0

define a while loop

while(x <4):

print x

x = x+1

Define a for loop

for x in range(2,7):
print(x)
Output

2
3
4
5
6
For Loop iterates with number declared in the range.

For example,

For Loop for x in range (2,7)

When this code is executed, it will print the number between 2 and 7 (2,3,4,5,6). In this code, number 7 is not considered inside the range.

For Loops can also be used for a set of other things and not just number. We will see thin in next section.

How to use For Loop for String
In this step, we will see how “for loops” can also be used for other things besides numbers.

Example:

use a for loop over a collection

Months = [“Jan”,”Feb”,”Mar”,”April”,”May”,”June”]
for m in Months:
print(m)
Output

Jan
Feb
Mar
April
May
June
Code Line 3: We store the months (“Jan, Feb , Mar,April,May,June”) in variable Months

Code Line 4: We iterate the for loop over each value in Months. The current value of Months in stored in variable m

Code Line 5: Print the month

How to use break statements in For Loop
Breakpoint is a unique function in For Loop that allows you to break or terminate the execution of the for loop

Example:

use a for loop over a collection

#Months = ["Jan","Feb","Mar","April","May","June"]
#for m in Months:
    #print m

use the break and continue statements

for x in range (10,20):
if (x == 15): break
#if (x % 2 == 0) : continue
print(x)
Output

10
11
12
13
14
In this example, we declared the numbers from 10-20, but we want that our for loop to terminate at number 15 and stop executing further. For that, we declare break function by defining (x==15): break, so as soon as the code calls the number 15 it terminates the program Code Line 10 declare variable x between range (10, 20)

Code Line 11 declare the condition for breakpoint at x==15,
Code Line 12 checks and repeats the steps until it reaches number 15
Code Line 13 Print the result in output
How to use “continue statement” in For Loop
Continue function, as the name indicates, will terminate the current iteration of the for loop BUT will continue execution of the remaining iterations.

Example

use a for loop over a collection

#Months = ["Jan","Feb","Mar","April","May","June"]
#for m in Months:
    #print m

use the break and continue statements

for x in range (10,20):
#if (x == 15): break
if (x % 5 == 0) : continue
print(x)
Output

11
12
13
14
16
17
18
19
Continue statement can be used in for loop when you want to fetch a specific value from the list.

In our example, we have declared value 10-20, but between these numbers we only want those number that are NOT divisible by 5 or in other words which don’t give zero when divided by 5.

So, in our range (10,11, 12….19,20) only 3 numbers falls (10,15,20) that are divisible by 5 and rest are not.

So except number 10,15 & 20 the “for loop” will not continue and print out those number as output.

Code line 10 declare the variable x for range (10, 20)
Code line 12 declare the condition for x divided by 5=0 continue
Code line 13 print the result
How to use “enumerate” function for “For Loop”
Enumerate function in “for loop” does two things

It returns the index number for the member
And the member of the collection that we are looking at
Example:

Enumerate function is used for the numbering or indexing the members in the list.

Suppose, we want to do numbering for our month ( Jan, Feb, Marc, ….June), so we declare the variable i that enumerate the numbers while m will print the number of month in list.

use a for loop over a collection

Months = [“Jan”,”Feb”,”Mar”,”April”,”May”,”June”]
for i, m in enumerate (Months):
print(i,m)

use the break and continue statements

    #for x in range (10,20):
    #if (x == 15): break
    #if (x % 5 == 0) : continue
    #print x

Output

0 Jan
1 Feb
2 Mar
3 April
4 May
5 June
When code is executed the output of the enumerate function returns the months name with an index number like (0-Jan), (1- Feb), (2- March), etc.

Code Line 3 declares the list of months [ Jan, Feb,…Jun]
Code Line 4 declares variable i and m for For Loop
Code Line 5 will print the result and again enter the For Loop for the rest of the months to enumerate
Pratical Example
Let see another example for For Loop to repeat the same statement over and again.

Python loop Working Code for all exercises
Code for while loop
x=0
while (x<4):
print (x)
x= x+1
For Loop Simple Example
x=0
for x in range (2,7):
print (x)

Use of for loop in string
Months = [“Jan”,”Feb”,”Mar”,”April”,”May”,”June”]
for m in (Months):
print (m)
Use break-statement in for loop
for x in range (10,20):
if (x == 15): break
print (x)
Use of Continue statement in for loop
for x in range (10,20):
if (x % 5 == 0): continue
print (x)

Code for “enumerate function” with “for loop”
Months = [“Jan”,”Feb”,”Mar”,”April”,”May”,”June”]
for i, m in enumerate (Months):
print (i,m)

How to use for loop to repeat the same statement over and again
You can use for loop for even repeating the same statement over and again. Here in the example we have printed out word “guru99” three times.

Example: To repeat same statement number of times, we have declared the number in variable i (i in 123). So when you run the code as shown below, it prints the statement (guru99) that many times the number declared for our the variable in ( i in 123).

for i in ‘123’:
print (“guru99”,i,)
Output

guru99 1
guru99 2
guru99 3
Like other programming languages, Python also uses a loop but instead of using a range of different loops it is restricted to only two loops “While loop” and “for loop”.

While loops are executed based on whether the conditional statement is true or false.
For loops are called iterators, it iterates the element based on the condition set
Python For loops can also be used for a set of various other things (specifying the collection of elements we want to loop over)
Breakpoint is used in For Loop to break or terminate the program at any particular point
Continue statement will continue to print out the statement, and prints out the result as per the condition set
Enumerate function in “for loop” returns the member of the collection that we are looking at with the index number
Python 2 Example

Above codes are Python 3 examples, If you want to run in Python 2 please consider following code.

How to use “While Loop”

Example file for working with loops

#

x=0

define a while loop

while(x <4):
print x
x = x+1

How to use “For Loop”

Example file for working with loops

#

x=0

define a while loop

while(x <4):

print x

x = x+1

Define a for loop

for x in range(2,7):
print x

How to use For Loop for String

use a for loop over a collection

Months = ["Jan","Feb","Mar","April","May","June"]
for m in Months:
    print m

How to use break statements in For Loop

#use a for loop over a collection
#Months = ["Jan","Feb","Mar","April","May","June"]
#for m in Months:
    #print m

use the break and continue statements

    for x in range (10,20):
        if (x == 15): break
        #if (x % 2 == 0) : continue
        print x

How to use “continue statement” in For Loop

#use a for loop over a collection
#Months = ["Jan","Feb","Mar","April","May","June"]
#for m in Months:
    #print m

use the break and continue statements

    for x in range (10,20):
        #if (x == 15): break
        if (x % 5 == 0) : continue
        print x

How to use “enumerate” function for “For Loop”

#use a for loop over a collection
Months = ["Jan","Feb","Mar","April","May","June"]
for i, m in enumerate (Months):
    print i,m

use the break and continue statements

    #for x in range (10,20):
    #if (x == 15): break
    #if (x % 5 == 0) : continue
    #print x

Output

0
1
2
3

2
3
4
5
6

Jan
Feb
Mar
April
May
June

10
11
12
13
14

11
12
13
14
16
17
18
19

0 Jan
1 Feb
2 Mar
3 April
4 May
5 June

Summary:

A conditional statement in Python is handled by if statements and we saw various other ways we can use conditional statements like if and else over here.

“if condition” – It is used when you need to print out the result when one of the conditions is true or false.
“else condition”- it is used when you want to print out the statement when your one condition fails to meet the requirement
“elif condition” – It is used when you have third possibility as the outcome. You can use multiple elif conditions to check for 4th,5th,6th possibilities in your code
We can use minimal code to execute conditional statements by declaring all condition in single statement to run the code
If Statement can be nested

Lesson 9: Functions

What is a Function in Python?
A Functions in Python are used to utilize the code in more than one place in a program, sometimes also called method or procedures. Python provides you many inbuilt functions like print(), but it also gives freedom to create your own functions.

How to define and call a function in Python
Function in Python is defined by the “def ” statement followed by the function name and parentheses ( () )

Example:

Let us define a function by using the command ” def func1():” and call the function. The output of the function will be “I am learning Python function”.

The function print func1() calls our def func1(): and print the command ” I am learning Python function None.”

There are set of rules in Python to define a function.

Any args or input parameters should be placed within these parentheses
The function first statement can be an optional statement- docstring or the documentation string of the function
The code within every function starts with a colon (:) and should be indented (space)
The statement return (expression) exits a function, optionally passing back a value to the caller. A return statement with no args is the same as return None.
Significance of Indentation (Space) in Python
Before we get familiarize with Python functions, it is important that we understand the indentation rule to declare Python functions and these rules are applicable to other elements of Python as well like declaring conditions, loops or variable.

Python follows a particular style of indentation to define the code, since Python functions don’t have any explicit begin or end like curly braces to indicate the start and stop for the function, they have to rely on this indentation. Here we take a simple example with “print” command. When we write “print” function right below the def func 1 (): It will show an “indentation error: expected an indented block”.

Now, when you add the indent (space) in front of “print” function, it should print as expected.

At least, one indent is enough to make your code work successfully. But as a best practice it is advisable to leave about 3-4 indent to call your function.

It is also necessary that while declaring indentation, you have to maintain the same indent for the rest of your code. For example, in below screen shot when we call another statement “still in func1” and when it is not declared right below the first print statement it will show an indentation error “unindent does not match any other indentation level.”

Now, when we apply same indentation for both the statements and align them in the same line, it gives the expected output.

How Function Return Value?
Return command in Python specifies what value to give back to the caller of the function.

Let’s understand this with the following example

Step 1) Here – we see when function is not “return”. For example, we want the square of 4, and it should give answer “16” when the code is executed. Which it gives when we simply use “print x*x” code, but when you call function “print square” it gives “None” as an output. This is because when you call the function, recursion does not happen and fall off the end of the function. Python returns “None” for failing off the end of the function.

Step 2) To make this clearer we replace the print command with assignment command. Let’s check the output.

When you run the command “print square (4)” it actually returns the value of the object since we don’t have any specific function to run over here it returns “None”.

Step 3) Now, here we will see how to retrieve the output using “return” command. When you use the “return” function and execute the code, it will give the output “16.”

Step 4) Functions in Python are themselves an object, and an object has some value. We will here see how Python treats an object. When you run the command “print square” it returns the value of the object. Since we have not passed any argument, we don’t have any specific function to run over here it returns a default value (0x021B2D30) which is the location of the object. In practical Python program, you probably won’t ever need to do this.

Arguments in Functions
The argument is a value that is passed to the function when it’s called.

In other words on the calling side, it is an argument and on the function side it is a parameter.

Let see how Python Args works –

Step 1) Arguments are declared in the function definition. While calling the function, you can pass the values for that args as shown below

Step 2) To declare a default value of an argument, assign it a value at function definition.

Python Functions Tutorial – Define, Call, Indentation & Arguments

Example: x has no default values. Default values of y=0. When we supply only one argument while calling multiply function, Python assigns the supplied value to x while keeping the value of y=0. Hence the multiply of x*y=0

Step 3) This time we will change the value to y=2 instead of the default value y=0, and it will return the output as (4×2)=8.

Step 4) You can also change the order in which the arguments can be passed in Python. Here we have reversed the order of the value x and y to x=4 and y=2.

Step 5) Multiple Arguments can also be passed as an array. Here in the example we call the multiple args (1,2,3,4,5) by calling the (*args) function.

Example: We declared multiple args as number (1,2,3,4,5) when we call the (*args) function; it prints out the output as (1,2,3,4,5)

Tips:

In Python 2.7. function overloading is not supported in Python. Function Overloading is the ability to create multiple methods of the same name with a different implementation. Function Overloading is fully supported in Python 3
There is quite a confusion between methods and functions. Methods in Python are associated with object instances while function are not. When Python calls a method, it binds the first parameter of that call to the appropriate object reference. In simple words, a standalone function in Python is a “function”, whereas a function that is an attribute of a class or an instance is a “method”.
Here is the complete Python 3 code

define a function

def func1():
print (“I am learning Python function”)
print (“still in func1”)

func1()

def square(x):
return x*x
print(square(4))

def multiply(x,y=0):
print(“value of x=”,x)
print(“value of y=”,y)

return x*y

print(multiply(y=2,x=4))
Here is the complete Python 2 code

define a function

def func1():
print ” I am learning Python function”
print ” still in func1″

func1()

def square(x):
return x*x
print square(4)

def multiply(x,y=0):
print”value of x=”,x
print”value of y=”,y

return x*y

print multiply(y=2,x=4)
Summary:
Function in Python is a piece of reusable code that is used to perform single, related action. In this article, we will see

Function defined by the def statement
The code block within every function starts with a colon (:) and should be indented (space)
Any arguments or input parameters should be placed within these parentheses, etc.
At least one indent should be left before the code after declaring function
Same indent style should be maintained throughout the code within def function
For best practices three or four indents are considered best before the statement
You can use the “return” command to return values to the function call.
Python will print a random value like (0x021B2D30) when the argument is not supplied to the calling function. Example “print function.”
On the calling side, it is an argument and on the function side it is a parameter
Default value in argument – When we supply only one argument while calling multiply function or any other function, Python assigns the other argument by default
Python enables you to reverse the order of the argument as well

Lesson 10: List

Python offers a range of compound datatypes often referred to as sequences. List is one of the most frequently used and very versatile datatype used in Python.

How to create a list?

In Python programming, a list is created by placing all the items (elements) inside a square bracket [ ], separated by commas.

It can have any number of items and they may be of different types (integer, float, string etc.).

# empty list
my_list = []
 
# list of integers
my_list = [1, 2, 3]
 
# list with mixed datatypes
my_list = [1, "Hello", 3.4]

Also, a list can even have another list as an item. This is called nested list.

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

How to access elements from a list?

There are various ways in which we can access the elements of a list.

List Index

We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5 elements will have index from 0 to 4.

Trying to access an element other that this will raise an IndexError. The index must be an integer. We can’t use float or other types, this will result into TypeError.

Nested list are accessed using nested indexing.

my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
 
# Output: o
print(my_list[2])
 
# Output: e
print(my_list[4])
 
# Error! Only integer can be used for indexing
# my_list[4.0]
 
# Nested List
n_list = ["Happy", [2,0,1,5]]
 
# Nested indexing
 
# Output: a
print(n_list[0][1])    
 
# Output: 5
print(n_list[1][3])

Negative indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.

my_list = ['p','r','o','b','e']
 
# Output: e
print(my_list[-1])
 
# Output: p
print(my_list[-5])

How to slice lists in Python?

We can access a range of items in a list by using the slicing operator (colon).

my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
 
# elements beginning to 4th
print(my_list[:-5])
 
# elements 6th to end
print(my_list[5:])
 
# elements beginning to end
print(my_list[:])

Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to access a range, we need two indices that will slice that portion from the list.

How to change or add elements to a list?

List are mutable, meaning, their elements can be changed unlike string or tuple.

We can use assignment operator (=) to change an item or a range of items.

# mistake values
odd = [2, 4, 6, 8]
 
# change the 1st item    
odd[0] = 1            
 
# Output: [1, 4, 6, 8]
print(odd)
 
# change 2nd to 4th items
odd[1:4] = [3, 5, 7]  
 
# Output: [1, 3, 5, 7]
print(odd)

We can add one item to a list using append() method or add several items using extend() method.

odd = [1, 3, 5]
 
odd.append(7)
 
# Output: [1, 3, 5, 7]
print(odd)
 
odd.extend([9, 11, 13])
 
# Output: [1, 3, 5, 7, 9, 11, 13]
print(odd)

We can also use + operator to combine two lists. This is also called concatenation.

The * operator repeats a list for the given number of times.

odd = [1, 3, 5]
 
# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])
 
#Output: ["re", "re", "re"]
print(["re"] * 3)

Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.

odd = [1, 9]
odd.insert(1,3)
 
# Output: [1, 3, 9] 
print(odd)
 
odd[2:2] = [5, 7]
 
# Output: [1, 3, 5, 7, 9]
print(odd)

How to delete or remove elements from a list?

We can delete one or more items from a list using the keyword del. It can even delete the list entirely.

my_list = ['p','r','o','b','l','e','m']
 
# delete one item
del my_list[2]
 
# Output: ['p', 'r', 'b', 'l', 'e', 'm']     
print(my_list)
 
# delete multiple items
del my_list[1:5]  
 
# Output: ['p', 'm']
print(my_list)
 
# delete entire list
del my_list       
 
# Error: List not defined
print(my_list)

We can use remove() method to remove the given item or pop() method to remove an item at the given index.

The pop() method removes and returns the last item if index is not provided. This helps us implement lists as stacks (first in, last out data structure).

We can also use the clear() method to empty a list.

my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
 
# Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list)
 
# Output: 'o'
print(my_list.pop(1))
 
# Output: ['r', 'b', 'l', 'e', 'm']
print(my_list)
 
# Output: 'm'
print(my_list.pop())
 
# Output: ['r', 'b', 'l', 'e']
print(my_list)
 
my_list.clear()
 
# Output: []
print(my_list)

Finally, we can also delete items in a list by assigning an empty list to a slice of elements.

>>> my_list = ['p','r','o','b','l','e','m']
>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']

Python List Methods

Methods that are available with list object in Python programming are tabulated below.

They are accessed as list.method(). Some of the methods have already been used above.

Python List Methods
append() – Add an element to the end of the list
extend() – Add all elements of a list to the another list
insert() – Insert an item at the defined index
remove() – Removes an item from the list
pop() – Removes and returns an element at the given index
clear() – Removes all items from the list
index() – Returns the index of the first matched item
count() – Returns the count of number of items passed as an argument
sort() – Sort items in a list in ascending order
reverse() – Reverse the order of items in the list
copy() – Returns a shallow copy of the list

Some examples of Python list methods:

my_list = [3, 8, 1, 6, 0, 8, 4]
 
# Output: 1
print(my_list.index(8))
 
# Output: 2
print(my_list.count(8))
 
my_list.sort()
 
# Output: [0, 1, 3, 4, 6, 8, 8]
print(my_list)
 
my_list.reverse()
 
# Output: [8, 8, 6, 4, 3, 1, 0]
print(my_list)

List Comprehension: Elegant way to create new List

List comprehension is an elegant and concise way to create a new list from an existing list in Python.

List comprehension consists of an expression followed by for statement inside square brackets.

Here is an example to make a list with each item being increasing power of 2.

pow2 = [2 ** x for x in range(10)]
 
# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
print(pow2)

This code is equivalent to

pow2 = []
for x in range(10):
   pow2.append(2 ** x)

A list comprehension can optionally contain more for or if statements. An optional if statement can filter out items for the new list. Here are some examples.

>>> pow2 = [2 ** x for x in range(10) if x > 5]
>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
['Python Language', 'Python Programming', 'C Language', 'C Programming']

Other List Operations in Python

List Membership Test

We can test if an item exists in a list or not, using the keyword in.

my_list = ['p','r','o','b','l','e','m']
 
# Output: True
print('p' in my_list)
 
# Output: False
print('a' in my_list)
 
# Output: True
print('c' not in my_list)

Iterating Through a List

Using a for loop we can iterate though each item in a list.

for fruit in ['apple','banana','mango']:
    print("I like",fruit)

Lesson 11: Strings

In Python everything is object and string are an object too. Python string can be created simply by enclosing characters in the double quote.

For example:

var = “Hello World!”

ccessing Values in Strings

Python does not support a character type, these are treated as strings of length one, also considered as substring.

We use square brackets for slicing along with the index or indices to obtain a substring.

var1 = "Guru99!"
var2 = "Software Testing"
print ("var1[0]:",var1[0])
print ("var2[1:5]:",var2[1:5])

Output

var1[0]: G
var2[1:5]: oftw 

Various String Operators

There are various string operators that can be used in different ways like concatenating different string.

Suppose if a=guru and b=99 then a+b= “guru99”. Similarly, if you are using a*2, it will “GuruGuru”. Likewise, you can use other operators in string.

OperatorDescriptionExample
[]Slice- it gives the letter from the given indexa[1] will give “u” from the word Guru as such ( 0=G, 1=u, 2=r and 3=u)x=”Guru” print (x[1])
[ : ]Range slice-it gives the characters from the given rangex [1:3] it will give “ur” from the word Guru. Remember it will not consider 0 which is G, it will consider word after that is ur.x=”Guru” print (x[1:3])
inMembership-returns true if a letter exist in the given stringu is present in word Guru and hence it will give 1 (True)x=”Guru” print (“u” in x)
not inMembership-returns true if a letter exist is not in the given stringl not present in word Guru and hence it will give 1x=”Guru” print (“l” not in x)
r/RRaw string suppresses actual meaning of escape characters.Print r’\n’ prints \n and print R’/n’ prints \n
% – Used for string format%r – It insert the canonical string representation of the object (i.e., repr(o)) %s- It insert the presentation string representation of the object (i.e., str(o)) %d- it will format a number for displayThe output of this code will be “guru 99”.name = ‘guru’ number = 99 print (‘%s %d’ % (name,number))
+It concatenates 2 stringsIt concatenate strings and gives the resultx=”Guru” y=”99″ print (x+y)
*RepeatIt prints the character twice.x=”Guru” y=”99″ print (x*2)

Some more examples

You can update Python String by re-assigning a variable to another string. The new value can be related to previous value or to a completely different string all together.

x = "Hello World!"
print(x[:6]) 
print(x[0:6] + "Guru99")

Output

Hello
Hello Guru99

Note : – Slice:6 or 0:6 has the same effect

Python String replace() Method

The method replace() returns a copy of the string in which the values of old string have been replaced with the new value.

oldstring = 'I like Guru99' 
newstring = oldstring.replace('like', 'love')
print(newstring)

Output

I love Guru99

Changing upper and lower case strings

In Python, you can even change the string to upper case or lower case.

string="python at guru99"
print(string.upper())

Output

PYTHON AT GURU99

Likewise, you can also do for other function as well like capitalize

string="python at guru99"             
print(string.capitalize())

Output

Python at guru99

You can also convert your string to lower case

string="PYTHON AT GURU99"
print(string.lower())

Output

python at guru99

Using “join” function for the string

The join function is a more flexible way for concatenating string. With join function, you can add any character into the string.

For example, if you want to add a colon (:) after every character in the string “Python” you can use the following code.

print(":".join("Python"))      

Output

P:y:t:h:o:n

Reversing String

By using the reverse function, you can reverse the string. For example, if we have string “12345” and then if you apply the code for the reverse function as shown below.

string="12345"         
print(''.join(reversed(string)))

Output

54321

Split Strings

Split strings is another function that can be applied in Python let see for string “guru99 career guru99”. First here we will split the string by using the command word.split and get the result.

word="guru99 career guru99"           
print(word.split(' '))

Output

['guru99', 'career', 'guru99']

To understand this better we will see one more example of split, instead of space (‘ ‘) we will replace it with (‘r’) and it will split the string wherever ‘r’ is mentioned in the string

word="guru99 career guru99"           
print(word.split('r'))

Output

['gu', 'u99 ca', 'ee', ' gu', 'u99']

Important Note:

In Python, Strings are immutable.

Consider the following code

x = "Guru99"
x.replace("Guru99","Python")
print(x)

Output

Guru99

will still return Guru99. This is because x.replace(“Guru99″,”Python”) returns a copy of X with replacements made

You will need to use the following code to observe changes

x = "Guru99"
x = x.replace("Guru99","Python")
print(x)

Output

Python

Above codes are Python 3 examples, If you want to run in Python 2 please consider following code.

Python 2 Example

#Accessing Values in Strings
var1 = "Guru99!"
var2 = "Software Testing"
print "var1[0]:",var1[0]
print "var2[1:5]:",var2[1:5]
#Some more examples
x = "Hello World!"
print x[:6] 
print x[0:6] + "Guru99"
#Python String replace() Method
oldstring = 'I like Guru99' 
newstring = oldstring.replace('like', 'love')
print newstring
#Changing upper and lower case strings
string="python at guru99"
print string.upper()
string="python at guru99"             
print string.capitalize()
string="PYTHON AT GURU99"
print string.lower()
#Using "join" function for the string
print":".join("Python")               
#Reversing String
string="12345"         
print''.join(reversed(string))
#Split Strings
word="guru99 career guru99"           
print word.split(' ')
word="guru99 career guru99"           
print word.split('r')
x = "Guru99"
x.replace("Guru99","Python")
print x
x = "Guru99"
x = x.replace("Guru99","Python")
print x

Output

var1[0]: G
var2[1:5]: oftw
Hello
Hello Guru99
I love Guru99
PYTHON AT GURU99
Python at guru99
python at guru99
P:y:t:h:o:n
54321
['guru99', 'career', 'guru99']
['gu', 'u99 ca', 'ee', ' gu', 'u99']
Guru99
Python

Python has introduced a .format function which does way with using the cumbersome %d and so on for string formatting.

Summary:

Since Python is an object-oriented programming language, many functions can be applied to Python objects. A notable feature of Python is its indenting source statements to make the code easier to read.

  • Accessing values through slicing – square brackets are used for slicing along with the index or indices to obtain a substring.
    • In slicing, if range is declared [1:5], it can actually fetch the value from range [1:4]
  • You can update Python String by re-assigning a variable to another string
  • Method replace() returns a copy of the string in which the occurrence of old is replaced with new.
    • Syntax for method replace: oldstring.replace(“value to change”,”value to be replaced”)
  • String operators like [], [ : ], in, Not in, etc. can be applied to concatenate the string, fetching or inserting specific characters into the string, or to check whether certain character exist in the string
  • Other string operations include
    • Changing upper and lower case
    • Join function to glue any character into the string
    • Reversing string
    • Split string

Lesson 12: Logic Gates

A Logic gate is an elementary building block of any digital circuits. It takes one or two inputs and produces output based on those inputs. Outputs may be high (1) or low (0). Logic gates are implemented using diodes or transistors. It can also be constructed using vacuum tubes, electromagnetic elements like optics, molecule etc. In a computer, most of the electronic circuits are made up logic gates. Logic gates are used to create a circuit that performs calculations, data storage or shows off object-oriented programming especially the power of inheritance.
There are seven basic logic gates defined, these are: AND gate, OR gate, NOT gate, NAND gate, NOR gate , XOR gate and XNOR gate.

1. AND Gate
The AND gate gives an output of 1 if both the two inputs are 1, it gives 0 otherwise.

Python3 program to illustrate
working of AND gate
def AND (a, b):
if a == 1 and b == 1: return True else: return False
Driver code
if name==’main‘:
print(AND(1, 1))
print(“+—————+—————-+”) print(” | AND Truth Table | Result |”) print(” A = False, B = False | A AND B =”,AND(False,False),” | “) print(” A = False, B = True | A AND B =”,AND(False,True),” | “) print(” A = True, B = False | A AND B =”,AND(True,False),” | “) print(” A = True, B = True | A AND B =”,AND(True,True),” | “)

Output:

True

+—————+—————-

 | AND Truth Table |    Result |

 A = False, B = False | A AND B = False  |

 A = False, B = True  | A AND B = False  |

 A = True, B = False  | A AND B = False  |

 A = True, B = True   | A AND B = True   |

2. NAND Gate
The NAND gate (negated AND) gives an output of 0 if both inputs are 1, it gives 1 otherwise.

Python3 program to illustrate
working of NAND gate
def NAND (a, b):
if a == 1 and b == 1:
return False
else:
return True
Driver code
if name==’main‘:
print(NAND(1, 0))
print(“+—————+—————-+”) print(” | NAND Truth Table | Result |”) print(” A = False, B = False | A AND B =”,NAND(False,False),” | “) print(” A = False, B = True | A AND B =”,NAND(False,True),” | “) print(” A = True, B = False | A AND B =”,NAND(True,False),” | “) print(” A = True, B = True | A AND B =”,NAND(True,True),” | “)

Output:

True

+—————+—————-

 | NAND Truth Table |    Result |

 A = False, B = False | A AND B = True  |

 A = False, B = True  | A AND B = True  |

 A = True, B = False  | A AND B = True  |

 A = True, B = True   | A AND B = False |

 
3. OR Gate
The OR gate gives an output of 1 if either of the two inputs are 1, it gives 0 otherwise.

Python3 program to illustrate
working of OR gate
def OR(a, b):
if a == 1:
return True
elif b == 1:
return True
else:
return False
Driver code
if name==’main‘:
print(OR(0, 0))
print(“+—————+—————-+”) print(” | OR Truth Table | Result |”) print(” A = False, B = False | A AND B =”,OR(False,False),” | “) print(” A = False, B = True | A AND B =”,OR(False,True),” | “) print(” A = True, B = False | A AND B =”,OR(True,False),” | “) print(” A = True, B = True | A AND B =”,OR(True,True),” | “)

Output:

False

+—————+—————-+

 | OR Truth Table |    Result |

 A = False, B = False | A AND B = False  |

 A = False, B = True  | A AND B = True   |

 A = True, B = False  | A AND B = True   |

 A = True, B = True   | A AND B = True   |

 
4. XOR Gate
The XOR gate gives an output of 1 if either both inputs are different, it gives 0 if they are same.

Python3 program to illustrate
working of Xor gate
def XOR (a, b):
if a != b:
return 1
else:
return 0
Driver code
if name==’main‘:
print(XOR(5, 5))
print(“+—————+—————-+”) print(” | XOR Truth Table | Result |”) print(” A = False, B = False | A AND B =”,XOR(False,False),” | “) print(” A = False, B = True | A AND B =”,XOR(False,True),” | “) print(” A = True, B = False | A AND B =”,XOR(True,False),” | “) print(” A = True, B = True | A AND B =”,XOR(True,True),” | “)

Output:

0

+—————+—————-+

 | XOR Truth Table | Result |

 A = False, B = False | A AND B = 0  |

 A = False, B = True  | A AND B = 1  |

 A = True, B = False  | A AND B = 1  |

 A = True, B = True   | A AND B = 0  |

 
5. NOT Gate
It acts as an inverter. It takes only one input. If the input is given as 1, it will invert the result as 0 and vice-versa.

Python3 program to illustrate
working of Not gate
def NOT(a):
if(a == 0):
return 1
elif(a == 1):
return 0
Driver code
if name==’main‘:
print(NOT(0))
print(“+—————+—————-+”) print(” | NOT Truth Table | Result |”) print(” A = False | A NOT =”,NOT(False),” | “) print(” A = True, | A NOT =”,NOT(True),” | “) 

Output:

1

+—————+—————-+

 | NOT Truth Table | Result |

 A = False | A NOT = 1  |

 A = True, | A NOT = 0  |

 
6. NOR Gate
The NOR gate (negated OR) gives an output of 1 if both inputs are 0, it gives 1 otherwise.

Python3 program to illustrate
working of NOR gate
def NOR(a, b):
if(a == 0) and (b == 0):
return 1
elif(a == 0) and (b == 1):
return 0
elif(a == 1) and (b == 0):
return 0
elif(a == 1) and (b == 1):
return 0
Driver code
if name==’main‘:
print(NOR(0, 0))
print(“+—————+—————-+”) print(” | NOR Truth Table | Result |”) print(” A = False, B = False | A AND B =”,NOR(False,False),” | “) print(” A = False, B = True | A AND B =”,NOR(False,True),” | “) print(” A = True, B = False | A AND B =”,NOR(True,False),” | “) print(” A = True, B = True | A AND B =”,NOR(True,True),” | “)

Output:

1

+—————+—————-+

 | NOR Truth Table |   Result |

 A = False, B = False | A AND B = 1  |

 A = False, B = True  | A AND B = 0  |

 A = True, B = False  | A AND B = 0  |

 A = True, B = True   | A AND B = 0  |

 
7. XNOR Gate
The XNOR gate (negated XOR) gives an output of 1 both inputs are same and 0 if both are different.

Python3 program to illustrate
working of Not gate
def XNOR(a,b):
if(a == b):
return 1
else:
return 0
Driver code
if name==’main‘:
print(XNOR(1,1))
print(“+—————+—————-+”) print(” | XNOR Truth Table | Result |”) print(” A = False, B = False | A AND B =”,XNOR(False,False),” | “) print(” A = False, B = True | A AND B =”,XNOR(False,True),” | “) print(” A = True, B = False | A AND B =”,XNOR(True,False),” | “) print(” A = True, B = True | A AND B =”,XNOR(True,True),” | “)

Output:

1

+—————+—————-+

 | XNOR Truth Table |  Result |

 A = False, B = False | A AND B = 1  |

 A = False, B = True  | A AND B = 0  |

 A = True, B = False  | A AND B = 0  |

 A = True, B = True   | A AND B = 1  |

Assignments:

  1. Explain the Review Process Inspection

2. Provide 10 Decimal Numbers with Corresponding Binary Numbers that are not yet used from the lesson
Example: 12 -> 1100

3. Provide 10 Binary Numbers with Corresponding Decimal Numbers that are not yet used from the lesson and not the reverse of the previous lesson and previous assignment
Example: 11011 -> 27

4. Make Conditional and Loop Statements that are not yet used from the lessons
1 Python working code for “elif” statement
1 Python working code for “for” statement
1 Python working code for “while” statement

Exam: Logic Gates

Exam: Logic Gates and Previous Lessons

Top of Form

1. ____ gives an output of 1 if both the two inputs are 1, it gives 0 otherwise.

 NOT Gate

 XNOR Gate

 OR Gate

 NAND Gate

 XOR Gate

 NOR Gate

 AND Gate

Bottom of Form

2. ____ gives an output of 1 both inputs are same and 0 if both are different.

 XOR Gate

 OR Gate

 NOR Gate

 XNOR Gate

 AND Gate

 NAND Gate

 NOT Gate

3. ____ gives an output of 1 if both inputs are 0, it gives 1 otherwise.

 AND Gate

 NOR Gate

 NOT Gate

 XNOR Gate

 OR Gate

 XOR Gate

 NAND Gate

4. ____ given as 1, it will invert the result as 0 and vice-versa.

 NAND Gate

 OR Gate

 XOR Gate

 AND Gate

 NOT Gate

 NOR Gate

 XNOR Gate

5. ____ gives an output of 1 if either both inputs are different, it gives 0 if they are same.

 OR Gate

 NOT Gate

 AND Gate

 NOR Gate

 XNOR Gate

 NAND Gate

 XOR Gate

6. How does a computer make its work extremely fast?

 Through the use of Functions

 Through the use of Logic Gates

 Through the use of Repetition Structures

 Through the use of List

7. ____ gives an output of 0 if both inputs are 1, it gives 1 otherwise.

 XNOR Gate

 AND Gate

 XOR Gate

 NAND Gate

 OR Gate

 NOR Gate

 NOT Gate

8. How does a computer store data?

9. Explain how input then process then output works in your own words.

10. ____ gives an output of 1 if either of the two inputs are 1, it gives 0 otherwise.

 XNOR Gate

 NOR Gate

 NOT Gate

 XOR Gate

 AND Gate

 OR Gate

 NAND Gate