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.
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.
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.
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.
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:
When working in script mode, after saving the file, we can run the program by clicking [Run] -> [Run Module] from the menu.
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.
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:
Example
For example:
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
Example 2: Calculating Area of a Rectangle
Output
200
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
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.
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)
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.
Here are the different data types available in Python:
The Number data type is used to store numerical values. It is further divided into three categories: int, float, and complex.
Numeric Data Types
Boolean Data Type (bool)
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
2. Boolean Variable
3. Float Variables
4. Complex Variable
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.
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')
Example
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
(A) Dictionary
Example of Dictionary
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:
Immutable Data Types: These data types do not allow changes to their values once they are created. Examples include:
Example:
Immutable Example:
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.
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.
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:
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.
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)
2. += (Add and Assign)
3. -= (Subtract and Assign)
4. *= (Multiply and Assign)
5. /= (Divide and Assign)
6. %= (Modulus and Assign)
7. //= (Floor Division and Assign)
8. = (Exponentiation and Assign)
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
Logical OR
Logical NOT
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
(b) is not
Membership operators are used to check whether a value is present in a given sequence, such as a list, tuple, or string.
(a) in
(b) not in
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:
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
Precedence of Operators in Python
The following table lists the precedence of operators in Python from highest to lowest:
Notes on Operator Precedence
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:
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 ] )
Example
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.
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'])
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:
Example:
Statement:
print()
print("Hello")
print(10*2.5)
print("I" + "love" + "my" + "country")
print("I'm", 16, "years old")
Output:
Explanation:
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:
Implicit Type Conversion:
Type 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
Program: Program of explicit type conversion from int to float.
Program: Program of explicit type conversion from float to int.
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, 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:
33 docs|11 tests
|
1. What are Python keywords and why are they important? | ![]() |
2. How do you define a variable in Python, and what are its rules? | ![]() |
3. What types of comments can be used in Python, and how do they differ? | ![]() |
4. What are the built-in data types in Python? | ![]() |
5. Can you explain what an expression and a statement are in Python? | ![]() |