100% found this document useful (1 vote)
1K views

Computer Applications Arihant

Python is an object-oriented programming language created by Guido van Rossum in 1989. It is designed for rapid prototyping and has interfaces for many operating systems and libraries. Python is widely used in fields like artificial intelligence, natural language processing, and neural networks. Some key features of Python include being easy to learn due to its simple structure and syntax. Python code is also portable and can run on many hardware platforms. Additionally, Python allows for extending functionality through modules written in other languages like C/C++.

Uploaded by

Ajay Arora
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views

Computer Applications Arihant

Python is an object-oriented programming language created by Guido van Rossum in 1989. It is designed for rapid prototyping and has interfaces for many operating systems and libraries. Python is widely used in fields like artificial intelligence, natural language processing, and neural networks. Some key features of Python include being easy to learn due to its simple structure and syntax. Python code is also portable and can run on many hardware platforms. Additionally, Python allows for extending functionality through modules written in other languages like C/C++.

Uploaded by

Ajay Arora
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

CHAPTER

09
Python: Programming
Language
Chapter Checklist Revision of Python Basics
Python is an object oriented programming language created by Guido Van Rossum in
oRevision of Python Basics
1989. It is a high level, interpreted and interactive language. Python is ideally designed
Features of Python for rapid prototyping of complex applications. It has interfaces for many operating
Python Character Set system calls and libraries. It is extensible to C or C++. Python is widely used in artificial
Token intelligence, natural language generation, neural networks and other advanced fields of

Running Python computer science.


A Simple Python Program
Data Types in Python
Features of Python
Python has following features
Python Variables
Arithmetic Operators Easy to learn Python has few keywords, simple structure and a
clearly defined syntax. This
allows the student to pick up the language quickly.
o FLow of Control
Portable Python can run on a wide variety of hardware platforms and has the same
oSelection Statements interface on all platforms.
o lterative Statements Extendable You can add low-level modules to the Python interpreter. These modules
more efficient.
enable programmers to add or to customise their tools to be

that can be created and ported to


GUI programming Python supports GUI applications
libraries and windows systems, such as Windows, Macintosh and Unix.
many system calls,
source software. You can freely
distribute copies of this
Open source Python is anopen
software's s o u r c e code and make changes to it.
software, read the

+latteam tnndopemdenk
176 Allinone Computer Applications Class 10th

Invalid ldentifiers

Python Character Set Explanation


Identifier identifier
Character set is a set of valid characters that, a language Keyword name cannot be
given to
n
can recognise. A character represents any letter, digit or allowed.
num2 Special characters are not
other sign. The character used in a Python source program Python
allowed in programming
belongs to the ASCIl (American Standard Code for num 1 Spaces are not
for declaring identifier.
language
Information Interchange). character
2num Digits are allowed butnot asfirst
Python supports the following character sets
Alphabets Ato Z(upper case), a toz (lower case) 2. Keywords
Digits O to 9 predefined reserved words by the
Keywords are
have some special or
Special Space 0 +-/\^& %# ${}U_> <?@.: programming language that
for special
Characters "etc
predefined meanings. These
are reserved
identifier names.
White Space Blank Space, Horizontal tau (-), Carriage return( and must not be used
as
purpose
). Newline,Form feed, Line terminators contain lowercase letters only.
All the Python keywords
Other Python can process all ASCll and unicode in Python which are listed
Characters characters as part of data or literals Some commonly used keywords
below
False None True
Token exec not
and
A program consists of various statements and statement
as finally or
comprises a sequence of atomic units called tokens. pass
break for
A token is the smallest element of a Python program that print
class from
is meaningful to the compiler.
The Python parser recognises these kinds of tokens;
continue global raise

