LEARN PYTHON THROUGH SERIES OF ROBOT'S ACTIVITIES
In the first lesson, a
robot named Janavi works for a boss named Janu. Janu assigns Janavi chores
around the house daily. Janavi approaches the boss and inquires, "What
household chores should be completed today?" Janu told Janavi,
"Today, there is only one thing you must do, and I will tell you what it
is. I bought 4 small plants from the shop and placed them near the stairs. Take
6 liters of water along with plants to the garden, then, add fertile soils, and
plant the roots firmly on the ground. You must water all of the plants at a
rate of 1.5 liters per plant. After that, assist me with the other work if
any," she said.
From the above conversation done in the English language, the
information is shared among the two persons, Janu and Janavi. How do we perform
this task in Python language?
A group of
characters from the source character set that are encased in double quotation
marks is known as a "string literal" ("…….").
A conversation that
happened between Janu and Janavi is described as string literal, denoted within
the double quotation marks. Literal refers to numbers, strings, characters, and
other values passed to variables. Variables are the memory locations where
literals were saved. Languages used in computer science applications rely
heavily on syntax and its meanings.
Chapter 1
describes various datatypes used in Python. Here, what Janu said is given as a
string literal. First, the String- data type
is described, here the program starts:
[In]Janu_words="Today, there
is only one thing you must do, and I will tell you what it is. I bought four
small plants from the shop and placed them near the stairs. You must water all
of the plants at a rate of 1.5 liters per plant. Take 6 liters of water to the
garden and water the plants, then, water all four plants at 1.5 liters per
plant, add fertile soils and plant the roots firmly on the ground. After that,
assist me with the other work if any"
[In] Janu_words
[Out]--- (will return the same
statements) –
# If additional words or any literal are to be
#added, then the ‘+’ operator will be used.
[In]Janu_word=“Today” + “any”
[In]Janu_word
[Out]Todayany
Next to the string data type, to describe the number data type, the
following code is executed.
Janu says how many jobs are there in the beginning? Job=1. This can be
identified as Datatype ‘int’ or ‘integer’. This is the first type
of ‘Number’ datatype.
Code:
[In]Job=1
[In]Job
[Out]1
[In]type(Job)
[Out]int
How much water did
Janu ask to pour per plant? waterperplant =1.5 liters. This is the second type
of ‘number’ datatype, Float. Here is the Code to check. Code:
[In] waterperplant=1.5
[In]waterperplant
[Out]1.5
[In]type(waterperplant)
[Out]=float.
#how many plants did janu #bought?
[In] num_plant=4
[In] num_plant
[Out] 4
[In] type(num_plant)
[Out]
int
Does Janavi have work today? or not.
This can be identified as Datatype ‘bool’ or ‘boolean’. If the job is
assigned, True will be #assigned, else, False will be assigned.
Code:
[In]Job_status=True
[In]Job_status
[Out]True
[In]type(Job_status)
[Out]bool
[In]Job_status=False
[In] Job_status
[Out]False
[In]type(Job_status)
[Out]bool
#Did
janu buy 4 plants?
[In]fourplant=True
[In] fourplant
[Out] True
[In]
type(fourplant)
[Out] bool
# If Janavi not #accepted
her
#Master’s request.
[In] janavi_action=False
[In]
janavi_action
[Out] False
[In]
type(janavi_action)
[Out] bool
#Otherwise, If Janavi #accepted her Master’s #request.
janavi_action=True
An array is a collection of items that are
stored in adjacent memory locations. The idea is to group items of the same
type. This makes calculating the position of each element easier by simply
adding an offset to a base value, i.e. the memory location of the array's first
element. Arrays are not built into Python, however, Python Lists can be used
instead. Strings in Python, like numerous other well-known programming
languages, are arrays of bytes signifying Unicode characters.
However, because Python lacks a character
data type, a single character is merely a one-length string.
Square brackets can access string
components.
[In]import array as arr
[In]numbersinstory=(1,4,6,"plant")
[In]print(numbersinstory[0])
# Here 0th element is printed.
[Out]1
[In]len(numbersinstory)
[Out]4
Let us discuss another datatype, ‘list’. Lists
are used to hold several elements in a single variable.
Lists are one of four built-in data
types in Python that are used to save a set of data. The other three are
Tuples, Sets, and Dictionaries, all of which have various properties and
applications. Let us discuss them one by one.
Datatype: Lists
Mom assigned 1 task to her daughter, she
bought 4 plants, and she told her daughter to pour 1.5 liters of water per
plant and a total of 6 liters of water.
List creation using []
[In]task_details=[1,4,1.5,'4
plants','6 litres']
[In] task _details
[Out] [1, 4, 1.5, '4 plants',
'6 liters']
[In] type(task_details)
[Out] list
How to index an element in the list?
Mom asked how much water was to be used per
plant. To get the answer to this question,
[In] task_details[2]
[Out] 1.5
List indexing starts with 0. The 3rd
element will be denoted here as 2. The third element is 1.5. Mom asked how many
tasks were to be assigned to Janavi. To get the answer to this question, 0
indexing must be used.
[In] task_details[0]
[Out] 1
Mom asked how much water was to
be taken.
[In] task_details[-1]
[Out] '6 liters'
Here the indexing is done in
the reverse order. It is also one of the indexing methods when a large number
of elements are in the list.
How to find the length of the list.?
[In] len(task_details)
[Out] 5
How to add task_details, i.e, water or more
elements in the list.
[In] task_detais.append('water')
[In] task_details
[Out] [1, 4, 1.5, 'plants', '6
liters', 'water']
How to add job_details, i.e, water in the
first place in the list?
task_details.insert(0,'water')
# 0 indicates the first element.
[In] task_details
[Out]['water', 1, 4, 1.5, 'plants', '6 liters',
'water']
How to count the elements in the list?
[In]
task_details.count(‘water’)
[Out] 2
How to remove the elements from the list?
[In] job_detais.pop()
[Out] 'water'
[In] job_detais
[Out] ['water', 1, 4, 1.5, 'plants', '6 liters']
[In] job_detais.pop(0)
[Out] 'water'
[In] job_detais
[Out] [1, 4, 1.5, 'plants', '6 liters']
To reverse the elements.
[In] job_detais.reverse()
[In] job_detais
[Out] ['6 liters', 'plants', 1.5, 4, 1,
'water']
List
Methods for Practices:
[In]list1=[3,5,7,
"john"]
[In]print(list1[0])
[Out]
3
[In]print(list1[1])
[Out]
5
[In]print(list1[2])
[Out]
7
[In]print(list1[3])
[Out]
john
[In]list1[3]="johnny"
[Out][3, 5,
7, 'johnny', 'janu']
[In]list1.append("janu")
[In]list1
[Out][3, 5, 7,
'johnny', 'janu']
[In] list1.insert(1,"janu")
[In]
list1
[Out]
[3, 'janu', 5, 7, 'johnny', 'janu']
[In] list1.count("janu")
[Out] 2
[In] list1.pop(1)
[Out] 'janu'
[In] list1.reverse()
[In] list1
[Out] ['janu',
'johnny', 7, 5, 'janu', 3]
# Dictionary Data type :
Creation of dictionary using the below-mentioned
format: key: values & {} symbol.
KEY and VALUES are mutually connected at least with one pair.
Mom assigned 1 task, bought 4 plants and asked
to pour 1.5 liters of water per plant
[In]event={'task':1, 'plant':4, 'waterperplant':1.5}
To obtain values from the key.
[In] event['task']
[Out] 1
[In] event['plant']
[Out] 4
Datatype: Tuple
Several
items can be stored in a single variable by using tuples. One of the four
built-in data types in Python for storing data collections is the tuple; the
other three are list, set, and dictionary, each with a unique set of features
and applications.
A
tuple is an unchanging, ordered collection.
'Set' is a data type like List, Tuple, and Dictionary data type. The data
in it is unsorted, unchangeable, and cannot be indexed. Let's take a brief look
at what happened at Janu's house.
Janu first offered Janaki
a plantation job. Then, they finished their homework.
Then they ate and slept.
Let's ask some questions about this event.
How much work was given to
Janavi at home? Did the job get done? True or False. Did everyone eat at night?
True or False. How many plants did they plant? In response to this, i.e. the
answer to this can be gathered through the set.
[In] import
numpy as np
[In]import pandas as pd
[In]answer=[1, True, True, "4
plants"]
[In]type(answer)
[Out]list
#This list can be used
with values. But, a set is not allowed with duplicate values.
[In]answer = {True,
"plant"}
[In]type(answer)
[Out]set
[In]answer = {1, True, "4
plants"}
[In]answer
[Out]{1, '4 plants'}
#here in
set, 1 and true are the same or duplicates.
[In]type(answer)
[Out]set
# Group of
people such as students, employees, and teams of players can be used as a list.
The set is
having limitations in Python.
Datatype: Date time
The robot must be taught how to manage the days.
import datetime
x =
datetime.datetime.now()
print(x.strftime("%A"))
print(x.hour)
print(x.year)
if x.year>=2000:
print("20 century")
if x.hour<=12:
print("afternoon")
Homework
Home Work 1. Write the numbers of any
10 via list. Sort it, then, pop the maximum element.
[In] import numpy as np
[In]randa=list(np.random.randint
(low = 3,high=8,size=10))
[In] print(randa)
[Out][3, 6, 3, 4, 3, 4, 6, 6, 6, 4]
[In] randa.sort()
[Out] [3, 3, 3, 4, 4, 6, 6, 6]
[In] randa.pop()
[Out]6
[In] randa
[Out][3, 3, 3, 4, 4, 6, 6]
[In] randa.count(3)
[Out]3
Home Work 2. Definition of complex
numbers
Perform addition of 2+6j,
4+9j. Find the magnitude of the answer.
[In]x=2+6j
[In]type(x)
[Out]complex
[In]y=4+9j
[In]a=x+y
[In]a
[Out] (6+15j)
#another declaration
method.
[In]x=complex(2,6)
[In]x
[Out] (2+6j)
#To find the magnitude of
the answer.
[In]import math
[In]mag=math.sqrt(x.real**2 +
x.imag**2)
[In]mag
[Out] 6.324555320336759
#another method using
abs() method.
[In]abs(x)
[Out] 6.324555320336759
Home Work 3:
After
finishing the household chores during the day, everyone got ready for dinner.
Janu's father asked for 3 idlis. Janu's mother said she wants two dosas.
She
said one dosa is enough for Janu. Janu's husband asked for two sabbaths, while
Janu's son asked for one dosa. Janu's daughter asked for 2 idlies (South Indian
Food). It is explained below how this can be explained in a dictionary form for
the machine (Jana), i.e. for Januvi.
Read
here how to teach data using a dictionary. Make it clear to the robot what
types of food to prepare for dinner and how many for each person. Everyone
chooses different types of food.
[In] food_time=input(“food_time
is now, “)
[In] print(food_time
is,+food_time)
[In] if food_time=breakfast:
food = {}
food[‘dad’] =’2 idly’
[In] food={}
[In] food['dad']='2 idly'
[In] food['mom']='1 dosa'
[In] food['bro']='1 chappati'
[In] food['sis']='fish'
[In] food
[Out] {'dad': '2 idly', 'mom': '1 dosa', 'bro': '1 chappati, 'sis':'fish'}
[In]food.get('dad')
[Out] '2idly'
[In]food.get('mom'1dosa'
[In]food.values()
[In]dict_values(['2 idly', '1 dosa', '1 chappathi','fish'])
[In]food.keys()
[In]dict_keys(['dad', 'mom', 'bro', 'sis'])
#suppose mom wants more Dosa, use the update command,
#only the value is updated.
[In]food.update({'mom':'2 dosa'})
[In]food
[Out]{'dad': '2 idly', 'mom': '2 dosa', 'bro': '1 chappathi', 'sis': 'fish'}"}
# suppose one guest is coming, and the guest wants no food,
#now use the update #command for updating both keys and values.
[In]food.update({'guest':'no food'})
[In]food
[Out]{'dad': '2 idly', 'mom': '2 dosa','bro': '1 chappathi', 'sis':'fish',
'guest': 'no food'}
#On the next day, let’s say the guest is not available for the dinner,
#then, how to pop the key and value from dict using popitem()
#command. For first-time use.
[In]food.popitem()
[In]food
[Out]{'dad': '2 idly', 'mom': '2 dosa', 'bro': '1 chappathi', 'sis': 'fish'}
#On the next day, let’s say the guest is not available for dinner, then,
#how to pop the key and value from dict using popitem() command.
#For the Second time use of popitem()
[In]food.popitem()
[Out]{'dad': '2 idly', 'mom': '2 dosa', 'bro': '1 chappathi'}
# if it is required to save the pop item separately into a variable x.
[In]x=food.popitem()
[In]x
[Out]('bro', '1 chappathi')
#for lunch all want to change the menu, then a new dict can be created
# using ‘fromkeys’ command.
# keys are familiar, family members, so will make empty dict with
#keys members=['dad', 'mom', 'bro', 'sis']
[In]fooditem=['friedrice', 'briyani', 'vegrice','chappati']
[In]food1={}
[In]newdict=food1.fromkeys(members,fooditem)
[In]newdict
[Out]{'dad': ['friedrice', 'briyani', 'vegrice', 'chappati'],
'mom': ['friedrice', 'briyani', 'vegrice', 'chappati'],
'bro': ['friedrice', 'briyani', 'vegrice', 'chappati'],
'sis': ['friedrice', 'briyani', 'vegrice', 'chappati']}
[In]type(food1)
[Out]"dict"
[In]food1.update({'dad':'friedrice', 'mom':'briyani', 'bro':'vegrice',
'sis':'chappati'})
[In]food1
[Out]{'dad': 'friedrice', 'mom': 'briyani', 'bro': 'vegrice', 'sis': 'chappati'}
[In]newdict.update({'dad':'friedrice', 'mom':'briyani', 'bro':'vegrice',
'sis':'chappati'})
[In]newdict
[Out]{'dad': 'friedrice', 'mom': 'briyani', 'bro': 'vegrice', 'sis': 'chappati'}
Summary
If we now look back at the events/stories we have studied together,
we can fully understand that we have
studied the following types of data.
1. Integer 2. Float
3. Complex
4. Strings 5. Dictionary 6. Set
4. Tuple 5. List
6. Boolean 7. Date
Type |
Mutable? |
Ordered? |
Indexed? |
List-[] |
Mutable: #3rd element is
replaced. [In]list1=[3,5,7, "john"] [In]print(list1) [ln]list1[3]="johnny" [In]list1 [Out] [3, 5, 7, 'john']
[3, 5, 7, 'johnny'] |
Ordered. # Ordered list1. list1=[3,5,7, "john"] print(list1[0]) print(list1[1]) print(list1[2]) print(list1[3]) list1[3]="johnny" list1 [Out]
3 5 7 john [3, 5, 7, 'johnny'] |
Indexed |
Dict |
Keys are immutable. |
Unordered |
Indexed |
Tuple |
Immutable |
Ordered |
Indexed |
Array |
Mutable |
Ordered |
Indexed |
Set |
Immutable |
Unordered |
Unindexed |
No comments:
Post a Comment