Python is a computer programming language often used to build websites and software, automate tasks, and conduct data analysis. Python is a general-purpose language, meaning it can be used to create a variety of different programs
What is Python used for? Python is commonly used for developing websites and software, task automation, data analysis, and data visualization. Since it’s relatively easy to learn, Python has been adopted by many non-programmers such as accountants and scientists, for a variety of everyday tasks, like organizing finances.
What can you do with python? Some things include:
Data analysis and machine learning
Web development
Automation or scripting
Software testing and prototyping Everyday tasks
Why is Python so popular?
Python is popular for a number of reasons.
Here’s a deeper look at what makes it so versatile and easy to use for coders.
It has a simple syntax that mimics natural language, so it’s easier to read and understand. This makes it quicker to build projects, and faster to improve on them.
It’s versatile. Python can be used for many different tasks, from web development to machine learning.
It’s beginner friendly, making it popular for entry-level coders.
It’s open source, which means it’s free to use and distribute, even for commercial purposes.
Python’s archive of modules and libraries—bundles of code that third-party users have created to expand Python’s capabilities—is vast and growing.
Let’s Start
Program : An ordered set of instructions to be executed by a computer to carry out a specific task is called a program.
The Programming language : The Programming language used to specify this set of instructions to the computer is called a programming language. Example: Python, C++, Visual Basic, PHP, Java.
As we know that computers understand the language of 0s and 1s which is called machine language or low level language. Example: Python, C++, Visual Basic, PHP, Java
Working with Python To write and run (execute) a Python program, we need to have a Python interpreter installed on our computer or we can use any online Python interpreter. The interpreter is also called a Python shell. Here, the symbol >>> is called Python prompt, which indicates that the interpreter is ready to receive instructions. We can type commands or statements on this prompt for execution.
It is difficult for humans to write or comprehend instructions using 0s and 1s. This led to the advent of high-level programming languages like Python, C++, Visual Basic, PHP, Java that are easier to manage by humans but are not directly understood by the computer.
IDLE : Integrated Development and Learning Environment
Execution Modes There are two ways to run a program using the Python interpreter:
a) Interactive mode
b) Script mode
Interactive Mode In the interactive mode, we can type a Python statement on the >>> prompt directly. As soon as we press enter, the interpreter executes the statement and displays the result(s), As show in figure:
Working in the interactive mode is convenient for testing a single line code for instant execution. But in the interactive mode, we cannot save the statements for future use and we have to retype the statements to run them again.
Script Mode In the script mode, we can write a Python program in a file, save it and then use the interpreter to execute the program from the file. Such program files have a .py extension and they are also known as scripts. Usually, beginners learn Python in interactive mode, but for programs having more than a few lines, we should always save the code in files for future use.
Python has a built-in editor called IDLE which can be used to create programs. After opening the IDLE, we can click File>New File to create a new file
Step to Run a Program
Choose Run Module form RUN option:
Save the program
Output shown in Interactive Mode
Python Keywords
Keywords are reserved words. Each keyword has a specific meaning to the Python interpreter. As Python is case sensitive, keywords must be written exactly as given in Table
A program written in a high-level language is called source code.
Identifiers In programming languages, identifiers are names used to identify a variable, function, or other entities in a program.
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 given in Table 3.1.
We cannot use special symbols like !, @, #, $, %, etc. in identifiers.
Variable is an identifier whose value can change. For example, variable age can have different value for different person. Variable name should be unique in a program. Value of a variable can be string.In Python, we can use an assignment statement to create new variables and assign specific values to them.
gender = 'M'
message = "Keep Smiling"
price = 987.9
Comment :
Comments are used to add a remark or a note in the source code. Comments are not executed by interpreter. They are added with the purpose of making the source code easier for humans to understand. They are used primarily to document the meaning and purpose of source code
A single line comment starts with # (hash sign). Everything following the # till the end of that line is treated as a comment and the interpreter simply ignores it while executing the statement.
Example 1:
Example 2:
Data Types Every value belongs to a specific data type in Python. Data type identifies the type of data which a variable can hold and the operations that can be performed on those data.
Number Number data type stores numerical values only. It is further classified into three different types: int, float and complex.
Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting of two constants, True and False. Boolean True value is non-zero. Boolean False is the value zero. Let us now try to execute few statements in interactive mode to determine the data type of the variable using built-in function type().
String is a group of characters. These characters may be alphabets, digits or special characters including spaces.
>>> str1 = 'Hello Friend'
>>> str2 = "452"
List List is a sequence of items separated by commas and items are enclosed in square brackets [ ]
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> list1 [5, 3.4, 'New Delhi', '20C', 45]
Tuple Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ( ). This is unlike list, where values are enclosed in brackets [ ]
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
Dictionary Dictionary in Python holds data items in key-value pairs and Items are enclosed in curly brackets { }. dictionaries permit faster access to data. Every key is separated from its value using a colon (:) sign
#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1) {'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
#getting value by specifying a key
>>> print(dict1['Price(kg)']) 120
Operators An operator is used to perform specific mathematical or logical operation on values. The values that the operator works on are called operands. For example, in the expression 10 + num, the value 10, and the variable num are operands and the + (plus) sign is an operator.
Arithmetic Operators Python supports arithmetic operators to perform the four basic arithmetic operations as well as modular division, floor division and exponentiation.
'+' operator can also be used to concatenate two strings on either side of the operator.
>>> str1 = "Hello"
>>> str2 = "India"
>>> str1 + str2
'HelloIndia'
'*' operator repeats the item on left side of the operator if first operand is a string and second operand is an integer value.
>>> str1 = 'India' >>> str1 * 2 'IndiaIndia'
Relational Operators Relational operator compares the values of the operands on its either side and determines the relationship among them.
Conside the given Python variables
num1 = 10
num2 = 0
num3 = 10
str1 = "Good"
str2 = "Afternoon"
Logical Operators
There are three logical operators (Table 3.6) supported by Python. These operators (and, or, not) are to be written in lower case only. The logical operator evaluates to either True or False based on the logical operands on its either side.
Membership Operators Membership operator is used to check if a value is a member of the given sequence or not.
Precedence of Operators So far we have seen different operators and examples of their usage. When an expression contains more than one operator, their precedence (order or hierarchy) determines which operator should be applied first.
How will Python evaluate the following expression?
20 + 30 * 40
How will Python evaluate the following expression?
(20 + 30) * 40
How will the following expression be evaluated? 15.0 / 4.0 + (8 + 3.0)
Assignment Operators Assignment operator assigns or changes the value of the variable on its left
Input and Output Sometimes, we need to enter data or enter choices into a program. In Python, we have the input() function for taking values entered by input device such as a keyboard. The input() function prompts user to enter data. By default It take string value we have to type caste input according to your need (integer or float to do arithmetic Operations).
Expressions
An expression is defined as a combination of constants, variables and operators. An expression always evaluates to a value. A value or a standalone variable is also considered as an expression but a standalone operator is not an expression.
Debugging Due to errors, a program may not execute or may generate wrong output. :
i) Syntax errors
ii) Logical errors
iii) Runtime errors
Syntax Errors Like any programming language, Python has rules that determine how a program is to be written. This is called syntax
Logical Errors
A logical error/bug (called semantic error) does not stop execution but the program behaves incorrectly and produces undesired /wrong output.
Runtime Error A runtime error causes abnormal termination of program while it is executing. Runtime error is when the statement is correct syntactically, but the interpreter can not execute it.
Functions A function refers to a set of statements or instructions grouped under a name that perform specified tasks. For repeated or routine tasks, we define a function. A function is defined once and can be reused at multiple Notes Rationalised 2023-24 Brief Overview of Python 45 places in a program by simply writing the function name, i.e., by calling that function
Python program using three built-in functions input(), int() and print():
#Calculate square of a number
num = int(input("Enter the first number"))
square = num * num print("the square of", num, " is ", square)
if..else Statements Usually statements in a program are executed one after another. However, there are situations when we have more than one option to choose from, based on the outcome of certain conditions. This can be done using if.. else conditional statements.
age = int(input("Enter your age "))
if age >= 18: # use ‘:’ to indicate end of condition.
print("Eligible to vote")
Program to subtract smaller number from the #larger number and display the difference.
Check whether a number is positive, negative, or zero. Using Nested if else
number = int(input("Enter a number: ")
if number > 0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
print("Number is zero")
For Loop Sometimes we need to repeat certain things for a particular number of times
Program to print even numbers in a given sequence using for loop.
#Program 3-4
#Print even numbers in the given sequence
numbers = [1,2,3,4,5,6,7,8,9,10]
for num in numbers:
if (num % 2) == 0:
print(num,'is an even Number')
The range() Function The range() is a built-in function in Python. Syntax of range() function is:
range([start], [stop], [step])
It is used to create a list containing a sequence of integers from the given start value upto stop value (excluding stop value), with a difference of the given step value.
>>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#start value is given as 2
>>> list(range(2, 10)) [2, 3, 4, 5, 6, 7, 8, 9]
#step value is 5 and start value is 0
>>> list(range(0, 30, 5)) [0, 5, 10, 15, 20, 25]
#step value is -1.
Hence, decreasing #sequence is generated
>>> list(range(0, -9, -1)) [0, -1, -2, -3, -4, -5, -6, -7, -8]
Do yourself : Program to print the multiples of 10 for numbers in a given range.
A loop may contain another loop inside it. A loop inside another loop is called a nested loop.
#Program 3-6
#Demonstrate working of nested for loops
for var1 in range(3):
print( "Iteration " + str(var1 + 1) + " of outer loop")
for var2 in range(2):
#nested loop
print(var2 + 1)
print("Out of inner loop")
print("Out of outer loop")
Expression : An expression in Python is a combination of operators and operands. An example of expression can be :
x=x+10 In this expression, the first 10 is added to the variable x. After the addition is performed, the result is assigned to the variable x.
x = 25 # a statement
x = x + 10 # an expression
Statements : An expression in Python is very different from statements in Python. A statement is not evaluated for some results. A statement is used for creating variables or for displaying values.
a = 25 # a statement
print(a) # a statement
Difference between Statements and Expressions in Python
Difference between Compiler and Interpreter
0 Comments