def return
identifiers, keywords, literals, operators and punctuators.
del import try
also calLd
Vakable) in while
elif
1. ldentifiers with
Identifiers are the fundamental building blocks of a else IS
except lambda yield
program which are used to give the name to data items
include by the programmer. The identifier is a sequence of
characters taken from the Python character set. 3. Literals or Constants
The rules in Python for identifiers are Literals refer to fixed values that the program may not alter
) Only Alphabets, Digits and Underscores are permitted. during the execution. They are used to express particular
Gi) Identifier name cannot start with a digit. values within the Python program.
ii) Keywords cannot be used as identifier. Python allows several kinds of literals
(io) Upper case and lower case letters are distinct because ) String literals i )Numeric literals
Python is case sensitive language. Gi) Boolean literals 1 (iv) Special literal None
) Special characters are not allowed except for () Literal eollectíons
underscore).
e.g.
4. Operators
Valid ldentifiers
Operators those tokens that perform
are a specific task/
ldentifier Explanation computations when applied on variable or some other
Name Capital letter with small letters are allowed objects in an expression (known as operands). Python
carries a wide range of operators which are as follows
name Smallletters are allowed
name 1 Digits and underscore are allowed along with () Arithmetic operators ) Comparison operators
alphabets. Gi) Logical operators (io) Bitwise operators
IN Keywords are allowed but we have to change case of
(Assignmentoperators (vi) Special operator
anyletter or complete word.
Underscore at the first position is allowed (vit) Membership operators
SUM
177
Python: Programming Language

5. Punctuators A Simple Python Program


Punctuators are also called as separators as it is used Let us execute programs in different modes of programing
to separate line of codes, variables etc.
Punctuators in Python have syntactic and semantic1. Interactive Mode Programming
meaning to the compiler but do not specify an
Involving the interpreter without passing a script file as a
operation that yields a value.
parameter brings up prompt where you can type the following
The following characters are used as punctuators in text and press Enter.
Python >>
print "HelloHorld
"#0 00@,:. If you are running new version of Python, then you would need
to use print statement with parenthesis as in print ("Hello
Running Python World")
There three different ways Output Hello World
are to start Python
1. Interactive Interpreter 2. Script Mode Programming
You can start Python from Unix, DOS or any other Invoking the interpreter with a script parameter begins execution
system that provides
you a command line of the script and continues until the script is finished. When the
interpreter or shell window. script is finished, the interpreter is no longer active.
Enter Python the command line. Let us write a simple Python program in a script. Python files
Start coding right away in the interactive have extension -py.
interpreter. Type the following source code in a test.py file print "Hello
$ Python # Unix/Linux World"
or
We assume that you have Python interpreter set in PATH
Python &# Unix/Linux
or
variable. Now, try to run this program as follows
$ Python test.py
C:>Python #Window/DOS
Output Hello World
2. Script from the Command Line
Python script be executed at command line by
can

invoking the interpreter on your application, as in


Check Point 01
1 Which one is valid identifier?
the following
$ Python script.py #Unix/Linux a)INT (b) is () import (d) sum 1
or
Python script.py # Unix/Linux
2 Which words are reserved for special purpose in Python? ReyeAo
,... are also called as separators. Bumustuatov
or
C:>Python script.py # Windows/DOS Data Types in Python
Every value in Python has a data type. Since everything is an
3. Integrated Development object in Python programming. Data types are actually classes
Environment (IDE) and variables are instance (object) of these classes.
You can run Python from a Graphical User Python has five standard data types: Numbers, String, List, Tuple
Interface (GUI) environment as well, if you have a and Dictionary. But here we will only discuss Numbers and
GUI application on your system that supports String data types.
Python.
If you are not able to set up the environment Numbers Data Type
properly, then you can take help from your system Numbers are created by numeric literals. Numeric objects are
admin. Make sure the Python environment is immutable which means when an object is created its value
properly set up and working perfectly fine. cannot be changed.
178 Allinone Computer Applications Class 10th

Python numbers data type is used to hold numeric Output


values ns 100
0 int It holds signed integers of nonlimited length. Aryan
Gi) long It holds long integers, they can also be
represented in octal and hexndecimal. Multiple Assignmenls to multiple variablen In a
Gi) float It holds flonting precision numbers. It is Python allows us to a8sign a value
which is also known as multiple ansignment
accurate upto 15 decimal places aingle statement as follows
(i0) complex It holds complex numbers and containa We can apply multiple ansignments in
two ways

integer in the range O to 255.


