Thursday, November 30, 2023

CHAPTER 8 PYTHON LIBRARY SERIES- MATPLOTLIB

A well-known Python library for producing interactive, animated, and static visualizations in a range of formats is called Matplotlib. It is appropriate for a variety of data visualization jobs since it offers an extensive and adaptable collection of charting capabilities.  It is important because of a few main reasons. Easy to Use: Matplotlib offers a straightforward and user-friendly interface for making a large range of plots and charts. Since the syntax is simple, both novice and seasoned coders can understand it.

Versatility: A wide variety of plot types, including as line plots, scatter plots, bar plots, pie charts, histograms, and more, are supported by Matplotlib. Because of its adaptability, users can produce almost any type of interactive, animated, or static graphic. Publication-Quality Plots: Matplotlib is made to produce plots that are suitable for publication. For scientists, researchers, and analysts who have to clearly and aesthetically communicate their findings, this is essential.

To install matplotlib library , execute the following code:

pip install matplotlib

The manager called an analyst robot and asked him to give a report -Year vs Volume- based on the data. The Datasheet is attached herewith. To access the CSV file, click here: https://drive.google.com/file/d/11VY93C6fKN1Jxm33-ti1O-sT0aza2l8D/view?usp=sharing

The analyst robot decided to draw the graphs in two different ways and give them to the manager. First way, bar graph and second way, scatter plot.
# Bar graph report: Program Begins Here. 
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
# Load data from the CSV file
file_path = 'ext_list_Novembertions.csv'
data = pd.read_csv('D:\Education Content-2\Apple\Books\pyhthon folder\ext_list_Novembertions.csv')
# To know the file details, show the first 4 or 5 rows of the data.
print(data.head())
# Create a bar plot
plt.bar(data['Year'], data['Volume'])
# Add labels and title
plt.xlabel('Year')
plt.ylabel('Volume')
plt.title('Bar Chart using CSV file')
# show the chart.
plt.show()
Output
Sourcerecord ID Source Title (newly added titles are highlighted in red) \
0 19700182619 Academic Journal of Cancer Research
1 19300157018 Academy of Accounting and Financial Studies Jo...
2 19700175174 Academy of Entrepreneurship Journal
3 19700175175 Academy of Marketing Studies Journal
4 19700175176 Academy of Strategic Management Journal
Print-ISSN E-ISSN Publisher \
0 19958943 NaN International Digital Organization for Scienti...
1 10963685 NaN Allied Business Academies
2 10879595 15282686.0 Allied Business Academies
3 10956298 15282678.0 Allied Academies
4 15441458 19396104.0 Allied Business Academies
Reason for discontinuation Year Volume Issue Page range
0 Publication Concerns 2013 6 2 84-89
1 Publication Concerns 2021 25 6 001-020
2 Publication Concerns 2024 27 5 001-021
3 Publication Concerns 2016 20 3 73-88
4 Publication Concerns 2025 20 5 001-024



# Scatter graph report: Program Begins Here. 
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

# Load data from the CSV file
file_path = 'ext_list_Novembertions.csv'
data = pd.read_csv('D:\Education Content-2\Apple\Books\pyhthon   folder\ext_list_Novembertions.csv')

# Create a Scatter plot
plt.scatter(data['Year'], data['Volume'])
# Add labels and title
plt.xlabel('Year')
plt.ylabel('Volume')

plt.title('scatter Chart using CSV data')
# Display the scatter plot
plt.show()
OUTPUT: 

#Scatter plot can be drawn normally without CSV file see below           example.
import matplotlib.pyplot as plt
import numpy as np

# Produce arbitrary information for the scatter plot.
np.random.seed(42)
#seed means what? Setting the random number generator's seed in   Python, notably when utilizing the NumPy library (np is a frequent  alias for NumPy), is done with the np.random.seed(42) line. This      holds implications for reproducible random number generation.
#More specifically, this means: Creating Random Numbers:             Although the numbers produced by #computers seem random,         algorithms are frequently used to generate them.
#A seed is the initial value used by these algorithms; if you use the      same seed, the sequence of "random" numbers will be the same.
Replicability: You may make sure that you get the same random number sequence each time you run your program by setting the seed to a specific value, in this example 42.


x_values = np.random.rand(50)  

#total  number of random x values is 50.
y_values = 2 * x_values + 1 + 0.1 * np.random.randn(50)  

