Introduction to Python

6. Writing and Executing First Python Program

Python सीखने का सबसे अच्छा तरीका है कि आप तुरंत अपना पहला प्रोग्राम लिखें और run करें। यह chapter step-by-step आपको पहला Python program बनाने और execute करने की प्रक्रिया सिखाएगा।


6.1 Python Program लिखना

Python program एक text file होती है जिसका extension .py होता है।
Example (Hello World Program):

# पहला Python प्रोग्राम
print("Hello, World!")

6.2 Python Program Execute करने के तरीके

(a) Using Python IDLE

  1. Python install करने के बाद IDLE open करें।
  2. Shell window में लिखें: print("Hello, Python!") और Enter दबाएँ → output मिलेगा।
  3. File → New File → code लिखें → Save as program.py → Run → Run Module (F5)।

(b) Using Command Prompt / Terminal

  1. Program को किसी text editor (Notepad, VS Code आदि) में लिखें और save करें, जैसे hello.py
  2. Command Prompt (Windows) या Terminal (Linux/Mac) open करें।
  3. File location पर जाएँ और type करें: python hello.py Output: Hello, World!

(c) Using Jupyter Notebook

  1. Anaconda या pip से Jupyter install करें। pip install notebook jupyter notebook
  2. Browser में notebook open होगा।
  3. Cell में code लिखें और Run करें: print("Hello, Jupyter!")

6.3 Inline Execution (Interactive Mode)

Python interpreter को सीधे run करके भी code लिखा जा सकता है।

python

फिर लिखें:

>>> print("Hello, Interactive Mode!")
Hello, Interactive Mode!

6.4 Example Programs

Example 1: Two Numbers Add करना

a = 10
b = 20
print("Sum =", a + b)

Output:

Sum = 30

Example 2: User Input लेना

name = input("Enter your name: ")
print("Welcome,", name)

Output:

Enter your name: Anand
Welcome, Anand

📌 Quick Note for Students:

  • हमेशा program को .py extension से save करें।
  • Beginners के लिए सबसे आसान तरीका है कि IDLE या VS Code से program run करें।
  • Execution के दौरान error आने पर error message ध्यान से पढ़ें – वही debugging की पहली step है।

String of Python

String of Python

Q1.What is a string in Python?

A. A sequence of integers
B. A sequence of characters
C. A sequence of floating-point numbers
D. A sequence of Boolean values

Answer: B

Explanation: In Python, a string is a sequence of characters enclosed in quotes. It can be defined using single quotes (‘…’) or double quotes (“…”).

Q2.Which of the following is a valid string in Python?

A. 1234
B. ‘1234’
C. 12.34
D. True

Answer: B

Explanation: ‘1234’ is a valid string in Python. A string can contain any sequence of characters, including digits, letters, and symbols.

Q3.What is the difference between single and double quotes in Python?

A. Single quotes can only be used for short strings, while double quotes can be used for longer strings.
B. Single quotes and double quotes are interchangeable.
C. Single quotes are used for strings, while double quotes are used for integers.
D. Single quotes are used for characters, while double quotes are used for strings.

Answer: B

Explanation: In Python, single and double quotes are interchangeable and can be used to define strings.

Q4.Which of the following is a valid way to concatenate two strings in Python?

A. str1 – str2
B. str1 + str2
C. str1 * str2
D. str1 / str2

Answer: B

Explanation: The + operator can be used to concatenate two strings in Python.

Q5.What is the result of the following code?

string1 = “Hello”
string2 = “World”
print(string1[1] + string2[3])

A. “Hd”
B. “eo”
C. “lW”
D. “ol”

Answer: C

Explanation: string1[1] is “e” and string2[3] is “d”, so the output is “lW”.

Q6.Which method can be used to convert a string to all lowercase letters in Python?

A. upper()
B. lower()
C. capitalize()
D. swapcase()

Answer: B

Explanation: The lower() method can be used to convert a string to all lowercase letters in Python.

Q7.Which method can be used to replace a substring in a string with a new substring in Python?

A. replace()
B. substr()
C. splice()
D. slice()

Answer: A

Explanation: The replace() method can be used to replace a substring in a string with a new substring in Python.

Q8.Which of the following is a valid way to access the length of a string in Python?

A. len(string)
B. string.length()
C. string.size()
D. length(string)

Answer: A

Explanation: The len() function can be used to access the length of a string in Python.

Q9.Which method can be used to split a string into a list of substrings based on a delimiter in Python?

A. join()
B. split()
C. replace()
D. substring()

Answer: B