Assigning Single Value to Mulliple Variables
You can ssign same value to multiple variables in a single
String Data Type
8tntement.
String is a sequence of unicode characters. Python uses
C8, Xy z l
single quotes or double quotes to represent strings. 1 and all
Multiline strings can be denoted using triple quotes, Here, integer object is created with the value
an
location,
o r " three variables are assigned to the same memory
Variables
Special Characters in Strings () Assigning Multiple Values to Mulliple
varlables in
You can even assign multiple values to multiple a
The backslash () character is used to introduce a
single statement.
special character. Following table has some special
symbol .g, a, b, c=5,8, "Rahul"
It will assign the values order wisc, I.e. two integer objects
Symbol Meaning
In New line with values 5 and 8 are a8signed to variables a and b
Horizontal tab
respectively. One string object with the value "Rahul" is
assigned to the variable c.
Backslash

Singlequoe Arithmetic Operators


Double quotes These operators are used to do arithmetie operations. These
operators are mainly divided in two types
Python Variables
Python variable is a reserved memory location to store 1. Binary Operators
values. In other words, a variable in a Python program The operators that work upon two operands are known as
gives data to the computer for processing. binary operators. Python arithmetic binary operators include
Variable names can be a group of both letters and digits, Addition, Subtraction, Multiplication, Division, Floor
but they have to begin with a letter or an underscore. Division, Exponent and Modulus.
Variable name should not be a keyword.
Addition Operalor(+
This operator is used to add the values of its operands.
Declaring Variable and Assigning Values
Python does not bound us to declare variable before e.g. if x=4, y=6 then (x +y) gives the resule 10.
using in the application. It allows us to create variable at Subtraction Operator(-)
required time. We don't need to declare explicitly
variable in Python. When we assign any value to the
This operator is used to calculate the difference between two
numbers.
variable that it is declared automatically.
The equal ( operator is used to assign value to a e.g. ifx=10, y =3, then x-y) gives the result 7.
variable. Multiplication Operalor (")
e.g >>> X = 100
This operator is used to calculate the product of two
numbers.
>>> Name = "Aryan"

>>> print (x) e.g. If x=3, y=7


>>> print (Name) then (x'y) gives the result 21.
modul o
179
Python: Programming Language

Division Operator /)
This operator is used to divide a number by another
Check Point 02 numbers?
number. 1 Which numbers data type holds floating precision
e.g. If x=6 and y=3 (a) complex (b) int
o loat (d) long
then (/y) gives the result 2. 2 Write the symbol which is used in String for horizontal tab. \E

Floor Division Operator //) 3 What is unary plus operator?

lt is the division of operands where the result is the


quotient in which the digits after the decimal point are Flow of Control
removed.
Flow of control refers to the order in which the individual
e.g. If x=16.5, y=4 executed. Control
statements, instructions of a program are

then (x//y) gives the result 4.0. statements allow the programmer to change the CPU's path
through the program. Every programming language
Exponentiation Operator (**) supports various types of control structures as sequence,
It performs exponentiation (power) calculation. It selection and iteration.
returns the result of a number raised to a power.
eg. If x =2, y =3 (i) Sequence
then (x*"y) gives the result 8. Sequence control means the statements are being executed
sequentially. Sequence structure is also known as straight
Modulus Operator (% line path.
This operator is used to find the remainder when its one
Statement 1
operand is divided by its other operand. Both the
operands must be of integer type.
Statement 2
e.g. If x =9, y=2 Statement 3
then (%y) gives the result 1.
Statement n
2. Unary Operators (i) Selection
Those operators that work on single operand to form an set
When programmers are required to execute a particular
expression are known as unary operators. These are two particular test condition,a
basic unary operators of statements depending upon a

branching statement is required.


Unary Plus l+) Operator
It precedes an operand. The operand must have
Condition True Statement 1
arithmetic type, and result is the value of the argument.
In simple words, it makes an expression positive.
False Statement 2
eg. If x=7 then +x =7 Statement 1"
if x=-7
then +x =-7
Statement 1

Unary Minus Operator


This operator is used to negate numbers of the integers, (TT) Iferafion
floating-point and decimal type. It reverses the sign of the It means repetition of a set of statements, depending upon a
operand's value. test condition. Till the time a condition remains true, a set
e.g. If x =7 then -x =-7 of statements are repeated again and again. Iteration is also
if x=-7 then -x =7 known as looping or repetition.
Class 10th
Allinone Computer Applications
180

(i) if else statement conditional expression. If


This s t a t e m e n t also
tests a

Condition False the entire block of statements


the condition is True, Otherwise, the entire
be executed.
True following the if will the else will be executed.
block ofstatements following
Statement1
Statement2" Body of else
Condition False
True
Selection Statements Bodyofif
or
These statements allow a program to execute a statement
set of statements depending upon a given condition. These
also called conditional statements or decision
statements are Syntax if (conditional statement):
statements.A seiection statement is a control statement that

paths in a
allows choosing between two or more execution statement(s)
program. else
Python provides below types of selectors: statements(5)

(i) if statement e.
The simplest and most common selection structure is the if y=3

statement. The if statement allows branching depending X = X+ y

upon the value or of variables. If the condition evaluates


state if (x >y):
print ("x is greater")
True, an action is followed otherwise, the action is ignored.
else
are in else part because x is not
print ("We
greater")
Condition False
Output
We are in else part because x is not greater.
True rolbelo2 in else
Bodyofif In above code, produces an output as "We are
because x is not greater". Because the conditional
part
statement under if0 evaluates as false x is not greater
than y, it is same as that of y.

Syntax if(conditional expression): Iferative Statements


statement(s) Iterative statements or loops enable a program with a
flow of logic. Each written
which is
e.g. cyclic statement

X =1 under the scope of a looping statement gets executed


y = 3
the number of times the iteration/looping
X = X + y
continues for.
if (x> y):
print ("x is greater") A looping statement enables repetition of tasks under
its scope based on a particular condition called as loop
Output x is greater noitorel condition. This loop condition evaluates to either True
In above example, produces an output as "x is greater". or False. A loop may be continued till a loop condition
Because the conditional statement under if0 will be always is evaluated as true.
evaluated as True.
oboge of
Python: Programming Language 181

Various types of loops in Python follows.


(i) while loop
are as

Check Point 03
1 Which of the following loop tests its condition before executing the
A while loop tests for its ending condition before statements in Python?
executing the statements enclosed in the loop body (a) while (b) for (o) do..while (d) if
even the first time. So if the
ending condition is met 2 Write the syntax of for loop
when the while loop begins, the lines of instructions 3 Draw the flow diagram for if statement.
it contains will never be carried out.

Syntax Programs
while (loop-condition): Program 1 For accepting an integer from user and

loop-body checking if this integer is greater than 10.


e.g. Sum of first 10 natural numbers a=int(input("Enter the value:"))
n=int if (a>10)
(input ("Enter the number: "))
print(a, "is greater than 10. ")
print (The number is:", n)
Sum =0 Output
i = 1 bed Enter the value: 40
while (i=n)-
Sum =Sum + i 40 is greater than 10.
i =i+ 1 2 For adding a number to non-zero real
print ("The sum is". sum)
Program
number x. g
Output Sum 100.00
Enter the number: 10 x=float(input("Please enter a real number: "))
print("Real number is:", x)
The number is: 10
if (x!=0.0):
The sum is 55 sum = sum+X

print("The sum is:", sum)


(i) for loop
Output
The for statement encloses one or more statements
Please enter a real number:56.8
that form the body of the loop. The statements in
Real number is:56.8
the loop repeat continuously a certain number
of times. The sum is: 156.8

Syntax Program 3 For asking yes or no


a user to answer to a
question such as "Are you ready to provide your credit
for variable> in <sequence> card number".
statements ans=input( "Are you ready to provide your credit
e.g. Sum of first 10 natural numbers card number (1=Yes/0=No): ")
n-int(input ("Enter the number: ") print("User choice is:", ans)
print ("The number is:", n) if(ans ="1') :
Sum = 0 print("\nNow we will continue processing the
i =1 transaction")
for i in range (1, n+1): if(ans= ='0'):
Sum=Sum + 1 print ("\nNow we will not continue processing
i =i +1 the transaction")
print ("The sum is", sum)
Output
Output Are you ready to provide your credit card
Enter the number : 10 number(1=Yes/0=No):1
The number is: 10 User choice is:1
The sum is 55 Now; we will continue processing the transaction
Allinone Computer Applications Class 10th
182

odd with n=n-1


Program 4 To find the number is cven or

compound statement.
print("The factorial of number 1s:",f)

n=int(input ("Enter the number: ")) Output


print("The number 1s:".n) Enter any number:5
if (n2--0): Number is :5
print("Remainder on division by 2 is:") 120
The factorial of number is :

print (n2) for loop to print


print("The number is an even number") Program 6 Using the
numbers from 1 to 10.
else:
1-1
print("Remainder on division by 2 is:")
for i in range (1,10+1)
print(n&2) print(1)
print("The number is an odd number")
Output
Output 1
Enter the number:55 2
The number is: 55 3
Remainder on division by 2 is:1
The number is an odd number

Program 5: To find factorial of a given number. 6


f=l
n=int(input ("Enter any number: "))
print ("Number is:".n)
while (n>0): 9
f f*n 10

SUMMARY
general-purpose programming
Python is an interpreted high-level programming language for
Python was created by Guido Van Rossum in
1989.
sets.
Python uses the traditional ASCII character
function, class, module or other object.
A Python identifier is a name used to identify a variable,
that cannot be used as ordinary identifiers.
Keywords in Python are reserved words
that carry out arithmetic or logical computation.
Operators are special symbols is Python
to store values.
Variables are nothing but reserved memory locations
being executed sequentially
Sequence control means the
statements are
a test condition.
Iteration means repetition of a set of statements, depending upon
i f statement allows branching depending upon the
value or state of variables.
while loop statement repeatedly executes a target statement as long as a given condition is true
times and abbreviates the code that manages the loop variable.
for loop executes a sequence of
statements multiple
Exam Practice
(Multiple Choice Questions [1 Mark each]

1 Which of the following is the


smallest Ans. (b) When prefixed with the letter ' or 'R' a string literal
element of a Python becomes a raw string and the escape secquences such
(a) Token program?
(b) Operator asin are not converted.
(c) Character set
(d) None of these 5 Which of the following is an invalid variable?
Ans. (a) A token is the smallest element
of a Python program (a) my_string_1 (b) 1st string
that is meaningfulto the
compiler. (c) foo (d)_Num
2 Which is the correct Ans. (b) Variable names should not start with a number.
(a) x Y
operator for power?
(b) X**Y
(c)X (d) x powy
6 Which one of these is floor division?
Ans. (b) In (a) / (b) (c) % (d)
Python, power or
exponentiation is x"y
i.e. 3*2-9 Ans. () 1I is a floor division operator.
When both of the
3 Which of the operands are integer then Python crops out the
following is/are punctuator of fraction part and gives you the round off value.
Python language? 7
(a) () (b) Sequence structure is also known as.
(a) straight line path (b) flow of control
(c) (d) All of these
(c) selection (d) iteration
Ans. (d) Python, punctuator is used to separate line of
code. Ans. (a) sequence structure is also known as straight line path.
0. ), 0, #, @ etc.
4
What is the output when 8 Which of the following statements allow a
following code is
program to execute a statement?
executed?
>>> print r"\nhello" (a) Selection (b) Assignment
(c) Conditional (d) Both a and c
(a) a new line and hello
(b) Inhello Ans. () Sclection or conditional statements allow a program
(c) the letter r and then hello to execute a statement or set of statements depending
(d) error upon a given condition.

Fill in the Blanks [1 Mark each]

T Python is a/an .... Ans. 2.0


programming
language. 7 Selection statement are also called..
Ans. object oriented
statements.
i s a sequence of characters taken from Ans. conditional or decision.
Python character set.
8 statements or loops enable a program
Ans. Identifier
with a cyclic flow of logic.
3 Sum 2 is a/an ......... identifier. Ans. Iterative
Ans. invalid
9 In for loop syntax,
4 Python files have extension for <variable> in.......
Ans. -Py statements
Ans. <sequence>
indicates labeled statement or
. a

conditional operator symbol. 10 . repeats continuously a certain number


of times.
Ans. Colon )
6 a =4.5, b =2 print a// b given the output.. Ans. loop
184 Allinone Computer Applications Class 10th

(True or False [1 Mark each]


1 Python code is easy to read. 6 Arithmetic operators are mainly divided in
Ans. True Python code is more clearly defined and easily two types.
read to user. Ans. True Arithmetic operators are mainly divided in two
types as Binary operator and Unary operator,
2 Sum_of_numbers is a valid identifier in
Python. 7 Sequence control means the statements are
Ans. True In Python, we can concatenate multiple words being executed randomly
with underscore Ans. False Sequence control mecans the statements are being
executed sequentially.
3 long data type holds signed integers of
non-limited length. 8 Iteration is also known as looping or
Ans. False int data type holds signed integers of non-limited repetition.
length. Ans. True Iteration is also known as looping or repetition.

4 Multiline strings can be denoted using triple 9 Iterative statements evaluate to either True or
quotes False.
Ans. True
Muliline strings can be denoted using triple Ans. True Iterative statements enable a program with a cyclic
quotes"or """ flow of logic which evaluates to cither True or False.

5 abc 1000 2000 3000 is a valid statement. 10 if statement executes a sequence of


statements multiple times.
Ans. False It is a invalid statement because spaces are not
allowed in variable names. Ans. False for loop executes a sequence of statements
muliple times.

(Very Short Answer (VSA) TYpe Questions [1 Mark each]

Whowas developed the Python language? 7 Which symbol is called the assignment
Ans. Python was developed by Guido Rossum in 1989. operator?
Ans. The symbol = is called the assignment operator.
2 What do you mean by Python character set?
Ans. Character set is a set of valid characters that a language 8 Draw the flow chart of sequence control
can recognise. structure.
Ans.
3 Write a short note on token. Statement1
Ans. A smallest individual unit in a program is known as
token. Statement2
4 Define the concept of constant in Python. Statement 3
Ans. Constants are the data values that can never change
their values during program execution Statement n
5 Write the name of any four punctuators used 9Explain the term selection statement in
in Python program.
Python.
Ans. Brackets 0, Parenthesis 0, Braces {}, Colon: Ans. Selection statement is a control statement that allows

6 How many types of constant are there in choosing berween two or more execution paths in a
program.
Python?
Ans. 10 Write the syntax of if statement.
Python allows five types of constants
String, Numeric, Boolean, Special None and Literal Ans. if (conditional expression):
collection. statements
Python: Programming Language 185

How many loops are there in Python 12 What is the syntax of while
loop in Python?
programming? Ans. while (loop-condition):
Ans. There are two
loops in Python programming as
(G) for loop
(i) while loop
loop-body

Short Answer (SA) Type Questions [2&3 Marks each]


T Mention the various
Python.
characteristics of c.g, >>> a = 10

>>> city="Meerut"
Ans. Python has the following features >>printa
() It has a large and broad >>print city
library.
(i) It has support for an
interactive mode. Output
ii) Python is an open source sofrware.
10
2 Which of the Mcerut
following are invalid names and
why?
G) PaidInterest (i) S-num 6 Write one example of following terms
(iii) Percent (iv) 123 (1) Identifier (ii) Punctuator
(v) abc km (vi) class (ii) Keyword
Ans. () Valid. Ans. () Identifier Sum_1 (ii) Punctuator Bracket 0
(i) Invalid, () is not allowed in the variable name. i) Keyword import
(ii) Valid. 7 Draw the flow diagram of selection
(iv) Invalid, first character must be alphabet. statements in Python.
Invalid, spacing is not allowed. Ans.
(vi) Invalid, class is a keyword.
3 Differentiate between identifier and
keyword. Condition True Statement 1J
Ans. Differences between identifier and keywords are as
follows False Statement2
Statement 1
Identifier Keywords
ldentifier is a name given to Keywords are predefined Statement1"
a class, interface, function reserved words that have
or variable. special meanings.
Identifier consists any Keyword must consist only
combination of letters
8 Explain the if else statement in Python.
letters
numbers and underscores. Ans. if else statement also tests a conditional expression. If
the condition is true, the entire block of statements
It allows both upper case It allows only lower case
and lower case. except False, None, True. following the if will
be executed, othewise the entire
block ofstatements following the else will be executed.
The purpose of identifier is We cannot use keywords
to provide names to for naming classes, 9Write output ofthe following code.
program elements. functions or variables. X = 4

y = 5
4What do you mean by Punctuators?
if (x> y):
Ans. Refer to text on Page No. 177.
print ("x is greater")
5 How to declare the variable and assigning else
values in Python? print ("y is greater")
Ans.
Pyrhon does not bound us to declare variable variable
before Ans. Output
using in the application. It allows us to create
at
y is greater
required time. The equal () operator is used to assign
value to a variable.
186 Allinone Computer Applications Class 10th

10 Observe the 12 Write the code to print following pattern.


given code and write the output.
sum 50.00 2
X = 86.4 22
if (xI=0.0) 222
sum S um +x 2 222
print("Real number is:", x) Ans. n =2
print("The sum is:", sum) for x in range (4):
Ans. Output print(n)
Real number is: 86.4 n = n* 10 + 2

The sum is: 136.40 13 Rewrite the following code after removed all
What will be the output of the following code: syntatical errors and underline each.
X = 2 n-input (1nt("Enter the number"))
sum 0
forx in range (2, 20+2,
+2) i 1
print (x) while 1(=n
Ans. Output
sum + 1 = Sum
2 1 = 1 + 2
print(sum);
6 Ans. Correct code is:
8 n-int input("Enter the number"))
10 sum 0
12 i = 1
14 while i=n:
16 Sum= Sum + 1
18 i= i + 2
20 print (sum)

Long Answer (LA) Type Questions [5 Marks each]


Determine which of the following identifiers 2 How will you run a simple program in
are valid? If invalid, explain with reason. Python?
() name 1 (i)_SUM Ans. Refer to text on Page No. 177.
(ii) Ssum iv num^2
(v) Name 3 What do you mean by Arithmetic operator?
Ans. The valid identifiers are Ans. Refer to text on Page No. 178.

Identifier Reason 4 Write the Python code to display Fibonacci


0 name1 Digits and underscore is allowed series as 0112358 13 21 34
along with alphabets. Ans. a =0
(7) SUM Underscore at the first position is
b 1
allowed
(V) Name Capital letter with small letters are
print("Fi bonacci series:")
allowed. print(a, end=" ")
print (b, end=" *)
The invalid identifiers are
for x in range (1, 9).
dentifier Reason iC a +b
il) Ssum $ sign can be used in other print (c, end = " )

programming languages for creating


identifier, however Python do not a, b b, C
Support '$' sign.
(iv) num^2 Special characters are not allowed
Python: Programming Language 187

Write the
program with appropriate output to
enter three numbers print("These angles will not make a

and triangle. ")


which is greatest number display that number
Ans. among them. Output
Enter first angle:45.6
a=int(input ("Enter first number:") Enter second angle:44.4
b=int(input ("Enter second number: ")) Enter third angle:90.0.
c=int input ("Enter third number:")) These angles will make a triangle.
print( a=",a)
print("b=",b) 7What do you mean by ifstatement in Python?
print("c=", c) Explain with an example and syntax.
if(a>b and a>c) Ans. Refer No.
to text on Page 180
print("a is greatest")
elif(ba and b>c 8 Python program to check whether a number

print("b is greatest") is prime or not.


a else: S S A0 Ans. n-int (input ("Enter the
print("c is greatest") print("n=".n)
number:
Output if n>1:
Enter first number: 45 for i in range(2,n//2):
1f (n%i)== 0:
Enter second number: 76
print(n, "1s not a príme number")
Enter third number: 23
break
a=45 ob
else:
b=76 print(n, "is a prime number ")
23 else:
b is greatest print(n, "is not a príme number")

O
Input three angles and determine if
Output
they Enter the number:67
make a triangle or not
Ans. n=67
a=float (input("Enter first angle:")) 67 is a prime number
b-float(input("Enter second angle:"))
ang
c=float(input("Enter third
sum=a+b+C
A >>>

Enter the number:78


if(sum= =180): 78
print("These angles will make a triangle.") 78 is not a prime number
else:

(Application Oriented Questions


Create variables for the following Z These are the fundamental building blocks of
i) to holdatrain number a program which are used to give the name to
(i) to hold the name of a subject data items included by the programmer. What
(ii) to hold balance amount in a bank account is it?
(iv) to hold a phone number Ans. Identifiers
Ans. (i) train_numn
(i) subject_name
(iii) balance amt Civ) phone_no

You might also like