# y values are chosen.
print(x_values)
print(y_values)
# to draw scatter plot
plt.scatter(x_values, y_values, label='Scatter Plot', color='blue', marker='o')
# for adding  title and label 
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Here the scatter plot')

# To add a legend
plt.legend()
# show the scatterplot
plt.show()
OUTPUT :
[0.37454012 0.95071431 0.73199394 0.59865848 0.15601864 0.15599452
0.05808361 0.86617615 0.60111501 0.70807258 0.02058449 0.96990985
0.83244264 0.21233911 0.18182497 0.18340451 0.30424224 0.52475643
0.43194502 0.29122914 0.61185289 0.13949386 0.29214465 0.36636184
0.45606998 0.78517596 0.19967378 0.51423444 0.59241457 0.04645041
0.60754485 0.17052412 0.06505159 0.94888554 0.96563203 0.80839735
0.30461377 0.09767211 0.68423303 0.44015249 0.12203823 0.49517691
0.03438852 0.9093204 0.25877998 0.66252228 0.31171108 0.52006802
0.54671028 0.18485446]
[1.8229269 2.91856544 2.45242306 2.1672066 1.16418508 1.24000462
1.07010335 2.83806451 2.23659185 2.23984114 1.07357739 2.90131148
2.59719308 1.48584585 1.46674989 1.45993703 1.52456273 2.01859163
1.89701638 1.68001279 2.17578837 1.26042182 1.4736558 1.61310302
1.99339255 2.70597593 1.39214655 2.12882217 2.22099274 1.02838885
2.25122926 1.4948519 1.12652058 3.05423544 2.66928956 2.69898495
1.61793225 1.16544349 2.37764213 1.6815481 1.22210928 2.02606508
1.21656645 2.76681378 1.4367106 2.27486886 1.71496236 2.07301115
2.04044454 1.42103565]

HISTOGRAM 
Large datasets that reflect measurements, observations, or simulation results are frequently worked with by engineers. Histograms give engineers a visual depiction of the data distribution, assisting them in recognizing underlying trends and patterns. The frequency of various events or values within a dataset is shown via histograms. Finding trends and anomalies is important for engineers since it helps them concentrate on areas that could need maintenance or additional research. The manager currently provides two CSV files and wants to retrieve the following information from the analyst robot. Analyst Robot takes the effort to do so. To get these files: https://drive.google.com/drive/folders/1O6OFRmHvCEP6KmFDUlEOTuKBAth0K4ao?usp=sharing In the first CSV file, calculate the temperature of a city, and visualize how the temperature of that city has varied over the last 10 years. In the second CSV file, it needs to calculate how much rainfall has been in that city over the last few years. Analyst Robot uses the Instagram tool to calculate the minimum and maximum values of only one piece of data in these two CSV files, temperature and rainfall. The following example illustrates the answer.

#Histogram Example for Temperature ditribution import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # Load data from a CSV file. file_path = 'Rajasthan_1990_2022_Jodhpur.csv' dfram = pd.read_csv('D:\Education Content-2\Apple\Books\pyhthon folder\Rajasthan_1990_2022_Jodhpur.csv') # retrive the values column from the csv file tavg = dfram['tavg'] # Using Matplotlib plt.hist(tavg, bins=20, color='blue', alpha=0.7) # Add labels and title plt.xlabel('Average Temperature') plt.ylabel('Frequency') plt.title('With Matplotlib, Histogram Example for Temperature distribution') #display the plot plt.show()

OUTPUT:

#Histogram Example for Rainfall ditribution
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Load data from a CSV file.
file_path = 'Rajasthan_1990_2022_Jodhpur.csv'
dfram = pd.read_csv('D:\Education Content-2\Apple\Books\
pyhhon folder\district wise rainfall normal1.csv')
# retrive the values column from the csv file
JAN = dfram['JAN']
# Using Matplotlib
plt.hist(JAN, bins=20, color='blue', alpha=0.7)
# Add labels and title
plt.xlabel('rainfall')
plt.ylabel('Frequency')
plt.title('With Matplotlib, Histogram Example for Rainfall distribution')
#display the plot
plt.show()


OUTPUT:









Monday, November 27, 2023

QUIZ- CHAPTER 2 LEARN VARIABLES

 To practice the QUIZ-CHAPTER 2 LEARN VARIABLES, click or copy and paste the link in the new browser tab. 

https://forms.gle/bTuwYbSuqZ7ZGDsVA