Explanation: The split() method can be used to split a string into a list of substrings based on a delimiter in Python.

Q10.Which method can be used to remove whitespace from the beginning and end of a string in Python?

A. trim()
B. strip()
C. remove()
D. clean()

Answer: B

Explanation: The strip() method can be used to remove whitespace from the beginning and end of a string in Python

Q11.Which of the following is a valid way to check if a substring is present in a string in Python?

A. string.contains(substring)
B. substring.in(string)
C. string.find(substring)
D. substring.check(string)

Answer: B

Explanation: The in operator can be used to check if a substring is present in a string in Python. The correct syntax is substring in string.

Q12.Which method can be used to convert a string to a list of individual characters in Python?

A. split()
B. join()
C. list()
D. chars()

Answer: C

Explanation: The list() function can be used to convert a string to a list of individual characters in Python.

Q13.Which of the following is a valid way to format a string with variables in Python?

A. “Hello, {0} and {1}!”.format(name1, name2)
B. “Hello, %s and %s!” % (name1, name2)
C. f”Hello, {name1} and {name2}!”
D. All of the above

Answer: D

Explanation: All of the options are valid ways to format a string with variables in Python. Option A uses the format() method, option B uses the % operator, and option C uses f-strings.

Q14.Which method can be used to check if a string starts with a certain substring in Python?

A. startswith()
B. contains()
C. beginswith()
D. substr()

Answer: A

Explanation: The startswith() method can be used to check if a string starts with a certain substring in Python.

Q15.Which method can be used to check if a string ends with a certain substring in Python?

A. endswith()
B. contains()
C. finishswith()
D. substr()

Answer: A

Explanation: The endswith() method can be used to check if a string ends with a certain substring in Python.

Q16.What is string interpolation in Python?

A. The process of converting a string to a list of characters
B. The process of replacing variables in a string with their values
C. The process of encrypting a string for secure transmission
D. The process of compressing a string to save storage space

Answer: B

Explanation: String interpolation is the process of inserting variables or expressions into a string. In Python, this can be done using f-strings, format() method, or % operator.

Q17.What is a raw string in Python?

A. A string that is not encoded in any particular character set
B. A string that is used for regular expressions
C. A string that is formatted with variables
D. A string that treats all characters as literal characters, including backslashes

Answer: D

Explanation: A raw string in Python is a string that treats all characters as literal characters, including backslashes. It is defined using the letter ‘r’ before the opening quote.

String of Python

Q18.Which method can be used to count the number of occurrences of a substring in a string in Python?

A. count()
B. find()
C. index()
D. substring()

Answer: A

Explanation: The count() method can be used to count the number of occurrences of a substring in a string in Python.

Q19.Which method can be used to convert a string to uppercase letters in Python?

A. upper()
B. lower()
C. title()
D. capitalize()

Answer: A

Explanation: The upper() method can be used to convert a string to uppercase letters in Python.

Q20.What is the difference between a string and a byte string in Python?

A. A string is a sequence of characters, while a byte string is a sequence of bytes
B. A string is immutable, while a byte string is mutable
C. A string can only contain ASCII characters, while a byte string can contain any byte value
D. A string is represented using Unicode encoding, while a byte string is represented using a specific character encoding

Answer: A

Explanation: A string is a sequence of characters, while a byte string is a sequence of bytes. In Python, strings are represented using Unicode encoding, while byte strings are represented using a specific character encoding such as UTF-8 or ASCII.

Q21. Which method can be used to replace all occurrences of a substring in a string with a new substring in Python?

A. replace()
B. remove()
C. replace_all()
D. subst()

Answer: A

Explanation: The replace() method can be used to replace all occurrences of a substring in a string with a new substring in Python.

Q22.What is string slicing in Python?

A. The process of converting a string to a list of individual characters
B. The process of splitting a string into a list of substrings based on a delimiter
C. The process of extracting a portion of a string based on its position
D. The process of encoding a string using a specific character set

Answer: C

Explanation: String slicing in Python is the process of extracting a portion of a string based on its position. It can be done using square brackets and specifying the start and end indices of the substring to extract.

Q23. Which method can be used to check if a string contains only numeric characters in Python?

A. isdigit()
B. isnumeric()
C. isalpha()
D. isalnum()

Answer: A

Explanation: The isdigit() method can be used to check if a string contains only numeric characters in Python.

Q24.Which method can be used to concatenate two or more strings in Python?

A. concat()
B. merge()
C. join()
D. combine()

Answer: C

Explanation: The join() method can be used to concatenate two or more strings in Python. It is called on a separator string and the strings to be concatenated are passed as a list.

