Docsity

"Python Programming Guide: Mastering the Basics and Beyond Python Programming Guide: Mast, Exercises of System Programming

Partial preview of the text

Download "Python Programming Guide: Mastering the Basics and Beyond Python Programming Guide: Mast and more Exercises System Programming in PDF only on Docsity!

Programming using Python

1) Which OS is supported by Raspberry pi? Ans- The Raspberry Pi supports a variety of operating systems, including: i. Raspberry Pi OS (formerly Raspbian): This is the recommended and official operating system for Raspberry Pi. It is a Debian-based Linux distribution optimized for the Raspberry Pi's hardware. Raspberry Pi OS is designed to be beginner-friendly and comes with pre-installed software and tools. ii. Ubuntu: The official Ubuntu Desktop distribution has a version optimized for Raspberry Pi. It provides a full desktop environment and access to the extensive Ubuntu software ecosystem. iii. Kali Linux: Kali Linux offers an ARM-based version specifically designed for penetration testing and ethical hacking purposes. It includes a wide range of security and hacking tools. iv. Windows 10 loT Core: Microsoft provides Windows 10 loT Core, a version of Windows designed for loT devices including Raspberry Pi. It enables developers to build Windows-based applications for loT scenarios. 2) What is NOOBS? Explain. Ans- NOOBS (New Out Of Box Software) is an operating system installation manager for the Raspberry Pi. It is designed to simplify the process of setting up the Raspberry Pi by providing an easy-to-use interface for selecting and installing various operating systems onto an SD card. NOOBS comes pre-installed on a Raspberry Pi SD card or can be downloaded from the official Raspberry Pi website. When the Raspberry Pi is powered on with a NOOBS SD card inserted, it boots into a user-friendly graphical interface that allows users to choose and install an operating system of their choice. NOOBS provides a selection of operating systems, including Raspberry Pi OS (formerly Raspbian) and other Linux distributions such as Ubuntu, Arch Linux ARM, and more. Users can select the desired operating system(s) and follow the on-screen instructions to install them onto the SD card. NOOBS also includes an option to install multiple operating systems in a dual-boot configuration, allowing users to easily switch between different operating systems without having to reformat the SD card.

4. Configure Wi-Fi (Optional) 5. Boot the Raspberry Pi: Insert the prepared SD card into the Raspberry Pi's SD card slot. Connect the necessary peripherals, such as a keyboard, mouse, and display, and then power on the Raspberry Pi. 6. Select Raspbian for Installation: The Raspberry Pi will boot into the NOOBS interface. From the menu, select "Raspbian" (or "Raspberry Pi OS") as the operating system you want to install. You can also choose to install additional operating systems if desired. 7. Start the Installation: Click on the "Install" button to begin the installation process. NOOBS will copy the necessary files from the SD card to the Raspberry Pi's storage. 8. Complete the Setup: After the installation is complete, the Raspberry Pi will automatically reboot into Raspbian. Follow the on-screen prompts to complete the initial setup, including language, keyboard layout, and user account details. Following these steps will guide you through the installation of Raspbian (Raspberry Pi OS) using the NOOBS installer, providing an easy and user-friendly way to set up the operating system on your Raspberry Pi.

5) Explain Data types used in Python. OR Write a short note on - Standard Data Types used in Python. Ans- Python has several built-in data types that are commonly used for storing and manipulating data.

1. Numeric Types: Integer {int): Represents integers {whole numbers) without any decimal points. Float {float): Represents floating-point numbers with decimal points. Complex {complex): Represents complex numbers in the form of 'a+ bj', where'a' and 'b' are real

numbers and T represents the square root of - 1.

2. Sequence Types: String {str): Represents a sequence of characters {strings) enclosed in single quotes {") or double quotes (""). List {list): Represents an ordered collection of items. Lists can contain elements of different data types and can be modified {mutable). Tuple {tuple): Represents an ordered collection of items, similar to a list, but tuples are immutable {cannot be modified once created). 3. Mapping Type: Dictionary (diet): Represents a collection of key-value pairs. Each value is associated with a unique key. Dictionaries are mutable and allow for efficient lookup of values based on keys. 4. Set Types: Set {set): Represents an unordered collection of unique elements. Sets are useful foreliminating duplicates and performing mathematical set operations (union, intersection, etc.). 5. Boolean Type: Boolean {bool): Represents a logical value, which can be either 'True' or 'False'. It is commonly used in conditional statements and boolean operations. 6. None Type: None (None): Represents a null or empty value. It is often used to indicate the absence of a value or as a default return value for functions that don't explicitly return anything.

7) Describe Tuple in Python with Syntax and Example. OR Write a short note on - Python Tuple Ans- In Python, a tuple is an ordered collection of elements, similar to a list. However, unlike lists, tuples are immutable, meaning they cannot be modified once created. Tuples are defined by enclosing the elements within parentheses'()' or without any enclosing brackets. Syntax for creating a tuple: my_tuple = (iteml, item2, item3, ...) OR my_tuple = iteml, item2, item3, ... Each element in the tuple is separated by a comma. Tuples can contain elements of any data type, and they can be the same or different types. Example that demonstrates the creation and characteristics of a tuple:

Creating a tuple

fruits= ('apple', 'banana', 'cherry', 'durian')

Accessing elements

print(fruits[0]) # Output: 'apple' print(fruits[2]) # Output: 'cherry'

Tuple with a single element

single_tuple = ('apple',)

Length of the tuple

length= len(fruits) print(length) # Output: 4

Tuple unpacking

fruitl, fruit2, fruit3, fruit4 = fruits print(fruitl, fruit2, fruit3, fruit4) # Output: 'apple', 'banana', 'cherry', 'durian'

8) Describe Dictionary in Python with Syntax and Example. OR Write a short note on - Python Dictionary Ans- In Python, a dictionary is a built-in data structure used to store a collection of key-value pairs. It is an unordered and mutable collection, meaning the elements can be modified after creation. Dictionaries are defined by enclosing the key-value pairs within curly braces'{}'. Syntax for creating a dictionary: my_dict = {keyl: valuel, key2: value2, key3: value3, ...} Each key-value pair is separated by a colon':' and individual pairs are separated by commas. Keys in a dictionary must be unique, and they can be of any immutable data type such as strings, numbers, or tuples. Values can be of any data type and can be duplicated. Example that demonstrates the creation and manipulation of a dictionary:

Creating a

dictionary student= { 'name': 'John Doe', 'age': 25, 'grade': 'A', 'courses': ['Math', 'Science', 'English'] }

Accessing

elements pri nt(student['name']) print(student['age'])

Modifying elements

student['grade'] = 'B' print(student['grade'])

Output: 'John Doe'

Output: 25

Output: 'B'

Adding new elements

student['city'] = 'New York' print(student)

Output: {'name': 'John Doe', 'age': 25, 'grade': 'B', 'courses': ('Math', 'Science', 'English'], 'city':

'New York'}

Removing elements

del student['courses'] print(student) # Output: {'name': 'John Doe', 'age': 25, 'grade': 'B', 'city': 'New York'}

Length of the dictionary

length = len(student) print(length) # Output: 4

10) Explain Decision making statements in Python. Ans- Decision making statements provide the ability to control the flow of execution based on certain conditions, allowing for more dynamic and flexible programs. Statement if statement elif statement else statement nested if statement switch statement Description Executes a block of code if aspecified condition is true. Optional statement used in conjunction with the if statement. It allows checking multiple conditions and executing a block of code if any condition is true. Optional statement used in conjunction with the if statement. It is executed if none of the conditions specified in the if and elif statements are true. An if statement inside another if statement. It allows checking multiple conditions in a hierarchical manner. Python does not have a built-in switchstatement. However, multiple if-elif-else statements can be used to achieve similar functionality. Example demonstrating the usage of decision-making statements in Python:

Example: Check if a number is positive, negative, or zero

num = int(input("Enter a number:")) if num > 0 : print("Number is positive.") elif num < 0: print("Number is negative.") else: print("Number is zero.") In the above example, the if statement is used to check if the number is greater than

  1. If the condition is true, it prints that the number is positive. The elif statement checks if the number is less than 0. If the condition is true, it prints that the number is negative. If none of the conditions in the if and elif statements are true, the else statement is executed, and it prints that the number is zero.

11) Explain 'elif' statement in Python. Ans- The'elif statement is a conditional statement used in Python in conjunction with the'if statement. It allow to check multiple conditions sequentially and execute a block of code if any of the conditions are true. The'elif statement is short for "else if". Syntax: if conditionl:

Code to execute if conditionl is true

elif condition2:

Code to execute if condition2 is true

elif condition3:

Code to execute if condition3 is true

else:

Code to execute if none of the conditions are true

Refer following steps for 'elif' statement working:

  1. The 'if statement is evaluated first. If the condition in the 'if statement is true, the corresponding block of code is executed, and the program skips the 'elif and 'else' statements.
  2. If the condition in the 'if statement is false, the program moves to the first 'elif statement. It evaluates the condition in the 'elif statement. If the condition is true, the corresponding block of code is executed, and the program skips any subsequent'elif and 'else' statements.
  3. If the condition in the 'elif statement is false, the program moves to the next 'elif statement (if any), and the process repeats.
  4. If none of the conditions in the 'if and'elif statements are true, the program executes the block of code in the 'else' statement (if present). The 'elif statement allows you to check multiple conditions in a sequential manner without having to nest multiple 'if statements. It provides a structured way to handle complex decision-making scenarios.