1. bossword = ("Jony, you must go to the shop. Here are the items you need to buy:                  

    "+str(coconut_nos)+" coconuts, "+str(apple_kgs)+" kilogram of apple, "+str(ghee_litres)+" liters of          ghee and "+str(coco_oil_litres)+" of coconut oil. You should buy this half liter of coconut oil only          if you have money. I will give you "+str(money_rs)+" rupees")

       Is this correct code in python? 

a)correct, only when +str(variable name)+ term is defined.

b)correct

c)None of above


2.   [In]list_items=["coconut","ghee","coconut oil"]

       [In]total_items=len(list_items)

       [In]total_items

        The output is:___________

a)1

b)0

c)2

d)3

3.    [In]price_items={"2 coconuts":70,"1 kg apple":200,"1 liter ghee":50,"0.5 liter coconut oil":75}

       #jony gets the total price.

       [In]total_price=sum(price_items.values())

        [In]total_price

        The output is________

a)350

b)395

c)400

d)300

4.     As soon as a value is assigned to a Python variable, it is created.

a)TRUE

b)FALSE

5.    Special characters are not allowed in variable names. A $ (dollar symbol) and _ (underscore) are             the sole exceptions.

a)TRUE

b)FALSE

6. Python variables are case-sensitive.

a)true

b)false

7.  dic={1:'apple'2:’mango’,3:’jack’}

     dic[4]=’banana’

     the value of variable 'dic' now becomes

a){1:'apple'2:’mango’,3:’jack’}

b){1:'apple'2:’mango’,3:’jack’,4:'banana'}

c){4:'banana',1:'apple'2:’mango’,3:’jack’}

  d)none of above


Thursday, November 23, 2023

QUIZ: CHAPTER 1- LEARN DATATYPES IN PYTHON


To practice the QUIZ, click or copy and paste the link in the new browser tab. 

https://forms.gle/ttzbq1GZSUjFewt49 

 1. A group of letters from the source character set that are encased in double       quotation marks is known as a ________________

a)string word

b)string literal

c)string object

d)string datatype

2. Literal refers to _______________and other values passed to variables. 

a)numbers

b)strings

c)characters

d)All the above

3. Variables are the memory locations where literals were saved.

a)TRUE

b)FALSE

4. What is the output for this code: 

     [In]Janu_word=“Today” + “any”

     [In]Janu_word

a)Today+any

b)Todayany

c)Today  any

d)todayany

5. What is the output for this code: 

      [In] waterperplant="1.5"

      [In]waterperplant

      [Out]1.5

      [In]type(waterperplant)

a)string

b)integer

c)float

d)boolean

6. Does Janavi have work today? or not.  The anwer can be identified as datatype of ‘__________’.

a)string

b)integer

c)float

d)boolean

7. Square brackets can access string components.

    import array as arr

    numbersinstory=(1,4,6,"plant")

    print(numbersinstory[0])

    The output for the above shown code:

a)4

b)1

c)6

d)plant

8. Lists are used to hold several elements in a single variable.

a)True

b)False

9. KEY and VALUES are mutually connected at least with one pair. Example: Mom                   assigned 1 task, bought 4 plants and asked to pour 1.5 liters of water per plant. Find the         right form for dictionary datatype.

a)event=['task':1, 'plant':4, 'waterperplant':1.5]

b)event=('task':1, 'plant':4, 'waterperplant':1.5)

c)event={'task':1, 'plant':4, 'waterperplant':1.5}

d)none of all

10.  The data in 'set' datatype is unsorted, unchangeable, and cannot be indexed.

a)True

b)False

Sunday, October 29, 2023

CHAPTER 2 LEARN VARIABLES

LEARN PYTHON THROUGH SERIES OF ROBOT'S ACTIVITIES

 

Jony is a robot. Her boss lady has given Jony a job today. Jony's boss lady orders him to go to the store and buy some things. "Jony, you must go to the shop. Here are the items you need to buy: two coconuts, one kilogram of apple, three liters of ghee, and half a liter of coconut oil. You should buy this half liter of coconut oil only if you have money. I will give you 500 rupees“, Shaking her head yes, she scanned the paper around her eyes, compared the items on the list with the list of items she heard with her ears, and decided in two seconds that it was ok and started to go to the store.

# Jony’s boss lady said a few words and it can be the string data type. It can be represented in Python as below with a variable name with (“ …… ”) symbol.

