RR Education

बच्चों का भविष्य होगा " रौशन "


Python Programming

By, Raushan Ranjan

What is Programming?

Just like we use Hindi or English to communicate with each other, we use a Programming language to communicate with the computer.

Programming is a way to instruct the computer to perform various tasks.

What is Python?

Python is a simple and easy-to-understand language that feels like reading simple English. This Pseudo code nature of Python makes it easy to learn and understandable for beginners.

Features of Python:

Installation

Python can be easily installed from python.org

When you click on the download button, python can be installed right after you complete the setup by executing the file for your platform.

Tip: Just install it like a game ☻

Chapter 1: Modules, Comments & Pip

Let’s write our very first python program.

Create a file called hello.py and paste the below code into it

Execute this file (.py file) by typing python hello.py, and you will see Hello World printed on the screen.

Modules

A module is a file containing code written by somebody else (usually) which can be imported and used in our programs.

Pip

Pip is a package manager for python. You can use pip to install a module on your system.

E.g., pip install flask (It will install flask module in your system)

Types of modules

There are two types of modules in Python:

  1. Built-in modules – Pre-installed in Python
  2. External modules – Need to install using pip

Some examples of built-in modules are os, abc, etc.

Some examples of external modules are TensorFlow, flask, etc.

Using Python as a Calculator

We can use python as a calculator by typing “python” + TO DO on the terminal. [It opens REPL or read evaluation print loop]

Comments

Comments are used to write something which the programmer does not want to execute.

Comments can be used to mark the author's name, date, etc.

Types of Comments:

There are two types of comments in python,

  1. Single line comments – Written using # (pound/hash symbol)
  2. Multi-line comments – Written using ’’’ Comment ’’’ or ’”” Comment ’””.

Chapter 1 – Practice Set

  1. Write a program to print Twinkle-Twinkle Little Star poem in python.
  2. Use REPL and print the table of 5 using it.
  3. Install an external module and use it to perform an operation of your interest.
  4. Write a python program to print the contents of a directory using os module. Search online for the function which does that.
  5. Label the program written in problem 4 with comments.

Chapter 2 – Variables and Data Types

A variable is a name given to a memory location in a program. For example

Variable – Container to store a value

Keywords – Reserved words in Python

Identifiers – class/function/variable name

Data Types:

Primarily there are the following data types in Python:

  1. Integers
  2. Floating point numbers
  3. Strings
  4. Booleans
  5. None

Python is a fantastic language that automatically identifies the type of data for us.

a = 71 #Identifies a as class<int> b = 88.44 #Identifies b as class<float> name = “Raushan” #Identifies name as class<Str>

Rules for defining a variable name: (Also applicable to other identifiers)

Examples of few valid variable names,

Raushan, raushan, one8, _akki, aakash, raushan_bro, etc.

Operators in Python

The following are some common operators in Python:

  1. Arithmetic Operators (+, -, *, /, etc.)
  2. Assignment Operators (=, +=, -=, etc.)
  3. Comparison Operators (==, >=, <=, >, <, !=, etc.)
  4. Logical Operators (and, or, not)

type() function and Typecasting

type function is used to find the data type of a given variable in Python.

a = 31
  
  type(a)                      #class<int>
  
  b =31type(b)                      #class<str>

A number can be converted into a string and vice versa (if possible)

There are many functions to convert one data type into another.

Str(31)           # ”31” Integer to string conversion
  
  int(32)       # 32 String to int conversion
  
  float(32)       #32.0 Integer to float conversion

… and so on

Here “31” is a string literal, and 31 is a numeric literal.

input() function

This function allows the user to take input from the keyboard as a string.

a = input(“Enter name”)               #if a is “Raushan”, the user entered Raushan

Note: The output of the input function is always a string even if the number is entered by the user.

Suppose if a user enters 34, then this 34 will automatically convert to “34” string literal.

Chapter 2 – Practice Set

  1. Write a Python program to add two numbers.
  2. Write a Python program to find the remainder when a number is divided by Z(Integer).
  3. Check the type of the variable assigned using the input() function.
  4. Use a comparison operator to find out whether a given variable a is greater than b or not. (Take a=34 and b=80)
  5. Write a Python program to find the average of two numbers entered by the user.
  6. Write a Python program to calculate the square of a number entered by the user.

Chapter 3 – Strings

The string is a data type in Python.

A string is a sequence of characters enclosed in quotes.

We can primarily write a string in three ways:

  1. Single quoted strings : a = ‘Raushan’
  2. Double quoted strings : b = “Raushan”
  3. Triple quoted strings : c = ’’’ Raushan ’’’

String Slicing:

A string in Python can be sliced for getting a part of the string.

Consider the following string:

StringSlicing

The index in a string starts from 0 to (length-1) in Python. To slice a string, we use the following syntax:

StringSlicing

Negative Indices: Negative indices can also be used as shown in the figure above. -1 corresponds to the (length-1) index, -2 to (length-2).

Slicing with skip value

We can provide a skip value as a part of our slice like this:

word = “amazing”
  
  word[1:6:2]           # It will return ’mzn’

Other advanced slicing techniques

word = ‘amazing’
  
  word[:7] or word[0:7]      #It will return ‘amazing’
  
  word[0:] or word[0:7]      #It will return ‘amazing’

String Functions

Some of the most used functions to perform operations on or manipulate strings are:

  1. len() function : It returns the length of the string.
len(‘Raushan’)               #Returns 7
  1. endswith(“han”) : This function tells whether the variable string ends with the string “han” or not. If string is “Raushan”, it returns for “han” since Raushan ends with han.
  2. count(“a”) : It counts the total number of occurrences of any character.
  3. capitalize() : This function capitalizes the first character of a given string.
  4. find(word) : This function finds a word and returns the index of first occurrence of that word in the string.
  5. replace(oldword, newword) : This function replaces the old word with the new word in the entire string.

Escape Sequence Characters:

Sequence of characters after backslash ‘\’ [Escape Sequence Characters]

Escape Sequence Characters comprises of more than one character but represents one character when used within the string.

Examples: \n (new line), \t (tab), \’ (single quote), \\ (backslash), etc.

Chapter 3 – Practice Set

  1. Write a Python program to display a user-entered name followed by Good Afternoon using input() function.
  2. Write a program to fill in a letter template given below with name and date.
letter = ‘’’ Dear <|NAME|>,
  
                          You are selected!
  
                          <|DATE|>
  1. Write a program to detect double spaces in a string.
  2. Replace the double spaces from problem 3 with single spaces.
  3. Write a program to format the following letter using escape sequence characters.
letter = “Dear Raushan, This Python course in nice. Thanks!!”

Chapter 4 – Lists and Tuples

Python Lists are containers to store a set of values of any data type.

friends = [‘Apple’, ‘Akash’, ‘Rohan’, 7, False]

The list can contain different types of elements such as int, float, string, Boolean, etc. Above list is a collection of different types of elements.

List Indexing

A list can be index just like a string.

L1 = [7, 9, ‘Raushan’]
  
  L1[0]7
  
  L1[1]9
  
  L1[70] – Error
  
  L1[0:2][7,9]         (This is known as List Slicing)

List Methods

Consider the following list:

L1 = [1, 8, 7, 2, 21, 15]
  1. sort() – updates the list to [1,2,7,8,15,21]
  2. reverse() – updates the list to [15,21,2,7,8,1]
  3. append(8) – adds 8 at the end of the list
  4. insert(3,8) – This will add 8 at 3 index
  5. pop(2) – It will delete the element at index 2 and return its value
  6. remove(21) – It will remove 21 from the last

Tuples in Python:

A tuple is an immutable (can’t change or modified) data type in Python.

a = ()              #It is an example of empty tuple
  
  a = (1,)           #Tuple with only one element needs a comma
  
  a = (1, 7, 2)   #Tuple with more than one element

Once defined, tuple elements can’t be manipulated or altered.

Tuple methods:

Consider the following tuple,

a = (1, 7, 2)
  1. count(1) – It will return the number of times 1 occurs in a.
  2. index(1) – It will return the index of the first occurrence of 1 in a.

Chapter 4 – Practice Set

  1. Write a program to store seven fruits in a list entered by the user.
  2. Write a program to accept the marks of 6 students and display them in a sorted manner.
  3. Check that a tuple cannot be changed in Python.
  4. Write a program to sum a list with 4 numbers.
  5. Write a program to count the number of zeros in the following tuple:
a = (7, 0, 8, 0, 0, 9)

Chapter 5 – Dictionary and Sets

Dictionary is a collection of key-value pairs.

Syntax:

''' a = {“key”: “value”,
  “Raushan”: “code”,
  “marks” : “100”,
  “list”: [1,2,9]}
  a[“key”]	# Prints value
  a[“list”] 	# Prints [1,2,9] '''
  

Properties of Python Dictionaries

  1. It is unordered
  2. It is mutable
  3. It is indexed
  4. It cannot contain duplicate keys

Dictionary Methods

Consider the following dictionary,

