Humanities/Arts Exam  >  Humanities/Arts Notes  >  Computer Science for Class 11  >  Chapter Notes: Getting Started with Python

Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts PDF Download

Introduction to Python

Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Programming languages can be used to create programs based on the algorithms written for various problems. Before learning the Python programming language, let us understand how a programming language works.

  • A program is a set of instructions given to a computer to perform a specific task, and a programming language is used to write these instructions.
  • Computers understand only machine language, which consists of 0s and 1s. However, it is difficult for humans to write programs in this language. Therefore, high-level programming languages like Python, C++ , Java , etc. were developed.
  • A program written in a high-level language is called source code. This source code needs to be translated into machine language using language translators like compilers and interpreters.
  • Python uses an interpreter to convert its instructions into machine language. An interpreter translates and executes the program statements one by one. If an error occurs, the execution stops.
  • On the other hand, a compiler translates the entire source code into object code. It scans the whole program and generates error messages if there are any.

As Donald Knuth said, "Computer programming is an art." A good programmer enjoys what he does and does it better because he views himself as an artist.

Overview of Python

Python is a high-level, interpreted language known for its clear syntax and simple structure, making it easy to understand and use. It is free and open-source, case-sensitive, and features a rich library of predefined functions. Python is also portable and platform-independent, capable of running on various operating systems and hardware platforms. Additionally, it is widely used in web development for creating popular web services and applications.

Features of Python

Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts

  • High-Level Language: Python is considered a high-level programming language because it allows developers to write programs using abstract concepts and human-readable syntax, without needing to manage complex details like memory management or hardware specifics. This makes Python user-friendly and accessible to a wide range of programmers.
  • Free and Open Source: Python is available for free, and its source code is open to the public. This means that anyone can download, use, modify, and distribute Python, fostering a large community of developers who contribute to its improvement and the development of third-party libraries and tools.
  • Interpreted Language: Python is an interpreted language, which means that Python programs are executed line by line by an interpreter at runtime. This allows for greater flexibility and easier debugging, as errors can be caught and fixed on the fly. However, it may result in slower execution speed compared to compiled languages.
  • Easy to Understand: Python programs are generally easy to read and understand due to their clear syntax and simple structure. The language emphasizes readability, using indentation to define code blocks, which helps developers quickly grasp the logic and flow of the program.
  • Case Sensitivity: Python is case-sensitive, meaning that variable names and identifiers are treated as distinct based on their letter casing. For example, "NUMBER" and "number" would be considered two different identifiers in Python. This feature allows for more flexibility in naming but requires developers to be consistent and mindful of their casing choices.
  • Portability and Platform Independence: Python is portable and platform-independent, meaning that Python programs can run on various operating systems (such as Windows, macOS, and Linux) and hardware platforms without requiring significant modifications. This is possible because Python abstracts away many of the underlying system details, allowing developers to focus on writing code that works across different environments.
  • Rich Standard Library: Python comes with a rich standard library that includes a wide range of pre-built modules and functions for various tasks, such as file handling, networking, web development, data manipulation, and more. This extensive library saves developers time and effort by providing ready-to-use solutions for common programming challenges.
  • Web Development: Python is widely used in web development, with many popular web services and applications built using Python frameworks and libraries. Frameworks like Django and Flask simplify the process of building web applications by providing tools and conventions for handling common tasks such as routing, database interaction, and user authentication. Python's versatility and ease of use make it a preferred choice for web developers.
  • Indentation for Code Blocks: Python uses indentation to define code blocks, such as loops, conditionals, and function definitions. Unlike many other programming languages that use braces or keywords to indicate code blocks, Python relies on consistent indentation levels to determine the scope of code. This feature not only enhances readability but also enforces a level of discipline in code formatting, as improper indentation can lead to syntax errors or unintended behavior.

Working with Python

To write and run a Python program, we need to have a Python interpreter installed on our computer, or we can use an online Python interpreter. The interpreter is also known as the Python shell.
In the Python interpreter, the symbol >>> represents the Python prompt, indicating that the interpreter is ready to receive instructions. We can type commands or statements at this prompt to execute them using the Python interpreter.

Execution Modes 