Q25.What is the difference between a string and a list in Python?

A. A string is mutable, while a list is immutable
B. A string can only contain characters, while a list can contain any data type
C. A string is indexed using square brackets, while a list is indexed using parentheses
D. A string is a sequence of characters, while a list is a sequence of values

Answer: D

Explanation: A string is a sequence of characters, while a list is a sequence of values. In Python, strings are immutable, meaning their values cannot be changed after they are created, while lists are mutable, meaning their values can be changed.

Q26.Which method can be used to remove leading and trailing whitespace characters from a string in Python?

A. lstrip()
B. rstrip()
C. strip()
D. remove()

Answer: C

Explanation: The strip() method can be used to remove leading and trailing whitespace characters from a string in Python.

Q27.Which method can be used to split a string into a list of substrings based on a delimiter in Python?

A. split()
B. join()
C. concatenate()
D. merge()

Answer: A

Explanation: The split() method can be used to split a string into a list of substrings based on a delimiter in Python. The delimiter can be specified as an argument to the method.

Q28.What is the difference between a string and a tuple in Python?

A. A string is mutable, while a tuple is immutable
B. A string can only contain characters, while a tuple can contain any data type
C. A string is indexed using square brackets, while a tuple is indexed using parentheses
D. A string is a sequence of characters, while a tuple is a sequence of values

Answer: D

Explanation: A string is a sequence of characters, while a tuple is a sequence of values. In Python, strings are immutable, meaning their values cannot be changed after they are created, while tuples are immutable, meaning their values cannot be changed.

Q29.Which method can be used to find the position of a substring in a string in Python?

A. find()
B. index()
C. search()
D. locate()

Answer: A

Explanation: The find() method can be used to find the position of a substring in a string in Python. If the substring is not found, the method returns -1.

Introduction to Internet of Things (IoT Basics)

IoT Tutorial: Introduction to Internet of Things (IoT Basics)

The Internet of Things (IoT) is a term used to describe a network of physical devices, vehicles, home appliances, and other items that are embedded with sensors, software, and connectivity to enable them to collect and exchange data. IoT is rapidly transforming industries and our daily lives. In this article, we will introduce you to the basics of IoT and its applications.

What is IoT?

IoT is a network of physical devices that are embedded with sensors, software, and connectivity to enable them to collect and exchange data. These devices range from simple sensors to complex machines like cars, drones, and robots. The collected data is sent to a cloud platform where it is analyzed to derive insights and improve efficiency.

Brief history of IoT

The concept of IoT was first introduced in 1982 by a group of researchers at Carnegie Mellon University who connected a Coca-Cola vending machine to the internet. However, it wasn’t until the early 2000s that IoT gained significant attention with the advancement of wireless communication and sensor technology. Since then, IoT has grown exponentially and is projected to have over 50 billion connected devices by 2030.

How does IoT work?

IoT devices use sensors to collect data such as temperature, humidity, and location. The collected data is then transmitted to a cloud platform through wireless or wired connectivity. The cloud platform stores and processes the data to generate insights that can be used to improve efficiency, productivity, and decision-making.

Components of IoT

There are four main components of IoT:

Sensors

Sensors are devices that collect data from the environment. They can measure various parameters such as temperature, humidity, pressure, and light intensity.

Connectivity

Connectivity refers to the communication between devices. IoT devices can use various communication technologies such as Wi-Fi, Bluetooth, Zigbee, and cellular networks to exchange data.

Cloud Platform

The cloud platform is where the collected data is stored and processed. Cloud platforms like Amazon Web Services (AWS) and Microsoft Azure provide tools for data analysis, machine learning, and artificial intelligence.

Data Analytics

Data analytics is the process of extracting insights from the collected data. This can be done using various techniques such as machine learning and artificial intelligence.

 

IoT Applications

IoT has various applications in different industries. Some of the popular applications are:

 Smart Home

Smart home technology uses IoT devices to automate various tasks such as turning off lights, adjusting thermostats, and controlling home appliances.

 Wearables

Wearables such as fitness trackers and smartwatches use IoT technology to collect data on physical activity, heart rate, and sleep patterns.

 Industrial IoT

Industrial IoT (IIoT) is used in manufacturing plants to improve efficiency and reduce downtime. IIoT devices can monitor machine performance and alert maintenance teams when repairs are needed.

 Agriculture IoT

Agriculture IoT (Agri-IoT) is used in farming to monitor soil moisture, temperature, and humidity to optimize crop yield. It can also track livestock and monitor their health.

 Healthcare IoT

