0% found this document useful (0 votes)
2 views17 pages

Chapter 1 Introduction to Python

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 17

Chapter 1 Introduction to Python

Learning Outcome
 Understand the meaning of program and programming
 Meaning of terms like syntax, Interpreter, execution of program
 Learn to code in IDLE screen

Programming is an essential skill in today’s world because programming is used everywhere


in our surroundings. To learn programming, we have to learn a programming language. There
are many programming languages like Java, C++, PHP etc.

Program: An ordered set of instructions to be executed by a computer to carry out a specific


task is called a program.

Programming Languages: The language used to specify this set of instructions to the
computer is called a programming language.

Python is regarded as the simple and easy to learn programming language because of the
following reasons.
 Easy to learn and code.
 It has a simple syntax and readability.
 Python code is 3 to 4 times shorter than Java and 8 to 10 times shorter than C++.
 It can run on various operating systems and hardware platforms.
 Python is used for testing microchips, building video games, web applications and a lot
more.
 Python is also helpful in web development. Many popular web services and applications
are built using Python.
 It has been used by organizations such as NASA, YouTube and Instagram. It is also used
for writing Google Apps.

Who created Python?


Python was created in the year 1991 by Guido van Rossum who is a Dutch programmer.

What is a source code?


A program written in a high-level language is called source code.

Language translators like compilers and interpreters are needed to translate the source code
into machine language.

Python uses an interpreter to convert its instructions into machine language, so that it can be
understood by the computer.
An interpreter processes the program statements line by line.

How to download Python

You can download Python from https://www.python.org/downloads.

Working with Python:


You can work in Python in two ways-
- Interactive mode
- Script mode

How to start Coding in Python (INTERACTIVE MODE)


When you install Python, an IDE named IDLE is also installed. You can use it to run Python on
your computer.
When you open IDLE, an interactive Python Shell is opened.
Opening IDLE : (Windows 7 )

To open IDLE (Integrated Development Environment) follow these steps:


 Click the Start button.
 Click All Programs.
 Select Python.
Click IDLE. The IDLE screen opens- called shell window (Fig 1)

Fig 1

IDLE is a text editor which helps you get your code (program) right. It is also known as the
Python Interactive Mode.

The code that you want to execute is typed after the entry prompt (>>>).

To run/execute a program/code in Interactive mode, press the Enter key.

Example 1: Program to print Hello, Python (Fig 2)


Fig 2

Note: Only text to be printed will be put in double quotes.

Example 2: Program to print 3+4 (Fig 3)

Fig 3

Congratulations! You just wrote your programs in Python.

As you can see, this was a pretty easy task. This is the beauty of the Python programming
language.

How to start Coding in Python (SCRIPT MODE) (Fig 4)


To open script mode, follow these steps:
 Open Python in interactive mode.
 Click the File menu
 Click the New File or New Window option.(as per version)

A new blank window appears to type codes and save it for later use
Fig 4

Type the program in the Window as shown below (Fig 5)

Fig 5

The program in script mode will not run without saving the program.
Saving the program
To Save the program click the File menu and click the Save As option.
Type the file name in the Save As dialog box.
The file is saved with .py as a file extension.
Running a python program
To run the program, click the Run menu and then click the Run Module.
The output of the program appears on shell. (Fig 6)

Fig 6

Syntax and Syntax errors

Syntax is the structure of an instruction in a computer language. It is the grammar of a


programming language.

When the computer executes the program and finds a mistake(s), it shows an error message.
Such mistake in the instruction or code is known as syntax error.

The errors are also known as bugs.

See the example given below.


Comments in a Python program
Comments are important for adding essential information about program statements.
The symbol # (hash) is used to put comments for the line of code. Python ignores the text after
the # symbol. (Fig 7)

Fig 7

Assignments for Practice


Write Python programs to print the following. Add the appropriate Comment lines to
each program.
1. My name is …..(type your name )
2. I study in Class V
3. My hobbies are .….( type your hobbies)
4. My School’s name is…..(type your School name)
5. My favourite subjects are…..(type your favourite subjects)
6. 10+2-5
7. 8*2-10
8. 4/2+12
9. 3*3*3
10. 2*2*2

********************
Chapter 2 Data types Operators in Python:

Python has standard data types as follows:

Data Types Explanation Example


Numbers It stores numeric values only. var=100
It is further classified into three different print (var)
types: Output
int (integers- e.g. 12,3,-2), 100
float(real or floating point numbers.-
e.g. 4.1,7.8)
and complex (for complex numbers).
String It stores a set of characters str=’Hello World!’
represented within quotations. print(str)
Output
Hello World
List List is a sequence of items separated list1 = [5, 3.4, "New Delhi",
by commas and the items are enclosed "20C", 45]
in square brackets [ ]. print(list1)
Output
[5, 3.4, 'New Delhi', '20C', 45]

