Unit 3: Introduction to Python Programming — Long Questions
10th Class Computer Science · Unit 3: Introduction to Python Programming
Ans. ★ Key Point
Python Programming Language
Python is a popular, easy-to-learn high level programming language designed to be readable and user-friendly. It uses simple syntax (like plain English) instead of complex symbols, making it perfect for beginners.
Commonly Used in Different Fields
Python is used to build websites, analyze data, create games, automate tasks, and even power advanced technologies like AI. Its versatility and large community support make it a go-to choice for solving problems in almost any field.
Ans. ★ Key Points Basic Concept of Programming Language | Basic Step to Write Code
1. Understanding Basic Programming Concepts
Computer programming is the process of creating a set of instructions that tell a computer how to perform a task. These instructions are written in a programming language that the computer can understand and execute.
Example Think of computer programming like giving directions to a friend on how to reach your house, you need to be clear and precise so your friend doesn't get lost. Similarly, when we write programs, we give clear and precise instructions to the computer to complete specific tasks.
2. Programming Basics
Computer programming involves the following basic steps to write a program:
a. Write Code: Create a set of instructions in a programming language.
b. Compile/Interpret: Translate the code into a form that the computer can understand.
c. Execute: Run the code to perform the task.
d. Output: Display the results or perform actions based on the code
Source Code
Human readable code written in programming languages like C, C++, Python.
Object Code: Machine readable code generated by compiling source code.
Ans. ★ Key Points Integrated Development Environment | How to Download Python?
1. Setting Up Python development environment
The development environment refers to the process of preparing a computer to write, run, and debug Python code effectively. This involves installing and configuring the necessary software, tools, and libraries that make development smoother and more efficient.
2. Steps of Python Installation
To complete the installation process of Python, follow these steps:
a. Download Python
Visit https://www.python.org/. Navigate to the "Downloads" section and click on the latest version of Python (e.g., Python 3.13.x) for your operating system (Windows, macOS, or Linux). The installer will download automatically.
b. Install Python
• Run the downloaded .exe file.
• Check the box "Add Python to PATH" during installation.
• Select "Install Now" or customize the installation if needed (e.g., choose the installation directory).
• Wait for the installation to complete, then click "Close"
c. Set Up an IDE
• Download and install a popular IDE like PyCharm, VS Code, or IDLE (included with Python).
• PyCharm is a powerful IDE for Python development, available in a free Community edition or a paid Professional edition.
• Visit: https://www.jetbrains.com/pycharm/ to download the version suitable for your operating system (Windows, macOS, or Linux).
DID YOU KNOW?
Q. What should you do when installing Python to make it easier to run from the command line, and what is another alternative for running Python programs?
Ans. When installing Python, make sure to check the box that says "Add Python to PATH." This makes it easier to run Python from the command line. We can also use online services to write and run Python program.
d. Configuring the IDE with Python
• Open PyCharm and start a new project.
• In the "Configure" or "Settings" menu, go to "Project Interpreter"
• Click the gear icon, select "Add Interpreter," and choose the path to your Python executable (e.g., C:Python312python.exe on Windows or /usr/bin/python3 on Linux/macOS). Browse to your installation folder if it's not auto-detected. Apply the settings and let PyCharm index the interpreter.
e. Testing the Configuration
• Create a new file (e.g., test.py) in your IDE.
• Write a simple script: print("Hello, Python!")
• Run the script (use the "Run" button in PyCharm/IDLE or F5 in VS Code after setting up a task).
• If the output appears (e.g., "Hello, Python!"), your IDE is correctly configured.
3. Google Colab
Another excellent option for using Python is Google Colab. It is a free cloud based platform that provides a Jupyter notebook environment with pre-installed Python and popular libraries like NumPy, Pandas, and Matplotlib. To get started, visit https://colab.research.google.com/, sign in with a Google account, and create a new notebook. No local installation is required, making it ideal for beginners or those working on machines with limited resources. You can write and execute Python code in cells.
Ans. ★ Key Points Syntax of Python
The following Python program demonstrates the simplicity and readability of the language:
print("This is my first page")
Output This is my first page
In this example, the print function is utilized to output the message enclosed in double quotation marks. This illustrates Python's straightforward syntax, where functions like print are used to perform actions such as displaying text.
Ans. ★ Key Points Comments | Single-Line | Multi-Line
Comments are the lines that are not executed by the Python interpreter. They are used to provide explanations or notes for the programmer.
Types of Comments
1. Single-line Comments
• Start with the # symbol.
• It is used to add a comment that explains one line or step in the code.
• Python skips the part after # when running the program.
Example
# This is a single-line comment
print("Hello,World!")
2. Multi-line Comments
• Multiline comments are used when you want to write a comment that covers more than one line.
• You can create them by using triple single quotation marks "" at the start and end of the comment.
• They are helpful for writing longer notes or explanations that take up several lines.
Example
"" This is a multi-line comment.
It spans multiple lines. """
print("Edhi Foundation operates the world's largest volunteer ambulance network")
3. Difference between Single-line Comment and Multi-line Comment
Feature | Single-line Comment | Multi-line Comment
Used for | Explaining one line of code | Explaining multiple lines or long notes
Symbol used | # at the start of the line | Triple single quotes "" at start and end
How it works | Python ignores everything after # on that line | Python ignores everything between the triple quotes
Best for | Short, quick notes | Longer explanations or blocks of text
Example | # This is a comment | "" This is a comment that takes multiple lines """
INTERESTING INFORMATION
Q. How are triple quotes used in Python, and are they actually multiline comments?
Ans. We can use the "" or ''(Triple Quotes) in python for multiline comments but actually they are multiline string literals which are ignored at runtime.
Ans. ★ Key Points Variable | Rules for Naming Variable
A variable in programming functions as a storage container within a computer's memory. It allows the storage of data that can be retrieved later in the code. In the example below, the variable age is utilized to hold numerical data. The value of a variable can change throughout the execution of a program, which is why it is referred to as a "variable".
Example
age=17
print("Areeda lived for",age,"years")
age=16
print("Hina lived for",age,"years")
Output
Areeda lived for 17 years
Hina lived for 16 years
This example illustrates how the variable "age" is assigned different values to represent the ages of Areeda and Hina, which are then printed as part of the output.
1. Rules for Naming Variables in Python
Variable names in Python must adhere to the following rules:
• The name must begin with a letter (a-z, A-Z) or an underscore ( _ ) . It cannot began with a digit.
Example: myvariable, count, var2 are valid: 2var is invalid.
• Subsequent characters can include letters, digits (0-9), or underscores ( _ ) .
• Variable names are case-sensitive, meaning age and Age are considered two different variables.
Example: myVar, myvar, and MYVAR are treated as different variables.
• Python's reserved keywords, such as for, while, if, etc., cannot be used as variable names.
Example: if = 10 is invalid because if is a keyword.
• Special characters like @, #, $, %, etc., are not allowed in variable names.
Example: my@var is invalid.
• There is no strict limit on the length of variable names, but overly long names can reduce readability
2. Example of Valid and Invalid Variable Names
• Valid: score, player1, temp, totalSum
• Invalid: 2nd place, my-var, for, my#score
DID YOU KNOW?
Q. What are some reserved words in Python, and can they be used as variable names?
Ans. Following are some of the reserved words in Python: if, else, elif, for, while, break, continue, and, or, not, in, is, True, False, None and print We cannot use them as a variable name.
Ans. ★ Key Points Data Types | Integer | Float | Strings | Boolean
In Python, you can create variables of different types to store various kinds of data. There are some common types of variables:
1. Integer (int)
Definition: Stores whole numbers without decimal points.
Example: age = 17
In this case, age is an integer variable storing the value 17
2. Floating-Point (float)
Definition: Stores decimal numbers.
Example: price = 19.99
In this case, price is a float variable storing the value 19.99
3. String (str)
Definition: Stores text or characters. Strings are enclosed in quotes, either single (' ') or double (" ").
Example: name = "Arshad"
In this case, name is a string variable storing the text "Arshad"
4. Boolean (bool)
Definition: Stores True or False.
Example: isstudent = True
In this case, isstudent is a boolean variable that stores the value True.
Ans. ★ Key Points Input | Output | I/O Examples
1. Input and Output Operations
Input and output operations allow you to interact with the user. You can ask the user to enter data (input) and display information to the user (output).
a. Input: We use the input() function to get user input. The input() function displays a message on the screen and waits for the user to type something and press Enter key. The text entered by the user is then stored in a variable.
Example: name=input("Enter your name:")
This line of code asks the user to enter their name and stores it in the variable name.
b. Output: Use the print() function to display information on the screen. The print() function takes one or more arguments and displays them.
Example: print("Hello,"+name+"!")
This line of code displays a greeting message that includes the user's name.
DID YOU KNOW?
Q. In print() function, which symbol is used between multiple values / variables to be printed?
Ans. In the print() function, comma( , ) is used between multiple values or variables to be printed.
Q. In Python, what defines the structure or scope of code?
Ans. Indentation defines the structure or scope of code in Python. Incorrect indentation may cause errors.
2. Handling Integer and Float Inputs
To handle numeric inputs, convert the input using int() for integers or float() for floating-point numbers, as the input() function always returns a string.
• Integer input example:
userage=int(input("Enter your age:"))
print("Your age is:",userage)
Output: Enter your age: 16
Your age is: 16
• Float input example:
userheight=float(input("Enter your height in meters: "))
print("Your height is",userheight,"meter")
Output: Enter your height in meters: 1.5
Your height is: 1.5 meter
Ans. ★ Key Points Operators | Arithmetic | Comparison | Assignment | Logical
An operator is a symbol that performs a specific operation on one or more operands (values or variables). Operators are used to carry out arithmetic, comparison, logical, assignment, and many other operations in a program. An expression is a combination of operators, operands that gives a result. For example, 2 + 3, a * b, or x > y are all operations. When the computer runs the code, it calculates the value of the expression. Example: In the expression a + b, the +is an operator that performs addition, and a and b are operands.
Types of Operators
There are four commonly used types of operators in the Python language.
1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations such as addition (+), subtraction (-), multiplication (*), division (/), modulus (%), exponentiation (**), and floor division (//) as shown in the following code.
Example
# Define variables
a=10
b=3
# Perform all arithmetic operations
print(a,"+", b,"=",a+b) # Output: 10+3=13
print(a,"*", b,"=",a*b) # Output: 10 * 3 = 30
print(a,"/", b,"=",a/b) # Output:10 / 3 = 3.33333333333335
print(a,"//", b,"=",a // b) # Output: 10 // 3=3
print(a,"%", b,"=",a%b) # Output: 10 % 3 = 1
print(a,"**", b,"=",a**b) # Output: 10**3= 1000
2. Comparison Operators
Comparison operators are used to compare two values or expressions. They determine the relational logic between them, such as equality (==), inequality (!=), greater than (>), less than (<), and so on. These operators return a boolean value (True or False) based on the comparison result.
Example
#Define variable
x = 10
y = 5
#Greater than
print(x, ">", y, "=", x > y) # Output: 10 > 5 = True
#Less than
print(x, "<", y, "=", x < y) # Output: 10 < 5 = False
#Equal to
print(x, "==", y, "=", x == y) # Output: 10 == 5 = False
#Not equal to
print(x, "!=", y, "=", x != y) # Output: 10 != 5 = True
#Greater than or equal to
print(x, ">=", y, "=", x >= y) # Output: 10 >= 5 = True
#Less than or equal to
print(x, "<=", y, "=", x <= y) # Output: 10 <= 5 = False
The above code demonstrates Python's comparison operators by defining two variables, x and y, and comparing them using various operators like >, <, ==, !=.
3. Assignment Operators
Assignment operators are used to assign values to variables. The most common assignment operator is the equal sign (=), which assigns the value on the right to the variable on the left. There are also compound assignment operators like += , -=, * =, and / =, which combine arithmetic operations with assignment.
Example
# Define initial values a = 10 b = 5
# Assignment
x = a; print("a =", x) # Output: a = 10
# Addition assignment
a += b; print("a after addition =", a) # Output: a after addition = 15
# Subtraction assignment
a -= b; print("a after subtraction =", a) # Output: a after subtraction= 10
# Multiplication assignment
a *= b; print("a after multiplication =", a) # Output: a after multiplication = 50
# Division assignment
a /= b; print("a after division =", a) # Output: a after division =10.0
# Floor division assignment
a //= b; print("a after floor division =", a) # Output: a after floor division = 2
# Modulus assignment
a %= b; print("a after modulus =", a) # Output: a after modulus =2.0
# Exponentiation assignment
a **= b; print("a after exponentiation =", a) # Output: a after exponentiation = 32.0
Above code illustrates the use of compound assignment operators in Python. It starts by assigning a value to a variable "a". It then demonstrates various assignments operations including addition, subtractions, multiplication, division, floor division, modulus, and exponentiation. Each operation updates the value of "a" and the results are printed with the updated values. The code comments show the output of each operation.
4. Logical Operators
Logical operators are used to combine multiple conditions or expressions in a program. The most common logical operators are and, or, and not. They are used to perform logical operations and return Boolean values based on the evaluation of the expressions involved.
Ans. ★ Key Points Operators | Comparison | Logical Operators | and | or | not
1. Comparison operators are used to compare two values or expressions and return a Boolean value (True or False). Examples include >, <, ==, !=, >=, <=.
2. Logical operators (and, or, not) are used to combine multiple conditions or expressions and return Boolean values based on the evaluation.
Example
# Define variables
x = True
y = False
# Logical AND
logicaland = x and y
print(x, "and", y, "=", logicaland) # Output: True and False = False
# Logical OR
logicalor = x or y
print(x, "or", y, "=", logicalor) # Output: True or False = True
Note
• and returns True only if both conditions are True.
• or returns True if at least one condition is True.
• not inverts a Boolean value.
Ans. ★ Key Points Operators | Arithmetic | Use of Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations on numbers.
Examples
1. Addition (+): Adds two numbers.
a=10
b=3
print(a+b) # Output: 13
2. Subtraction (-): Subtracts the second number from the first.
print(a - b) # Output: 7
3. Multiplication (*): Multiplies two numbers.
print(a*b) # Output: 30
4. Division (/): Divides the first number by the second (returns float).
print(a/b) # Output: 3.33333333333335
5. Floor Division (//): Divides and returns the integer part of the quotient.
print(a//b) # Output: 3
6. Modulus (%): Returns the remainder of division.
print(a%b) # Output: 1
7. Exponentiation (**): Raises the first number to the power of the second.
print(a**b) # Output: 1000
When to use
• Addition, subtraction, multiplication, division used for general calculations.
• Modulus operators are used to find remainders. They are useful in loops, arrays, or checking even/odd numbers.
• Exponentiation used for powers or mathematical formulas.
• Floor division are used when only integer results are needed.
Ans. ★ Key Points Operator Precedence | Priority of Operators | Order of Operations
Operator precedence determines the order in which operations are performed in an expression. In Python as well as in Mathematics, certain operators have higher precedence and are evaluated before others. Understanding this helps ensure that your calculations are done correctly.
1. Parentheses ( ): Highest precedence. Operations inside parentheses are performed first.
(3+2) *4 evaluates to 20.
2. Exponentiation (**): Performs power operations next.
2**3 evaluates to 8.
i.e.2+2*2**3=18
3. Multiplication '*', Division '/', and Modulus '%': These operations come next. 4*3 evaluates to 12, 10/2 evaluates to 5.0 and 11%3 evaluates 2.
4. Addition '+' and Subtraction '-': These have lower precedence compared to multiplication and division. i.e.5+2 evaluates to 7, and 10-4 evaluates to 6.
Example Consider the following code to show operator precedence:
print("=== PYTHON OPERATOR PRECEDENCE DEMONSTRATION ===")
#1. Arithmetic Operators
print("1. ARITHMETIC OPERATORS:")
print(f"3 + 2 * 5= {3+2*5}") # Multiplication
before addition
print(f"(3 + 2) * 5 = {(3 + 2) * 5}") # Parentheses change order
print(f"2 ** 3*4= {2 ** 3*4}") # Exponentiation
before multiplication
print (f"15 / 3 * 2= {15 / 3 * 2}") # Division and
multiplication (left to right)
print (f"15// 4 + 2={15//4+2}") # Floor division
before addition
print(f"11// 4 + 2={11//4+2}") # Floor division
before addition
print(f"17% 4 * 2={17%5*2}") # Modulo before multiplication
Output
=== PYTHON OPERATOR PRECEDENCE DEMONSTRATION ===
1. ARITHMETIC OPERATORS:
3 + 2 * 5 = 13
(3 + 2) * 5 = 25
2 ** 3 * 4 = 32
15 / 3 * 2 = 10.0
15 // 4 + 2 = 5
11 // 4 + 2 = 4
17 % 5 * 2 = 4
DID YOU KNOW?
Q. What does putting an f before a string do in Python?
Ans. In python "f" before string is used for string interpolation (embedding variables to expression) inside a string.
Q. What does it mean that exponentiation (**) is right associative in Python?
Ans. Right associative means Python evaluates ** from right to left. For example, in 2 ** 3 ** 2, it first calculates 3 ** 2 and then 2 ** 9. This is different from most operators, which are left to right.