There are two ways to use the Python interpreter:
a) Interactive mode
b) Script mode

(A) Interactive Mode
In interactive mode, you can execute individual Python statements instantly. To use interactive mode, simply type a Python statement at the >>> prompt and press enter. The interpreter will execute the statement and display the result immediately.

(B) Script Mode
In script mode, we can write a Python program in a file, save it, and then use the interpreter to execute it. Python scripts are saved as files with the extension ".py". By default, these scripts are saved in the Python installation folder.

To execute a script, we have two options:

  • Type the file name along with the path at the prompt. For example, if the file is named prog5-1.py, we simply type prog5-1.py.
  • Open the program directly from IDLE.

When working in script mode, after saving the file, we can run the program by clicking [Run] -> [Run Module] from the menu.

Python Keywords

In Python, keywords are reserved words that have a specific meaning to the interpreter. These keywords can only be used for the purpose for which they are defined. Since Python is case-sensitive, keywords must be written exactly as shown in the table below.

  • False
  • class
  • finally
  • return
  • None
  • lambda
  • try
  • True
  • nonlocal
  • while
  • del
  • global
  • elif
  • yield
  • assert
  • else
  • import
  • pass
  • break
  • except
  • raise

Identifiers in Python

Identifiers are the names used to identify a variable, function, or other entities in a program. In Python, there are certain rules to be followed while naming an identifier. They are as follows:

  • The name should begin with an uppercase or a lowercase alphabet or an underscore sign ( _ ). This may be followed by any combination of characters a–z, A–Z, 0–9 or underscore ( _ ). Thus, an identifier cannot start with a digit.
  • It can be of any length. (However, it is preferred to keep it short and meaningful).
  • It should not be a keyword or reserved word.
  • We cannot use special symbols like !, @, #, $, %, etc., in identifiers.

Example

  • To find the average of marks obtained by a student in three subjects, we can choose the identifiers as marks1, marks2, marks3 and avg.
  • To calculate the area of a rectangle, we can use identifier names, such as area, length, breadth for clarity and readability.

Variables

  • Variables in Python are used to store data and are identified by unique names called identifiers.
  • A variable in Python refers to an object stored in memory, which can be of different types such as strings, numbers, or alphanumeric characters.
  • Variables can be created and assigned values using an assignment statement.

For example:

  • gender. 'M'
  • message. "Keep Smiling"
  • price. 987.9

In Python, variable declaration is implicit, meaning variables are automatically declared and defined when they are assigned a value for the first time.  

However, variables must be assigned values before they are used in expressions, otherwise, it will lead to an error in the program.  

When a variable name occurs in an expression, the interpreter replaces it with the value of that variable.  

Example 1: Displaying Variable Values

  • In the following program, the variable message holds a string value and the variable userNo holds a numeric value:

Example 2: Calculating Area of a Rectangle

  • The area of a rectangle can be calculated by multiplying its length and breadth.
  • For instance, if the length is 10 units and the breadth is 20 units, the area can be calculated as follows:

Output
200

Comments in Python

Comments are an essential part of writing code in Python as they help in adding remarks or notes within the source code. The key point to note is that comments are not executed by the interpreter; instead, they are meant for human understanding.

The primary purpose of comments is to make the source code more comprehensible for individuals. They serve to document the meaning, purpose, input, and output requirements of the code, ensuring that programmers can recall later how the code functions and how to use it. This is especially important in large and complex software projects where multiple programmers may work together, or where one programmer's code needs to be maintained by another. In such cases, comments provide the necessary documentation to understand the program's workings.