13} List and explain different types of operators used in Python. Ans- In Python, operators are symbols or special characters that perform operations on operands, such as variables, values, or expressions. These operators allow you to perform various operations and comparisons in Python, enabling to manipulate data and control program flow efficiently. Operator Type Arithmetic Operators Assignment Operators Operator Description · +· Adds two operands or performs unary positive operation. Subtracts the right operand from the left operand or performs unary negative operation. Multiplies two operands. · 1 · Divides the left operand by the right operand, returning a floating-pointnumber. · 11 · Performs floor division, returning the largest integer less than or equal to the quotient. Returns the remainder after division. "**" Raises the left operand to the power of the right operand. Assigns the value of the right operand to the left operand. += Adds the right operand to the left operand and assigns the result to the left operand. Subtracts the right operand from the left operand and assigns the result to the left operand. · *=· Multiplies the left operand by the right operand and assigns the result to the left operand. ·I=· Divides the left operand by the right operand and assigns the result to the left operand. '/I=· Performs floor division on the left operand by the right operand and assigns the result to the left operand. '%=· Calculates the modulo of the left operand and assigns the result to the left operand.

  • **= · Raises the left operand to the power of the right operand and assigns the result to the left operand.

Comparison Operators

. != "<. ">. <= ">= Checks if the operands are equal. Checks if the operands are not equal. Checks if the left operand is less thanthe right operand. Checks if the left operand is greater than the right operand. Checks if the left operand is less than or equal to the right operand. Checks if the left operand is greater than or equal to the right operand. Logical Operators ·and· or Returns "True' if both operands are 'True'. Returns ·True· if either operand is'True-. ·not· Returns "Tru-e if the operand is'False- , an-d Fals-e if the operand is ·True·. Bitwise Operators "&"^ Performs bitwise AND operation on the binary representations of the operands. Performs bitwise XOR operation on the binary representations of the operands. Performs bitwise negation of the binary representationof the operand. « Shifts the bits of the left operand to the left by the number of positions specified by the right operand. ·» · Shifts the bits of the left operand to the right by the number of positions specified by the right operand. Membership Operators Returns ·True· if a value is found in the specified sequence. · not Returns ·True· if a value is not found in the specified sequence. 1n· Identity Operators Returns "True· if bothoperands refer to the same object. · is Returns ·True· if bothoperands do not refer to the same object. not·

16) Explain Time related functions used in Python? OR What is the use of 'time' function? Ans- These time-related functions are part of the time module in Python, and they provide various functionalities for working with time and dates. Function "time.time()· "time.sleep()" "time.perf_counter()" "time.process_time()" "time.strftime()" "time.strptime()" "time.gmtime()" "time.localtime()" "time.mktime()" "time.asctime()" "time.ctime()" Description Returns the current timein seconds since the epoch (January 1, 1970 , 00:00: 00 UTC). Suspends the execution of the program for a specified number of seconds. Returns the value of a clock with the highest available resolution for measuring shortdurations. Returns the sum of the system and user CPU time of the current process in seconds. Formats a time value according to a specified format stringandreturns the formatted string. Parses a string representing atime value according to a specified format and returns a time tuple. Converts atime value in seconds since the epoch to a struct_time in UTC timezone. Converts atime value in seconds since the epoch to a struct_time in local timezone. Converts a struct_time representing a local time to seconds since the epoch. Converts a struct_time to a string representing a time in the format "Day Month Date HH:MM:SS Year". Converts atime value in seconds since the epoch to astring representing a timein the format "Day Month Date HH:MM:SS Year".

16 17} Give Python Operator Precedence.

Ans-

The following table list all operators precedence in Python, from highest to lowest: Operator Parentheses · ( > · Exponentiation · ** · Unaryplusandmlnus ·+x·, ·-x· Multiplication, division, modulus Addition and subtraction Bitwise shifts Bitwise AND ·&• BitwiseOR · Bitwise XOR ·A· Comparison operators Logical NOT ·not· Logical AND ·and· Logical OR ·or· Conditionalexpressions · if else· Assignment operators Description Grouping and overriding precedence Exponentiation Positive and negative signs Multiplication ·*·,division · 1 ·, modulus'%• Addition ·+·,subtraction · - · Left shift ·«·,right shift · » · Bitwise AND Bitwise XOR Logical NOT Logical AND Logical OR Conditional expressions