[In]bossword = ("Jony, you must go to the shop. Here are the items you need to buy: two coconuts, one kilogram of apple, three liters of ghee, and half a liter of coconut oil. You should buy this half liter of coconut oil only if you have money. I will give you 500 rupees")

#Jony wants to count the letters in the statement given by his boss lady.

#Jony uses the following comment.

[In]len(bossword)

[Out]254

#Jony wants to store the numbers in a different location, whereas, in the previous comment the whole statement was stored in a single variable named ‘bossword’. 

[In]coconut_nos=2

[In]apple_kgs=1

[In]ghee_litres=3

[In]coco_oil_litres=0.5

[In]money_rs= 500

The code can also be written as below. 

[In]bossword = ("Jony, you must go to the shop. Here are the items you need to buy: "+str(coconut_nos)+" coconuts, "+str(apple_kgs)+" kilogram of apple, "+str(ghee_litres)+" liters of ghee and "+str(coco_oil_litres)+" of coconut oil. You should buy this half liter of coconut oil only if you have money. I will give you "+str(money_rs)+" rupees")

[In]bossword

[Out] 'Jony, you must go to the shop. Here are the items you need to buy: 2 coconuts, 1 kilogram of apple, 3 liters of ghee, and 0.5 of coconut oil. You should buy this half liter of coconut oil only if you have money. I will give you 500 rupees'

She carefully separated what kind of data she was given, namely integers 2 coconuts: the number 2 is an integer, a kilogram of apples is one, three liters of oil is an integer, and finally 1.5 liters of coconut oil is a decimal number (float). Now, she kept her master's commands as a string in her memory and also took a list of ingredients, coconut: two, apple: one kg, more ghee: one liter, coconut oil: 1.5, and operator.

# check the datatypes of each value

#list the values and index all

After tabulating the products and asking the shopkeeper for a price list, calculate the total price of 500 rupees and give it to the shopkeeper, if there is any leftover, buy one and a half liters of coconut oil.

#Jony is now preparing to go to the shop. She listed the items to buy first, then count the items.

[In]list_items=["coconut","ghee","coconut oil","apple"]

[In]total_items=len(list_items)

[In]total_items

[Out]4

 

The calendar was included in the table and the price of the other items that the shopkeeper paid would correspond to the prices of the other items.

#Jony includes the calendar and the shop id using the dictionary datatype to verify the transaction details later.

[In]shoping_details={"shopid":234, "date":"04:02:2022"}

[In]shoping_details

{'shopid': 234, 'date': '04:02:2022'}

shoping_details["date"]

'04:02:2022'

Jony patiently asked the shopkeeper to tell her the price of the items. Further, She said, "If there is a balance, I will take the items away, I will give you the price list". Shopkeeper said ok, she calmed down, and counted the items, the number of items on the list and the number of items he was keeping was correct, ok, She waited for the price list, the price list said 475, so there are only 25 rupees left, for 25 rupees, She can buy a coconut.

#shopkeeper told Jony the price items.

[In]price_items={"2 coconuts":30,"1 kg apple":250,"1 liter ghee":55,"0.5 liter coconut oil":75}

#jony gets the total price.

[In]total_price=sum(price_items.values())

[In]total_price

[Out]410

The shopkeeper asked how much coconut oil Jony wants. Jony wants 1.5 liters. If it is less than 25 rupees, give her the rest. If not, She explained that only 25 rupees is enough.

#now jony calculates the balance price.

[In]total_price=410

[In]money_rs=500

[In]bal_price=money_rs-total_price

[In]bal_price

[Out]90

 

Robots can use different types of programming languages. Jony uses Python language. Now she explains how Johnny fulfilled his duty perfectly. "I first recorded in my memory the words spoken by my master.

I made a separate note of the numbers marked in them and put in a table the objects connected with them. Before that, I saved in written form the long statement made by her boss lady.

Now when I visit a store I save the store ID in my memory. Also, I have added the store name along with the store ID. I will also include the location of the store.

Now what I need to do is to know if there are any approaches in this shop I go to that shop, and now the shopkeeper asked Jony, "Jony you have already loaned Rs 10 on a specified date last week and now you have to pay it". Jony couldn't make up his mind because boss lady didn't give her any information about this, after a while she said no you give me 1.5 liters for the remaining amount, I will give this 10 rupees when I come back next time. For my mistress did not tell me these particulars, although I have noted them in my memory. After getting the approval for it, I will give it when I come next time”.