a = {“name”: “Raushan”,from: “India”,
      “marks”: [92,98,96]}
  1. items() : returns a list of (key,value) tuple.
  2. keys() : returns a list containing dictionary’s keys.
  3. update({“friend”: “Sam”}) : updates the dictionary with supplied key-value pairs.
  4. get(“name”) : returns the value of the specified keys (and value is returned e.g., “Raushan” is returned here)

More methods are available on docs.python.org

Sets in Python

Set is a collection of non-repetitive elements.

S= Set()          # No repetition allowed!
  
  S.add(1)
  
  S.add(2)
  
  # or Set = {1,2}

If you are a programming beginner without much knowledge of mathematical operations on sets, you can simply look at sets in python as data types containing unique values.

Properties of Sets

  1. Sets are unordered # Elements order doesn’t matter
  2. Sets are unindexed # Cannot access elements by index
  3. There is no way to change items in sets
  4. Sets cannot contain duplicate values

Operations on Sets

Consider the following set:

S = {1,8,2,3}
  1. Len(s) : Returns 4, the length of the set
  2. remove(8) : Updates the set S and removes 8 from S
  3. pop() : Removes an arbitrary element from the set and returns the element removed.
  4. clear() : Empties the set S
  5. union({8, 11}) : Returns a new set with all items from both sets. #{1,8,2,3,11}
  6. intersection({8, 11}) : Returns a set which contains only items in both sets. #{8}

SET1

Chapter 5 – Practice Set

  1. Write a program to create a dictionary of Hindi words with values as their English translation. Provide the user with an option to look it up!
  2. Write a program to input eight numbers from the user and display all the unique numbers (once).
  3. Can we have a set with 18(int) and “18”(str) as a value in it?
  4. What will be the length of the following set S:
S = Set()
  
  S.add(20)
  
  S.add(20.0)
  
  S.add(20)

What will be the length of S after the above operations?

  1. S = {}, what is the type of S?
  2. Create an empty dictionary. Allow 4 friends to enter their favorite language as values and use keys as their names. Assume that the names are unique.
  3. If the names of 2 friends are the same; what will happen to the program in Program 6?
  4. If the languages of two friends are the same; what will happen to the program in Program 6?
  5. Can you change the values inside a list which is contained in set S
S = {8, 7, 12, “Raushan”, [1, 2]}

Chapter 6 – Conditional Expressions

Sometimes we want to play pubg on our phone if the day is Sunday.

Sometimes we order Ice-cream online if the day is sunny.

Sometimes we go hiking if our parents allow.

All these are decisions that depend on the condition being met.

In python programming too, we must be able to execute instructions on a condition(s) being met. This is what conditions are for!

If else and elif in Python

If else and elif statements are a multiway decision taken by our program due to certain conditions in our code.

Syntax:

'''
  if (condition1):		// if condition 1 is true
      print(“yes”)
  elif (condition2):		// if condition 2 is true
      print(“No”)
  else:				// otherwise
      print(“May be”)
  '''
  

Code example:

a = 22
  if (a>9):
      print(“Greater”)
  else:
      print(“lesser”)

Quick Quiz: Write a program to print yes when the age entered by the user is greater than or equal to 18.

Relational Operators

Relational operators are used to evaluate conditions inside if statements. Some examples of relational operators are:

= = -> equals
  
  >=  -> greater than/equal to
  
  <=, etc.

Logical Operators

In python, logical operators operate on conditional statements. Example:

and -> true if both operands are true else false
  
  or -> true if at least one operand is true else false
  
  not -> inverts true to false and false to true

elif clause

elif in python means [else if]. If statement can be chained together with a lot of these elif statements followed by an else statement.

'''
  if (condition1):
      #code
  elif (condition 2):
      #code
  elif (condition 2):
      #code
  ….
  else:
      #code    '''
  
  • The above ladder will stop once a condition in an if or elif is met.

Important Notes:

  • There can be any number of elif statements.
  • Last else is executed only if all the conditions inside elifs fail.

Chapter 6 – Practice Set

  1. Write a program to find the greatest of four numbers entered by the user.
  2. Write a program to find out whether a student is pass or fail if it requires a total of 40% and at least 33% in each subject to pass. Assume 3 subjects and take marks as an input from the user.
  3. A spam comment is defined as a text containing the following keywords:

“make a lot of money”, “buy now”, “subscribe this”, “click this”. Write a program to detect these spams.

  1. Write a program to find whether a given username contains less than 10 characters or not.
  2. Write a program that finds out whether a given name is present in a list or not.
  3. Write a program to calculate the grade of a student from his marks from the following scheme:
90-100 Ex
80-90 A
70-80 B
60-70 C
50-60 D
<50 F
  1. Write a program to find out whether a given post is talking about “Raushan” or not.