In Python, a comment is initiated with the hash sign ( # ). Everything following the hash sign until the end of the line is considered a comment, and the interpreter ignores it during execution. This feature allows programmers to include helpful notes and explanations within their code without affecting its functionality.

Example:
Variable amount is the total spending on groceries.
Grocery amount = 3400
TotalMarks is the sum of marks in all the tests of Mathematics.
TotalMarks = test1 + test2 + finalTest

Program: Write a Python program to find the sum of two numbers.

num1 = 10
num2 = 20
result = num1 + num2
print(result)

Output: 30

Everything Is an Object

Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts

In Python, every piece of data, whether it's a number, a string, or any other type, is treated as an object. This means that any value can be assigned to a variable or passed to a function as an argument.

  • Unique Identity of Objects: Every object in Python has a unique identity (ID) that stays the same for the object's entire life. This ID is similar to the object's memory address. You can find out an object's identity using the  id()  function.
  • Objects in Object-Oriented Programming (OOP): In OOP, objects represent real-world things like employees, students, vehicles, boxes, books, etc. Each object has two main things: (i) data or attributes, and (ii) behavior or methods. There are also classes and class hierarchies from which objects can be created.
  • Python and OOP: Python is an object-oriented programming language, but its definition of an object is more flexible. Some objects in Python might not have attributes, and some might not have methods. This is different from stricter OOP languages like C++ and Java.

Example:
In this example, we will explore the concept of object identity in Python by looking at two variables, num1 and num .

Step 1: Creating the First Variable
We start by assigning the value 20 to the variable num1.
num1 = 20 

Step 2: Checking the Identity of the First Variable

We then use the  id()  function to check the identity of num1. The id() function returns a unique identifier for the object, which is its memory address.
id(num1) 

Step 3: Creating the Second Variable
Next, we create a second variable num2 by performing a simple arithmetic operation: 30 - 10.
num2 = 30 - 10 

Step 4: Checking the Identity of the Second Variable

We again use the  id()  function to check the identity of num2.
 id(num2) 

Data Types in Python

In Python, every value is associated with a specific data type. A data type defines the kind of data that a variable can hold and the operations that can be performed on that data.
Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Here are the different data types available in Python:

  • Numeric Types: These include integers, floating-point numbers, and complex numbers.
  • Sequence Types: This category includes lists, tuples, and ranges.
  • Text Type: The text type in Python is represented by strings.
  • Mapping Type: Python has a built-in dictionary data type for mapping.
  • Set Types: These include sets and frozen sets.
  • Boolean Type: The boolean type in Python represents truth values, either True or False.
  • None Type: Python has a special None type to represent the absence of a value.

Number

The Number data type is used to store numerical values. It is further divided into three categories: int, float, and complex.

Numeric Data Types
Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Boolean Data Type (bool)

  • The Boolean data type is a subset of the integer data type.
  • It consists of two constants: True and False.
  • A Boolean True value is represented by any non-zero, non-null, and non-empty value, while False is represented by the value zero.

Example:
Let us now try to execute few statements in interactive mode to determine the data type of the variable using built-in function type().

Let's explore different variables in Python and their types.

1. Integer Variables

  • num1 = 10
  • num2 = -1210

2. Boolean Variable

  • var1 = True

3. Float Variables

  • float1 = -1921.9
  • float2 = -9.8 * 102 Output: -980.0000000000001  

4. Complex Variable

  • var2 = -3 + 7.2j
  • Output: (-3 + 7.2j)

In Python, variables of simple data types like integers, floats, and booleans hold single values. However, these variables are not suitable for storing long lists of information, such as the names of months in a year, names of students in a class, names and numbers in a phone book, or a list of artifacts in a museum.
To handle such cases, Python provides data types like tuples, lists, dictionaries, and sets, which are designed to store multiple values efficiently.

Sequence

A sequence in Python refers to an ordered collection of items, where each item is associated with an index. Python provides three main types of sequence data types: Strings, Lists, and Tuples. While we will explore each of these in detail in later chapters, let’s take a brief look at what they are.

(A) String
A string is a collection of characters, which can include letters, numbers, and special characters, as well as spaces. Strings are enclosed in either single quotation marks (e.g., ‘Hello’. or double quotation marks (e.g., “Hello” ). The quotation marks are not part of the string; they simply indicate where the string begins and ends for the interpreter. 
For example:
>>> str1 = 'Hello Friend' 
>>> str2 = "452"

It’s important to note that we cannot perform numerical operations on strings, even if the string contains numeric characters, as in the case of str2.

(B) List
A list is a collection of items arranged in a specific order, and these items are separated by commas. Lists are enclosed within square brackets [ ].

Example:
# To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
# print the elements of the list
>>> print(list1)
Output: [5, 3.4, 'New Delhi', '20C', 45]

(C) Tuple
A tuple is similar to a list in that it is a sequence of items separated by commas, but the items in a tuple are enclosed within parentheses ( ). This is the key difference between a tuple and a list, where values are enclosed in square brackets [ ]. Once a tuple is created, its contents cannot be changed.

Example:
# create a tuple
tuple1 >>> (10, 20, "Apple", 3.4, 'a')
# print the elements of the tuple
tuple1 >>> print(tuple1)
Output: (10, 20, "Apple", 3.4, 'a')

Set

  • A set is a collection of items that are unordered and non-duplicate. The items in a set are separated by commas and enclosed in curly brackets { }.
  • Unlike a list, a set cannot have duplicate entries. Once a set is created, its elements cannot be changed.

Example

  • Creating a set
  • set1 = {10, 20, 3.14, "New Delhi"}
  • print(type(set1))
  • print(set1)
  • Output: {10, 20, 3.14, "New Delhi"}
  • Duplicate elements are not included in a set
  • set2 = {1, 2, 1, 3}
  • print(set2)
  • Output: {1, 2, 3}

None

  • None is a unique data type in Python that has only one value: None itself. It is used to represent the absence of a value in a specific context.

  • None does not support any special operations and is not the same as False or 0 (zero).

Example of None

  • myVar = None
  • print(type(myVar))
  • print(myVar)

Mapping in Python

  • Mapping is an unordered data type in Python, and the most common mapping data type is the dictionary.

(A) Dictionary

  • A dictionary in Python stores data in key-value pairs, where each item is enclosed in curly brackets { }.
  • Dictionaries allow for quick access to data, with each key separated from its value by a colon (:).
  • The keys are typically strings, and their corresponding values can be of any data type.
  • To access a value in the dictionary, you need to specify its key within square brackets [ ].

Example of Dictionary

  • # Create a dictionary
  • dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
  • print(dict1)
  • print(dict1['Price(kg)'])

Mutable and Immutable Data Types in Python

In Python, data types can be classified as mutable or immutable based on whether their values can be changed after they are created.

Mutable Data Types: These are data types whose values can be changed after they are created. Examples include:

  • Lists: list can be modified by adding, removing, or changing elements.
  • Dictionaries: The contents of a dictionary can be changed by adding, removing, or updating key-value pairs.
  • Sets: Elements can be added or removed from a set after it is created.

Immutable Data Types: These data types do not allow changes to their values once they are created. Examples include:

  • Integers: Once an integer object is created, its value cannot be changed.
  • Strings: String cannot be modified after it is created. Any operation that seems to modify a string actually creates a new string object.
  • Tuples: Tuple's elements cannot be changed once it is created.
  • Frozensets: Similar to sets, but the elements cannot be changed after creation.
  • Bytes: Bytes object cannot be modified after it is created.

Example:

  • Mutable Example:
  • Creating a list:
  • my_list = [1, 2, 3]
  • Modifying the list:
  • my_list.append(4)  # my_list is now [1, 2, 3, 4] 

Immutable Example:

  • Creating a string:
  • my_string = "Hello"
  • Attempting to modify the string:
  • my_string[0] = "h"  # This will raise an error 

Understanding the difference between mutable and immutable data types is crucial for effective programming in Python, as it affects how data is stored, accessed, and modified in memory.

Deciding on Python Data Types

  • Lists are ideal for situations where you need a basic collection of data that will be changed often. For instance, if you have a list of students in a class, it’s easy to update when new students join or others leave.
  • Tuples are used when the data should not change. For example, the names of the months in a year.
  • Sets are preferable when you need to ensure that all elements are unique and to avoid duplicates. For instance, a list of artifacts in a museum.
  • Dictionaries are recommended when the data is constantly changing, when you need fast lookups based on a custom key, or when you need a logical association between key-value pairs. A mobile phone book is a good example of using a dictionary.

Operators in Python

An operator is a symbol that tells the computer to perform a specific mathematical or logical operation on one or more values. The values that the operator works on are called operands. For example, in the expression 10 + num, 10 and num are operands, and + is the operator. Python has various types of operators, which are categorized based on their functionality.

When comparing strings in Python, the comparison is done lexicographically using the ASCII values of the characters. The comparison starts from the first character of both strings. If the first characters are the same, the second characters are compared, and so on, until a difference is found or the end of the strings is reached.

Arithmetic Operators in Python

Python provides a range of arithmetic operators to perform various mathematical operations, including the basic four operations, modular division, floor division, and exponentiation.

Here’s a detailed look at each arithmetic operator in Python:

Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Relational Operators in Python

Relational operators are used to compare the values of operands on either side and determine the relationship between them. Let's consider the Python variables:  num1 = 10 ,  num2 = 0,  num3 = 10,  str1 = "Good", and  str2 = "Afternoon"  for the following examples.
Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Assignment Operators in Python

Assignment operators are used to assign or modify the value of a variable in Python. Here are the different types of assignment operators:

1. = (Simple Assignment)

  • Assigns the value from the right-side operand to the left-side operand.
  • Example:
  •  country = 'India' 
  •  country outputs  'India' 

2. += (Add and Assign)

  • Adds the value of the right-side operand to the left-side operand and assigns the result to the left-side operand.
  • Note:  x += y  is the same as x = x + y 
  • Example:
  •  num2 = 2 
  •  num1 += num2 
  •  str1 = 'Hello' 
  •  str2 = 'India' 
  •  str1 += str2 

3. -= (Subtract and Assign)

  • Subtracts the value of the right-side operand from the left-side operand and assigns the result to the left-side operand.
  • Note:  x -= y  is the same as  x = x - y 
  • Example:
  •  num1 -= num2

4. *= (Multiply and Assign)

  • Multiplies the value of the right-side operand with the value of the left-side operand and assigns the result to the left-side operand.
  • Note:  x *= y  is the same as  x = x * y 
  • Example:
  •  num1 *= 3 
  •  a = 'India' 
  •  a *= 3  outputs  'IndiaIndiaIndia'

5. /= (Divide and Assign)

  • Divides the value of the left-side operand by the value of the right-side operand and assigns the result to the left-side operand.
  • Note:  x /= y  is the same as  x = x / y 
  • Example:
    num1 = 6 
    num1 /= num2 

6. %= (Modulus and Assign)

  • Performs modulus operation using two operands and assigns the result to the left-side operand.
  • Note:  x %= y  is the same as  x = x % y 
  • Example:
    num1 = 7 
    num1 %= num2 

7. //= (Floor Division and Assign)

  • Performs floor division using two operands and assigns the result to the left-side operand.
  • Note:  x //= y  is the same as  x = x // y 
  • Example:
    num1 //= num2 

8. = (Exponentiation and Assign) 

  • Performs exponential (power) calculation on operands and assigns the value to the left-side operand.
  •  Note:  x = y  is the same as  x = x  y  
  • Example:
    num1 = num2 

Logical Operators

Python supports three logical operators: and, or, and not. These operators are used to evaluate conditions and return either True or False based on the logical operands involved.

By default, most values in Python are considered True except for specific cases like None, False, 0 (zero), and empty collections such as "" (empty string), () (empty tuple), [] (empty list), and {} (empty dictionary). For example, num1 = 10 and num2 = -20 are both logically True.

Logical AND

  • The condition is True only if both operands are True.
  • Example:
  • True and True returns True.
  • num2 = -20
  • bool(num1 and num2) returns True.
  • True and False returns False.
  • num3 = 0
  • bool(num1 and num3) returns False.
  • False and False returns False.

Logical OR

  • The condition is True if at least one of the operands is True.
  • Example:
  • True or True returns True.
  • True or False returns True.
  • bool(num1 or num3) returns True.
  • False or False returns False.

Logical NOT

  • This operator is used to reverse the logical state of its operand.
  • Example:
  • bool(num1) returns True.
  • not num1 returns False.

Identity Operators in Python

Identity operators are used to check if a variable is of a specific type or to see if two variables refer to the same object in memory. There are two identity operators in Python:

(a) is

  • Description: This operator evaluates to True if the variables on either side point to the same memory location. In other words, it checks if the identity of the two variables is the same.
  • Example:  type(num1) is int checks if num1 is of type int. num1 is num2 checks if num1 and num2 refer to the same object in memory.

(b) is not

  • Description: This operator evaluates to True if the variables on either side do not point to the same memory location. It checks if the identity of the two variables is different.
  • Example: num1 is not num2 checks if num1 and num2 do not refer to the same object in memory.

Membership Operators

Membership operators are used to check whether a value is present in a given sequence, such as a list, tuple, or string.

(a) in

  • The in operator returns True if the specified value is found in the sequence and False otherwise.
  • For example:
  •  a = [1, 2, 3] 
  •  2 in a Output: True
  •  '1' in a Output: False

 (b) not in 

  • The not in operator returns True if the specified value is not found in the sequence and False otherwise.
  • For example:
  •  a = [1, 2, 3] 
  •  10 not in a Output: True
  •  1 not in a Output: False

Expressions

An expression is a combination of constants, variables, and operators that evaluates to a value. It can be as simple as a single value or variable, but a standalone operator does not qualify as an expression. Here are some examples of valid expressions:

  • 100
  • num
  • num - 20.4
  • "Global" + "Citizen"
  • 3.0 + 3.14
  • 23/3 - 5 * 7(14 - 2)

Precedence of Operators

The evaluation of an expression in Python depends on the precedence of operators. When an expression contains different types of operators, precedence determines the order in which they are applied. Operators with higher precedence are evaluated before those with lower precedence.

Binary and Unary Operators

  • Most of the operators are binary, meaning they work with two operands. For example, in the expression  a + b , + is a binary operator.
  • Unary operators, on the other hand, require only one operand and have higher precedence than binary operators. For instance, the unary minus operator  - can be used to negate a value, as in  -depth.

Precedence of Operators in Python

The following table lists the precedence of operators in Python from highest to lowest:
Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Notes on Operator Precedence

  • Parentheses can be used to override the precedence of operators. The expression within parentheses is evaluated first.
  • For operators with equal precedence, the expression is evaluated from left to right.

Examples: How will Python evaluate the following expression?  20 + 30 * 40 
Sol:
= 20 + (30 * 40) #Step 1 #precedence of * is more than that of + = 20 + 1200 #Step 2 = 1220 #Step 3 

Example: How will Python evaluate the following expression?  20 - 30 + 40 

Sol: The two operators (–) and (+) have equal precedence. Thus, the first operator, i.e., subtraction is applied before the second operator, i.e., addition (left to right).
= (20 - 30) + 40 #Step 1 = -10 + 40 #Step 2 = 30 #Step 3 

Example: How will Python evaluate the following expression?  (20 + 30) * 40 
Sol: = (20 + 30) * 40 # Step 1 #using parenthesis(), we have forced precedence of + to be more than that of * = 50 * 40 # Step 2 = 2000 # Step 3 

Example: How will the following expression be evaluated in Python?  15.0 / 4 + (8 + 3.0) 
Sol:  = 15.0 / 4 + (8.0 + 3.0) #Step 1 = 15.0 / 4.0 + 11.0 #Step 2 = 3.75 + 11.0 #Step 3 = 14.75 #Step 4 

Statement

In Python, a statement is a piece of code that can be executed by the Python interpreter.

Example:

  • x = 4. This is an assignment statement where the value 4 is assigned to the variable x.
  • cube = x  * * 3. Another assignment statement that calculates the cube of x and assigns it to the variable cube. 
  • print(x, cube). This is a print statement that outputs the values of x and cube.
  • When the above code is executed, it will display: 4 64

Input and Output in Python

In Python, we can use the input() function to take input from the user. This function prompts the user to enter data and treats all input as strings, regardless of whether the user enters a number or a word.

Syntax of input()

input( [ Prompt ] )

  • Prompt is an optional message that can be displayed to the user before taking input. If specified, it appears on the screen before the user enters data.
  • When the user types data and presses the enter key, the input() function captures it, converts it into a string, and assigns it to the variable on the left side of the equals sign.

Example

  • fname = input("Enter your first name: "). The user is prompted to enter their first name. For example, if the user types "Arnab", the variable fname will store the string "Arnab".
  • age = input("Enter your age: "). The user is asked to enter their age. If the user types "19", the variable age will store the string "19".
  • type(age). This function checks the data type of the variable age. Since the input() function treats all input as strings, age will be of type string.

If we want to convert the string input to a different data type, such as an integer, we can use typecasting. For example, we can convert the age string to an integer using the int() function:

age = int(input("Enter your age: "))

If the user enters a non-numeric value that cannot be converted to an integer, an error will occur.

Outputting Data to the Screen

In Python, the function print() is used to display data on the screen, which is the standard output device. The print() function evaluates the expression provided to it and then shows the result on the screen. print(value [, ..., sep = ' ', end = '\n'])

  • sep. This optional parameter specifies the separator between multiple output values. By default, a space is used as the separator, but you can change it to any character, integer, or string.
  • end. This optional parameter allows you to define a string that will be appended after the last output value. The default setting is to add a new line.

When using the print() function, it's important to note the difference between using a plus sign (+) and a comma (,) to combine strings. A plus sign does not add any space between the strings, while a comma inserts a space. For example:

  • print("Hello" + "World") will output: HelloWorld
  • print("Hello", "World") will output: Hello World

Example:
Statement:
print()
print("Hello")
print(10*2.5)
print("I" + "love" + "my" + "country")
print("I'm", 16, "years old")

Output:

  • 25.0
  • Ilovemycountry
  • I'm 16 years old

Explanation:

  • In the example, the print() function is used to display various outputs.
  • The third print() function demonstrates string concatenation using the + operator to combine strings.
  • The fourth print() function appears to concatenate strings but uses commas to separate arguments. This allows mixing different data types, such as an integer (16) with strings.
  • If different types are used with + instead of a comma, it will result in an error, which will be discussed in the context of explicit conversion in the next section.

Type Conversion

Type conversion in Python refers to the process of changing the data type of a variable from one type to another. This can be done in two ways:

  • Explicit (Forced) Type Conversion: When the programmer specifies the conversion explicitly in the code.
  • Implicit Type Conversion: When the Python interpreter automatically converts the data type when it deems necessary.
Example of Type Conversion

Implicit Type Conversion: 

  • a = 5 # integer b = 2.5 # float c = a + b # c is implicitly converted to float print(c) # Output: 7.5 Explicit 

Type Conversion: 

  • a = "5" # string b = int(a) # explicit conversion to integer print(b) # Output: 5

Explicit Conversion

In programming, explicit conversion, also known as type casting, occurs when a programmer deliberately forces a data type conversion in the code. The general syntax for explicit data type conversion is:

(new_data_type) (expression)

By using explicit type conversion, there is a potential risk of losing information because we are compelling an expression to conform to a specific type. For instance, when converting a floating-point value like x = 20.67 into an integer using int(x), the fractional part .67 will be discarded.

Python provides several functions for explicitly converting an expression or a variable to a different type. Here are some commonly used functions:

Explicit Type Conversion Functions in Python

  • int(x). Converts x to an integer.
  • float(x). Converts x to a floating-point number.
  • str(x). Converts x to a string representation.
  • chr(x). Converts the ASCII value of x to its corresponding character.
  • ord(x). Returns the character associated with the ASCII code x.

Program: Program of explicit type conversion from int to float.

Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Program: Program of explicit type conversion from float to int.


Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Program: Example of type conversion between numbers and strings.

#Type Conversion between Numbers and Strings priceIcecream = 25 
priceBrownie = 45 
totalPrice = priceIcecream + priceBrownie 
print("The total is Rs." + totalPrice )

Program: Program to show explicit type casting. 

#Explicit type casting 
priceIcecream = 25 
priceBrownie = 45 
totalPrice = priceIcecream + priceBrownie 
print("The total in Rs." + str(totalPrice)) 

Output: 
The total in Rs.70 
Similarly, type casting is needed to convert float to string. In Python, one can convert string to integer or float values whenever required.

Program: Program to show explicit type conversion. 

#Explicit type conversion 
icecream = '25' 
brownie = '45' 
#String concatenation 
price = icecream + brownie 
print("Total Price Rs." + price) 
#Explicit type conversion - string to integer
price = int(icecream)+int(brownie) 
print("Total Price Rs." + str(price))

Output: 
Total Price Rs.2545 
Total Price Rs.70

Implicit Conversion

Implicit conversion, also known as coercion, occurs when Python automatically converts data types without explicit instruction from the programmer.

In a program where an integer is added to a float, Python implicitly converts the integer to a float to ensure the operation is carried out without loss of information. This process is called type promotion, where data is converted to a wider-sized type.

For example, consider the following code:
# Implicit type conversion from int to float num1 = 10 
# num1 is an integer num2 = 20.0 
# num2 is a float sum1 = num1 + num2 
# sum1 is the sum of a float print(sum1) print(type(sum1))  

In this example, the integer value in num is added to the float value in  num2 , and the result is automatically converted to a float and stored in  sum1. This demonstrates implicit data conversion.

One might wonder why the float value was not converted to an integer instead. This is because type promotion ensures that operations are performed by converting data to a wider-sized type whenever possible, preventing any loss of information.

Debugging

Debugging is the process of finding and fixing errors or mistakes in a program. When a programmer writes a program, they can make errors that prevent the program from running correctly or producing the right output. These errors are called bugs. There are three main types of errors that can occur in a program:

  • Syntax Errors: These occur when the code does not follow the rules of Python's syntax. For example, if parentheses are not used correctly, like in the expression (7 + 11 without a closing parenthesis, it leads to a syntax error. The interpreter will show an error message and stop executing the program if there is a syntax error.
  • Logical Errors: These errors happen when the code is syntactically correct, but the logic used in the program is flawed. The program runs without any errors, but the output is not what was expected because of a mistake in the logic.
  • Runtime Errors: These occur when the program is running, and an error happens that prevents it from continuing. For example, trying to divide a number by zero will cause a runtime error.
The document Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts is a part of the Humanities/Arts Course Computer Science for Class 11.
All you need of Humanities/Arts at this link: Humanities/Arts
33 docs|11 tests

FAQs on Getting Started with Python Chapter Notes - Computer Science for Class 11 - Humanities/Arts

1. What are Python keywords and why are they important?
Ans. Python keywords are reserved words that have special meaning in the Python programming language. They cannot be used as identifiers (names for variables, functions, etc.) because they are part of the syntax of Python. Keywords are important because they define the structure and flow of the code, making it necessary for programmers to understand them in order to write effective Python programs.
2. How do you define a variable in Python, and what are its rules?
Ans. In Python, a variable is defined by assigning a value to a name using the equals sign (`=`). For example, `x = 10` defines a variable named `x` with a value of `10`. The rules for naming variables include: they must start with a letter or underscore, followed by letters, digits, or underscores; they cannot be keywords; and they are case-sensitive.
3. What types of comments can be used in Python, and how do they differ?
Ans. In Python, comments can be single-line comments, which start with a `#`, or multi-line comments, which are enclosed in triple quotes (`'''` or `"""`). Single-line comments are used for brief explanations, while multi-line comments are useful for longer descriptions or disabling blocks of code. Both types of comments are ignored by the Python interpreter.
4. What are the built-in data types in Python?
Ans. Python has several built-in data types, including: - Numeric types (integers, floats, complex numbers) - Sequence types (strings, lists, tuples) - Mapping type (dictionaries) - Set types (sets and frozensets) - Boolean type (True or False) - None type (represents the absence of a value) These data types are fundamental for storing and manipulating data in Python.
5. Can you explain what an expression and a statement are in Python?
Ans. An expression in Python is a combination of values, variables, operators, and calls to functions that are evaluated to produce another value. For example, `5 + 3` is an expression that evaluates to `8`. A statement, on the other hand, is a complete instruction that performs some action, such as `print("Hello, World!")`. Statements do not return a value and can include expressions within them.
Related Searches

video lectures

,

shortcuts and tricks

,

mock tests for examination

,

Objective type Questions

,

Viva Questions

,

Sample Paper

,

Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts

,

Semester Notes

,

Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts

,

pdf

,

study material

,

ppt

,

Previous Year Questions with Solutions

,

Getting Started with Python Chapter Notes | Computer Science for Class 11 - Humanities/Arts

,

past year papers

,

Free

,

Extra Questions

,

practice quizzes

,

Exam

,

MCQs

,

Summary

,

Important questions

;