Introduction

Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985-1990.

python-logo

Python has fewer syntactical constructions than other languages. Python is designed to be highly readable. It uses English keywords frequently whereas the other languages use punctuations.

In this Blog, we will be studying Python version 3 programming language. In each blog post, we will have a simple problem statement/title explaining what is the purpose of the given assignment. I will be adding comments in the assignments along with the number of reference links so that it will be easy for you all to understand the purpose of the code statements. You may add comments if you have any queries regarding the assignment. I hope you will enjoy studying python 3 with me. Thank you!

 

Advertisements

Control Structure: For Loop

Hey folks, we are going to learn about for loop in python.

The first and foremost question:

  • When do we use for loops?

for loops are traditionally used when you have a block of code which you want to repeat a fixed number of times.

Suppose we have to print  0 to n numbers in the screen, we will use for loop to print those n numbers.

Let us take a look over the next simple assignment in which we will use a for loop.

# Assignment No. 8 
# Problem Statement: 1. Print 0 to 10 numbers using first for loop and
#                    2. print 0 to 14 numbers using second for loop


print("\n\n First for loop: ")

for i in range(0,11):
    print(i)


print("\n\n Second for loop: ")

for i in range(15):
    print(f"This is element number {i} ")



Output: 

0
1
2
3
4
5
6
7
8
9
10

Second for loop: 
This is element number 0 
This is element number 1 
This is element number 2 
This is element number 3 
This is element number 4 
This is element number 5 
This is element number 6 
This is element number 7 
This is element number 8 
This is element number 9 
This is element number 10 
This is element number 11 
This is element number 12 
This is element number 13 
This is element number 14 

Process finished with exit code 0


Functions used:

1. print ()

We have used a print () function which prints whatever we type inside parentheses. Computer just ignores whatever we put inside the parentheses and prints the string in the console.


Note:

\n is the newline character used to add the new line to a string to be printed.


 

Range Function

What is Python’s range() Function?

In Python, range() function generates a list of numbers, which is generally used to iterate over with for loops.


Python’s range() Parameters

The range() function has two sets of parameters, as follows:

range(stop)

  • stop: Number of integers (whole numbers) to generate, starting from zero.

range(3) == [0, 1, 2].

range([start], stop[, step])

  • start: Starting number of the sequence.
  • stop: Generate numbers up to, but not including this number.
  • step: Difference between each number in the sequence.

Note that:

  • All parameters must be integers.
  • All parameters can be positive or negative.
  • range() (and Python in general) is 0-index based, meaning list indexes start at 0, not 1. eg. The syntax to access the first element of a list is mylist[0]. Therefore the last integer generated by range() is up to, but not including, stop. For example range(0, 5) generates integers from 0 up to, but not including, 5.

Range Examples

>>> range(5)
[0, 1, 2, 3, 4]