INTRODUCTION TO ROBOT'S PYTHON

LEARN PYTHON THROUGH SERIES OF ROBOT'S ACTIVITIES

 Artificial Intelligence (AI) is the futuristic technology that promises to be amazing. In the current environment, everyone needs to learn about machine learning and artificial intelligence. In the realm of artificial intelligence (AI), a computer is comparable to a well-manicured paddy field. Therefore, managing a farming estate does not require extensive knowledge of the art of land cultivation. With the right knowledge on what to plant and how to care for it, he can become the greatest farmer. Similar to this, even if a person is not a skilled programmer, they may still use AI and ML algorithms to create computer applications provided they know what kind of software to create and are enthusiastic about computers. This could be the digital era's future vision.

Learn Python to grow yourself further in AI and ML technologies and, you will become an AI and ML enthusiast soon after you read this blog.       

Source codes will be forwarded to you based on your request.  

The Jupiter Notebook was used to create all of the codes (Python programs) in this book. Jupiter Python can be easily installed on your computer/laptop using the link attached here.

1. https://www.python.org/downloads/

2. https://jupyter.org/install

           In these programs, the input is denoted by the letter [In], and the output is indicated next to the word [Out]. For getting output, users have to hit the ‘Enter’ button. The statements starting with the ‘#’ symbol are only for demonstration purposes and do not execute during the run command.

 

All lines must be properly indented in the program. For every Chapter, more than one event/ situation/ incident is elaborated on using examples of real-world problems. In each chapter of this blog, an example event or chaotic situation is given and explained. In each case/example, we need to tell a robot how to help us through the Python language.

CHAPTER 7 LEARN CLASS IN PYTHON

 LEARN PYTHON THROUGH SERIES OF ROBOT'S ACTIVITIES 

A user-defined class serves as a template or prototype from which objects can be built. Classes offer a way to group functionality and data. A new class produces a new type of object, enabling the creation of new instances of that type. Each instance of a class may have characteristics connected to it to preserve its state. Class instances may also contain methods for changing their state that is defined by their class. Sana is working as a professor in a college. Sana had ordered the robot named Tana, to monitor students of her college to improve the educational methods, that is to say,

how well the students have learned the content of each subject by conducting a series of tests or exams on each student.

 

Sana gives the marks obtained by the student to the robot, Tana, and similarly gives the completed question paper to the robot. At present questions are asked from 5 subjects of 20 marks each from each subject.

 

The function of this task is to assess whether the content of all 5 subjects is well understood by the students based on how much each student has scored in these 5 subjects.

To do this, the robot needs information about how each student wrote the answers to the related questions in the 5 subjects,

and the robot has to calculate the percentage of the student's score in each subject and convert it into a percentage and submit it to the professor.

The job of Tana is to get the given data, and marks of the students and, at the same time take the marks of the students in each subject separately and convert it into percentages and get the learning percentage of each subject.

Program 1:

[In]Class Student():

    def __init__(self, name, roll, gen):

        self.name=name

        self.roll=roll

        self.gen=gen

    def show(self):

        print("The student details are: Name :",  self.name, ", Roll No: ", self.roll, ", Gender: ", self.gen)

#This comment prints the student details.

[In]class Student():

    def __init__(self, name, roll, gen):

        self.name=name

        self.roll=roll

        self.gen=gen

    def show(self):

        print("The student details are: Name :",  self.name, ", Roll No: ", self.roll, ", Gender: ", self.gen)

stu1=Student('raj',123,"male")

stu1.show()

[Out]The student details are: Name : raj , Roll No:  123 , Gender:  male

[In]class Science(Student):

    def __init__(self, name, roll, gen):

        super().__init__(name, roll, gen)

        self.marks1=0

        self.marks2=0

    def test1marks(self, score1):

        self.score1=score1

        self.marks1 = self.marks1+ self.score1

        [In]print("The test 1 marks updated", self.marks1)

    def test2marks(self, score2):

        self.score2=score2

        self.marks2 = self.marks2+ self.score2

        [In]print("The test 2 marks updated", self.marks2)

[In]stu1=Science('raji',123,'female')

[In]stu1.test1marks(100)

[Out]The test 1 marks updated 100

[In]stu1.test2marks(10)

[Out]The test 2 marks updated 10

Program 2:

In the second example, A shopkeeper has to calculate the total price for 3 items bought by a customer. The 3 items are moong, oil, and vegetables. The program is very simple to make a class program that contains different functions such as _init_, and price. The output of this program executes the price function with the prices of all the groceries. This is available in the Ingredients class. The values of prices are passed to the Ingredients class.

[In] class Ingredients:

    def __init__(self, m,o,c):

        self.m=m

        self.o=o

        self.c=c

    def price(self):

        tot= self.m + self.o + self.c

        print("The total price is Rs.", tot)

p=Incredients(45,34,4)

p.price()

​[Out] The total price is Rs.  83

The next program explains the functions of a class with more than one function.

[In]class Ingredients:

def unitprice(self,moong,oil,veg):

        self.moong=moong self.oil = oil

        self.veg = veg

        print("The unitprice of moong is Rs",self.moong)

        print("The unitprice of oil is Rs",self.oil)

        print("The unitprice of veg is Rs",self.veg)

def quantity(self,moonquan=float,oilquan=float, vegquan=float):

        self.moonquan=moonquan

        self.oilquan = oilquan

        self.vegquan = vegquan

        print("The quantity of moong is ",self.moonquan,"kg")

        print("The quantity of oil is ",self.oilquan,"kg")

        print("The quantity of veg is ",self.vegquan,"kg")

def price(self,m=float,o=float,v=float,tot=float):

        m=self.moong*self.moonquan

        o=self.oil*self.oilquan

        v=self.veg*self.vegquan

        self.m =m

        self.o =o

        self.v =v

        tot= self.m+self.o+self.v

        print("The total price of the groceries is Rs. ",tot)

p=Incredients()

p.unitprice(1,4,4)

p.quantity(0.5,1,4)

p.price()

[Out] The unitprice of moong is Rs 1

The unitprice of oil is Rs 4

The unitprice of veg is Rs 4

The quantity of moong is  0.5 kg

The quantity of oil is  1 kg

The quantity of veg is  4 kg

The total price of the groceries is Rs.  20.5

 

 

 

CHAPTER 6 LEARN FUNCTIONS

 LEARN PYTHON THROUGH SERIES OF ROBOT'S ACTIVITIES 

To repeat a particular action, reducing the generation of codes each time, and reusing codes generated once, is called operations in computer language. Activities are an event in which an action is initiated and completed within a specified time frame and this event is completed through specified procedures. For example, activities such as going to the store, returning from the store, writing an essay, and cooking can be considered. A shopping activity consists of various small tasks. Decide what to buy, decide how much of each item to buy, decide how much money you need to have, learn about giving money and buying the balance, get it all into a bucket, and take it home again.

This example shows how a robot can complete household chores promptly as an operation. Similarly, other operations may have several smaller tasks and conditions attached to them, such that when a robot is given a command, the commands are executed one after the other, and an operation is completed.

 

Ironing, Washing, Playing, Walking, Brushing, Gardening, Reading, Shopping, Cleaning the home, Cooking, Cleaning the kitchen, and singing.

Ironing function

    [In]def iron():

       dress_type=input("get the type of dress   ")

        dress_typelist=dress_type.split()

        print(dress_typelist)

        for x in dress_typelist:

            if x == "cotton":

           print("Maintain temperature at 60 deg")

                print("iron is over")

            elif x== "velvet":

            print("Maintain temperature at 30 deg")

                    print("iron is over")

            else:

                print("select correct cloth")

    [In]iron()

    [Out]get the type of dress   velvet

    ['velvet']

    [Out]Maintain temperature at 30 deg

    [Out] iron is over

    #Running the function again.

    [In]iron()

    [In]get the type of dress   cotton

    ['cotton']

    [Out]Maintain temperature at 60 deg

    [Out]iron is over

        #Running the function again.

 [In]iron()

    [In]get the type of dress   polyester

    ['polyester']

    [In]select correct cloth

Washing function

    #washing job

    def wash():

no_ofcloth=int(input("enter the no of dresses  "))

        while no_ofcloth<6:

            if no_ofcloth<3:

                waterlow=int(input("get the low water level   "))

                print("motor on. finish wash")

            else:

                waterhigh=int(input("get the high water level   "))

                print("motor on. finish wash")

            break

        else:

            print("get the low no of dresses")

    #Running the function.

    [In]wash()

    [In]enter the no of dresses  2

    [In]get the low water level   4

    [In]motor on. finish wash

    #Running the function again.

    [In]wash()

    [In]enter the no of dresses  5

    [In]get the high water level   5

    [In]motor on. finish wash

    #Running the function again.

    [In]wash()

    [In]enter the no of dresses  7

    [In]get the low no of dresses

    Autonomous Car Driving

         The following decisions were made before the car has to be moved from one place to another place. There were 4 sensors located beside the wheels of the car. If any sensor input is 0, no obstacle is assumed, False condition. If any sensor detects an obstacle, then the sensor input will be 1, True.