Healthcare IoT is used in hospitals and clinics to track patient health data and monitor medical equipment. It can also be used for remote patient monitoring, telemedicine, and drug delivery.

 IoT Security

IoT security is a major concern as the devices are connected to the internet and can be vulnerable to cyber attacks. Security measures such as encryption, authentication, and access control are used to protect IoT devices and data.

 Challenges in IoT

There are several challenges in implementing IoT, including privacy concerns, interoperability, and standardization. Additionally, there is a lack of skilled professionals who can design, develop, and maintain IoT systems.

 Future of IoT

The future of IoT is exciting, with the potential to transform industries and improve our daily lives. Advancements in 5G technology, artificial intelligence, and blockchain will drive the growth of IoT. We can expect to see more connected devices, smart cities, and autonomous vehicles in the coming years.

Conclusion

In conclusion, IoT is a network of physical devices that collect and exchange data to improve efficiency, productivity, and decision-making. IoT has various applications in different industries, including smart homes, wearables, and healthcare. However, there are challenges in implementing IoT, and security is a major concern. The future of IoT is bright, and we can expect to see more innovative applications in the coming years.

FAQs

Q1. What is the difference between IoT and M2M?

A1.Machine-to-machine (M2M) refers to the direct communication between devices, while IoT involves the use of sensors, connectivity, and cloud platforms to collect and analyze data.
How does IoT improve efficiency?
IoT devices can monitor and optimize processes, reduce downtime, and automate tasks, resulting in increased efficiency.

Q2.What are some security measures used in IoT?

A2.Encryption, authentication, access control, and network segmentation are some security measures used in IoT.
What are the challenges in implementing IoT?
Challenges in implementing IoT include privacy concerns, interoperability, standardization, and a lack of skilled professionals.
What is the future of IoT?The future of IoT is exciting, with advancements in 5G, AI, and blockchain driving growth and innovation in the industry.

book solution : Exception Handling in Python

Table of Content :

       1. “Every syntax error is an exception but every exception cannot be a syntax error.” Justify the statement

.
       2. When are the following built-in exceptions raised? Give examples to support your answers.
a) ImportError
b) IOError
c) NameError
d) ZeroDivisionError

3. What is the use of a raise statement? Write a code to accept two numbers and display the quotient. Appropriate exception should be raised if the user enters the second number (denominator) as zero (0).

4. Use assert statement in Question No. 3 to test the division expression in the program.

5. Define the following:
a) Exception Handling
b) Throwing an exception
c) Catching an exception

6. Explain catching exceptions using try and except block

Q1. “Every syntax error is an exception but every exception cannot be a syntax error.” Justify the statement.

Answer : – The statement is true, and it highlights the difference between syntax errors and exceptions in programming.

In programming, syntax errors occur when the code violates the language’s syntax rules. For example, forgetting to close a parenthesis or using an undefined variable. These errors are detected by the compiler or interpreter during the compilation or interpretation phase and prevent the code from running. Thus, every syntax error is an exception because it breaks the normal flow of the program execution.

On the other hand, exceptions are errors that occur during the execution of a program. These errors are not necessarily caused by syntax violations, but rather by unexpected events, such as a division by zero, an invalid file operation, or a network error. Exceptions can be handled by the program to prevent it from crashing, and they may or may not be caused by syntax errors. Therefore, every exception cannot be a syntax error because an exception can be caused by a logical error or an external event that is not related to syntax violations.

In summary, every syntax error is an exception because it interrupts the normal program flow, but every exception cannot be a syntax error because exceptions can be caused by a wide range of unexpected events, not necessarily syntax violations.

Page : 1           2           3           4

Chapter 1 : Exception Handling in Python theory

Syntax Errors in python
Syntax errors in Python are errors that occur when the interpreter encounters code that violates the rules of the Python language syntax. In other words, syntax errors occur when there is a mistake in the way the code is written, such as a missing colon or parentheses.

Here’s an example of a syntax error:

bash
Copy code
print(“Hello, world!”
This code is missing a closing parentheses for the print function, which results in a syntax error. When you run this code, you will see an error message that looks something like this:

arduino
Copy code
File “<stdin>”, line 1
print(“Hello, world!”
^
SyntaxError: unexpected EOF while parsing
The error message indicates that the interpreter encountered an unexpected end of file while trying to parse the code.

Other examples of syntax errors include:

Missing colon after an if statement
Missing parentheses around function arguments
Using an invalid keyword as a variable name
Syntax errors are usually easy to fix once you identify them. The error message will give you a clue as to where the error is located in your code.

Page : 1           2           3           4