Math in Python
You can use python as a calculator. Following are a few examples. You will get output
in blue colour.
Operators in Python
Operator Name Example Answer
+ Add 5+5 10
- Substract 5-5 0
* Multiply 5*5 25
/ Divide 5/2 5//2 2.5 2
% Modulus (Remainder) 20%8 4
** Exponent 2**5 32
Practical Activity:
Python Statements:
1. print(“3+2 is an addition”)
2. print(“Addition=”,3+2)
3. print(“21 divided by 3=”,21/3)
4. print(“18 divided by 5=”, 18/5, “remainder=” , 18%5)
5. print(“18 divided by 5=”, 18//5, “remainder=” , 18%5)

Observe the output of statements 4 and 5.


Comparison Operators:
These are logical operators that are used to compare values.
List of comparison operators:
Operator Meaning
== Equal To
!= Not equal to
> Greater Than
< Less Than
>= Greater than equal to
<= Less than equal to
In programming languages a double equal to ( ==) sign is used to compare two values
and single equal to (=) sign is used to assign values.
Practical Activity:
Compare two values and print the result
x=20
y=15
print( “x>y is” , x>y)
print( “x<y is” , x<y)

********************
Chapter 3 Inputs in Python

Python language provides numerous in-built functions that can be used at the Python
prompt. Functions like input( ) and print( ) are widely used for input and output
operations respectively. You have learnt the print ( ) function, now let’s learn how to
use the input () function.
input () gives flexibility to take input from the user.
Syntax:

input ( [ prompt ])
where ‘prompt’ is the string you wish to display on the screen. It is optional.

Practical Activity:

>>>num= input (“Enter a number :” )


Enter a number: 33
>>> num
‘33’ (output)

To convert strings such as ‘33’’ into a number use int ( ) or float ( ) functions.

Practical Activity :
Write a program to add two numbers provided by the user.
Same program can be written in other way also , check the following:

Practical in Script Mode with float ( ) function:


Write a program to find out the area of the rectangle where length and breadth
provided by the user.

Output:

********************
Chapter 4 Conditional Statements in Python

Like other programming languages,conditional statements check for the condition and
accordingly evaluate the result.
Python assumes any non zero and non null values as TRUE, and if it is either zero or
null,then it is assumed as FALSE value.

Python provides the following types of decision making statements.


● if statement
● if ….else statement
● elif statement

If Statement

The if statement contains a logical expression. By using this expression ,the data is
compared and a decision is made based on the result of the comparisons.

Syntax:

if condition :
statement(s)

If the condition evaluates to TRUE,the block of statement(s) inside the if statement is


executed.If condition evaluates to FALSE, the first set of code after the end of the if
statement(s) is executed.

The indentation implies that its execution is dependent on the condition. There
is no limit on the number of statements that can appear as a block under the if
statement.
Practical Activity:
Write a program to check if the number is positive and print the message. Ask the user
for input a number.

# If the number is positive, print a message


num=float(input(“Enter a number:”))
if num > 0 :
print(“Positive number”)
Output

If …..else statement
An else statement can be combined with if statement that will execute if the condition
resolves FALSE value.

Syntax:
if condition:
statement(s)
else:
statement(s)
Practical Activity:

# Program to check if number is positive or negative.


num = float(input("Enter a number:"))
if num > 0:
print("Positive number")
else:
print("Negative Number")
Output:

If…elif…else Statement:
The elif statement allows you to check multiple conditions for True. It executes a block
of code as soon as one of the conditions evaluates to true.
Syntax:
if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
Practical Activity:
Write a program to check if the number is zero, positive or negative. Print appropriate
message. And ask the user to input a number.
# Program to check if number is positive or negative or zero.
num = float(input("Enter a number:"))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative Number")
Output:

********************
Chapter 5 Logical Operators and loops

There are three logical operators 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 either side.
Every value is logically either True or False. By default, all values are True
except None, False, 0 (zero), empty collections "", (), [], {}, and few other
Special values.
So if we say num1 = 10, num2 = -20, then both num1 and num2
are logically True.

Operator Operation Description

and Logical AND If both the operands are


True, then condition
becomes True

or Logical OR If any of the two


operands
are True, then condition
becomes True

not Logical NOT Used to reverse the


logical
state of its operand

********************
Chapter6 Basics of for Loop

Sometime in programming language you need to execute a block of code repeatedly,


this repetition of the statement is controlled by iterative statements in python. Python
supports two types of loops
1. for
2. while

for loop : The for loop is used when you are sure about how many times a loop body
will be executed. It is known as definite loop.

Syntax
for<variable> in range(initial value,final value,step value):

Examples
for i in range(1,5)
output
1
2
3
4
Remember the value displayed would be from 1 to 4
for i in range(1,10,2)
output
1
3
5
7
9
Programs
1. Write a program to display first 10 natural number.
2. Write a program to find sum of odd numbers between 10 and 30
3. Write a program to display table of input number.
4. Write a program to input start value, stop value and step value and display the
output (Assuming start<stop)
********************

You might also like