[In] def drive1():

         fls=str(input("front left sensor input   "))

         frs=str(input("front right sensor input   "))

    def forwbreak():

           print("stop the forward vehicle, apply brake")

    def forwacce():

         print("forward acceleration on")

    def forright():

        print("steer right")

    def forleft():

        print("steer left")

    def revbreak():

        print("stop the reversed vehicle, apply brake")

    def revacce():

        print("steer 4")

    if fls == "1" and frs == "1":

            forwbreak()

    elif frs=="1" and fls=="0":

            forleft()

    elif fls=="1" and frs=="0":

            forright()

    elif fls == "0" and frs == "0":

            forwacce()

    return

#When the function runs, based on the decision the car will be driven.

[In]drive1()

    front left sensor input   1

    front right sensor input   0

    steer right

[In] drive1()

    front left sensor input   1

    front right sensor input   1

    stop the forward vehicle, apply the brake

[In] drive1()

    front left sensor input   0

    front right sensor input   1

    steer left

[In]drive1()

    front left sensor input   0

    front right sensor input   0

    forward acceleration on

   #This example shown below is the function drive(), that is using 2 sensors. These 2 sensors will get the input from the user. As per user input, the decisions will be made. 

def drive():

        get_sendata=input(" the sensor data    ")

        sendata = get_sendata.split(",")

        print(sendata)

        a=type(sendata)

        b=len(sendata)

        print(a)

        print(b)

        a1=sendata[0]

        b2=sendata[1]

        print(a1)

        print(b2)

        if a1=="0" and b2=="1":

            print("turn left")

        elif a1=="1" and b2=="0":

            print("turn right")

        elif a1=="0" and b2=="0":

            print("accelerate")

        elif a1=="1" and b2=="1":

            print("stop the car")

        return

    When program runs

[In]drive()

    [Out] the sensor data    0,0

    ['0', '0']

    <class 'list'>

    [Out] 2

    [Out] 0

    [Out] 0

    Accelerate

[In]drive()

 

 

[Out] the sensor data    1,1

    ['1', '1']

    <class 'list'>

    [Out] 2

    [Out] 1

    [Out] 1

    [Out] stop the car

Practice Problem

If 4 sensors are fitted in a car, then the following program will be used.

[In]def drive():

         get_sendata=input(" the sensor data    ")

         sendata = get_sendata.split(",")

         print(sendata)

    #a1=front left , b2= front right, c3=rear right,     

        d4=rear left sensors.

        a=type(sendata)

    b=len(sendata)

    print(a)

    print(b)

    a1=sendata[0]

    b2=sendata[1]

    c3=sendata[2]

    d4=sendata[3]

    print(a1)

    print(b2)

    print(c3)

    print(d4)

    if ((a1=="0") and (c3=="0") and (d4=="0") and (b2=="1")):

        print("turn left and accelerate")

    elif ((b2=="1") and (c3=="1") and (d4=="1") and (a1=="0")):

        print("turn right and accelerate")

    elif a1=="0" and b2=="0":

        print("accelerate")

    elif c3=="1" and d4=="1":

        print("stop reverse the car")

    elif ((a1=="1") and (b2=="1") and (c3=="1") and (d4=="0")):

        print("reverse the car towards rear right")

    elif ((a1=="1") and (b2=="1") and (d4=="1") and (c3=="0")):

        print("reverse the car towards rear left")

    return

[In] drive()

[Out] the sensor data    0,0,0,1

['0', '0', '0', '1'] # list created.

<class 'list'>

4 # length of list elements, 4 elements.

0   # sensor data1

0   # sensor data2

0   # sensor data3

1   # sensor data4

accelerate

 

CHAPTER 18 EXPLORING THERMODYNAMICS WITH PYTHON: UNDERSTANDING CARNOT'S THEOREM AND MORE

  Python is a versatile programming language that can be used to simulate and analyze various physical phenomena, including thermal physics ...