>>> range(1,10)
 [1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> range(0,20,2)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

>>> range(20,0,-2)
[20, 18, 16, 14, 12, 10, 8, 6, 4, 2]


 

Control Structure: While Loop

For iteration, Python provides a standard while statement and a very powerful for statement. The while statement repeats a body of code as long as a condition is true.


# Assignment No. 7
# Title: Print Hello World using While loop

i = 0

n = int(input("How many times do you want to print 'Hello World'? "))

while i < n:
    print("Hello world")
    i = i + 1


Output:

How many times do you want to print 'Hello World'?  5

Hello world
Hello world
Hello world
Hello world
Hello world

Process finished with exit code 0


Functions used:

1. print ()

We have used a print () function which prints whatever we type inside parentheses. Computer just ignores whatever we put inside the parentheses and prints the string in the console.

2. input ()

When the input() function is called, the program flow will be stopped until the user has given an input. The input() function accepts the user input.


Important Note:

Folks, read this statement again:

n = int ( input (“How many times do you want to print ‘Hello World’? “) )

By default, input() receives input as a string. But we will have to convert input into integer type.

Hence, we used int() function to convert the input string into int type which is later used in the while statement.


 

Control Stuctures: if..elif..else Statements

Conditional statements are part of every programming language.

In this assignment, we will learn about if elif else statements in Python.

The if statement, which will evaluate whether a statement is true or false, and run code only in the case that the statement is true. It is likely that we will want the program to do something even when an if statement evaluates to false, the else statement will be executed in such case.

In many cases, we will want a program that evaluates more than two possible outcomes. For this, we will use an else if statement, which is written in Python as elif.

The elif or else if statement looks like the if statement and will evaluate another condition.

python-if-else-elif


# Assignment No. 6
# Title: if elif else Operations

print ("if elif else Operations")

print ("Enter a number:")
a=input()
if 10>int(a):
    print ("10 is greater than "+ a )
else:
    print ("10 is lesser than " + a)
    

choice="y"

while choice=="y":
    print ("Now enter a string:")
    b=input()
    if "a" in b:
        print ("the string you entered contains letter a")
    elif "e" in b:
          print ("the string you entered contains letter e")
    elif "i" in b:
          print ("the string you entered contains letter i")
    elif "o" in b:
          print ("the string you entered contains letter o")
    elif "u" in b:
          print ("the string you entered contains letter u")
    else:
        print ("The string you entered does not contain a,e,i,o,u")
    print("Enter your choice as y or n")
    choice=input()

print ("End of program")


Output:

if elif else Operations

Enter a number: 8
10 is greater than 8

Now enter a string:
God
the string you entered contains letter o
Enter your choice as y or n
y
Now enter a string:
soul
the string you entered contains letter o
Enter your choice as y or n
y
Now enter a string:
divine
the string you entered contains letter e
Enter your choice as y or n
y
Now enter a string:
peace
the string you entered contains letter a
Enter your choice as y or n
y
Now enter a string:
happiness
the string you entered contains letter a
Enter your choice as y or n
n

End of program

Process finished with exit code 0

Functions used:

1. print ()

We have used a print () function which prints whatever we type inside parentheses. Computer just ignores whatever we put inside the parentheses and prints the string in the console.

2. input ()

When the input() function is called, the program flow will be stopped until the user has given an input. The input() function accepts the user input.


 

String Operations

In this assignment, we will learn some basic string operations.

String Special Operators

Assume string variable a holds ‘Hello’ and variable b holds ‘Python’, then:

Operator Description Example
+ Concatenation – Concatenates two strings a + b  gives HelloPython
* Repetition – Creates new strings, concatenating multiple copies of the same string a*2 gives HelloHello
[] Slice – Gives the character from the given index a[1] gives e
[ : ] Range Slice – Gives the characters from the given range a[1:4] gives ell
in Membership – Returns true if a character exists in the given string H in a gives 1
not in Membership – Returns true if a character does not exist in the given string M not in a will give 1

# Assignment No. 5
# Title: String Operations

print ("This Program shows String Operations")

s1="apple"
s2="juice"

print ("Concatenation is: \n")
print (s1+s2)

print ("\n Other operations: ")

print (s1*2)
print (s1+" is a fruit")
print ("2")
print ("3")
print ("2"+"3")
print ("match"+"2")
print ("orange"+s2)

print ("------------------------------------")
print ("Enter a string")
s3=input(" ")

print("you entered "+ s3)

print ("ice" in s2)
print ("app" in "apple")
print (not "ice" in s2)
print ("------------------------------------")

print ("Length of the string is : ")
print (len(s3))

print ("------------------------------------")

print (s3.lower())

print (s3.upper())

s4=Divine
print (s4.swapcase())

print ("------------------------------------")
print ("Find")
f1="Recreate yourself daily!"
f2="self"


f1.find(f2)
f1.find(f2,10)
f1.find(f2,18)

print ("Replace")

print (f1.replace("daily","wisely"))

print ("------------------------------------")

Output: 

This Program shows String Operations

Concatenation is: 
applejuice

Other operations: 

appleapple
apple is a fruit
2
3
23
match2
orangejuice

-------------------------------------------------
Enter a string
nature

you entered nature

True
True
False

-------------------------------------------------

Length of the string is : 
6
-------------------------------------------------

nature

NATURE

-------------------------------------------------

Find
13
13
-1

Replace
Recreate yourself wisely!

-------------------------------------------------
Process finished with exit code 0

Functions used:

1. print ()

We have used a print () function which prints whatever we type inside parentheses. Computer just ignores whatever we put inside the parentheses and prints the string in the console.

2. input ()

When the input() function is called, the program flow will be stopped until the user has given an input. The input() function accepts the user input.

3. len ()

Returns the length of the string

4. lower()

The lower() method returns a copy of the string in which all case-based characters have been lowercased.

Converts all uppercase letters in string to lowercase.

5. upper()

The upper() method returns a copy of the string in which all case-based characters have been uppercased.

Converts lowercase letters in string to uppercase.

6. swapcase()

Inverts case for all letters in string.

7. find(str, beg=0 end=len(string)) 

Determine if str occurs in string if starting index beg and ending index end are given returns index if found and -1 otherwise.

str − This specifies the string to be searched.
beg − This is the starting index, by default its 0.
end − This is the ending index, by default its equal to the length of the string.

8. replace()

Replaces all occurrences of old in string with new or at most max occurrences if max given.

 


Notes:

#  is used for inserting comments

\n  is used to insert newline

‘+’ operator can concatenate two strings

Also, note that whenever we have to mention a string, we put the string name inside double quotes ” “.

For example: “fruit”, “orange”, “2match”, “9”, “12months”


 

 

Arithmetic Operations (Version 2: with user input from keyboard)

In the previous blog post Arithmetic Operations (Version 1 : with default input), we used default input parameters for all the arithmetic operations. Now we will be using the input from user.


# Assignment No. 4
# Simple Arithmetic Operations with user input
# Title: Simple Arithmetic Operations: addition, subtraction,
# multiplication and division performed on the input given by user.

print ("Enter first number \n")
num1= input()
print ("Enter second number \n")
num2= input()

print("\n This Program shows Simple Arithmetic Operations")

print (" \n Addition is:")
print(int(num1)+int(num2))

print (" \n Subtraction is:")
print(int(num1)-int(num2))

print (" \n Multiplication is:")
print(int(num1)*int(num2))

print (" \n Division is:")
print(int(num1)/int(num2))

print (" \n Remainder is:")
print(int(num1)%int(num2))

print (" \n Quotient is:")
print(int(num1)//int(num2))

print ("\n Exponential operation is: ")
print(int(num1)**int(num2))


Output:

Enter first number
5

Enter second number
4

This Program shows Simple Arithmetic Operations

Addition is:
9

Subtraction is:
1

Multiplication is:
20

Division is:
1.25

Remainder is:
1

Quotient is:
1

Exponential operation is:
625

Process finished with exit code 0


Functions used:

1. print ()

We have used a print () function which prints whatever we type inside parentheses. Computer just ignores whatever we put inside the parentheses and prints the string in the console.

2. input ()

When the input() function is called, the program flow will be stopped until the user has given an input. The input() function accepts the user input.


Note:

#  is used for inserting comments

\n  is used to insert newline


 

Accepting user input from keyboard

In Python 3.0, we can use input() function to read data from the user. We can store the input from user into a variable.


# Assignment No. 3
# Title: Accepting user input from keyboard

print ("\n Enter a number")
num1= input()

print (" You have entered ")
print (num1)   
# a number entered by user is stored in variable num1 

name= Input ("Enter your name: ")

print ("Your name is ")
print (name)

# name entered by user is stored in variable name

Output: 

 Enter a number
 4

 You have entered 
 4

 Enter your name: Learnerdb

 Your name is 
 Learnerdb

Process finished with exit code 0


Functions used:

1. print ()

We have used a print () function which prints whatever we type inside parentheses. Computer just ignores whatever we put inside the parentheses and prints the string in the console.

2. input ()

When the input() function is called, the program flow will be stopped until the user has given an input.


Note:

#  is used for inserting comments

\n  is used to insert newline