Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
22 views23 pages

Python 18 Sept 24 09 14 00

Python is a general-purpose programming language known for its ease of use, expressive syntax, and cross-platform capabilities, though it is not the fastest and has fewer libraries compared to languages like C++ and Java. It can be used in interactive or script mode, with the latter preferred for larger programs. Python has various distributions, including Anaconda for scientific computing, and supports multiple IDEs such as Spyder and Jupyter Notebook.

Uploaded by

sunilcentral17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views23 pages

Python 18 Sept 24 09 14 00

Python is a general-purpose programming language known for its ease of use, expressive syntax, and cross-platform capabilities, though it is not the fastest and has fewer libraries compared to languages like C++ and Java. It can be used in interactive or script mode, with the latter preferred for larger programs. Python has various distributions, including Anaconda for scientific computing, and supports multiple IDEs such as Spyder and Jupyter Notebook.

Uploaded by

sunilcentral17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Characteristics of Pvthon

Advantages:
Easy to use.

Expressive language.
Interpreted language:

Its completeness
Cross platform language.

Free & open source


Variety of usage /applications

Disadvantages:
• Not the fastest language
Lesser librariess than c++, PERL, JAVA

Not strong on type binding

In
Not easily convertible

python we, can work in interactive mode


RANA
&script mode. Python interpreter is called the

Python Shell.

Interactive

Command
Command
Mode

is

is
typed in front of

typed one at a time, then it


command prompt: CH
is
>>>
executed & the
CITY
result is given at the output.
mode does not savesthe command.
Intetractive

The output sandwitchedbetween the command


is lines.

It is used to test the code.

The interactive mode is suitable for small programs.


Editing the code written in interactive mode a tedious task. We need to revisit all our
is

previous commands and if still, we could not edit we need to type everything again.

Script Mode

Command is typed in Editor pane.


Python instructions are stored in a file generallywith .pyextension. They areexecuted
together in one go as a unit.
The saved instructions are known as Python script or Python program.
The output is not sandwitchedbetween the command lines.

The saved instructions can be used again in future. It is much preferred over interactive
mode by experts in the program
The script mode is suitable for large programs.
Editing your script is easier in script mode.

1
Q1. What is Python?

Python is a general purpose programming languagecreated by Guido Van Rossum.

Python is most praised for its elegant syntaxand readable code. It is based on or

influenced by two programming languages: ABClanguage & Modula-3


Q2. What is Anaconda?

Adistribution of Python is a bundle that contains an implementationof Python along

with a bunch of libraries or tools. Python has many distributions, like

CPython: this is the default, and what you should be using if you have no idea.

Jython: implementationin java, allows you to use the java api.

IronPython: implementationfor .net, allows you to usethe .net api.

PyPy: JIT implementation.

Anaconda :It is a free and open-sourcedistribution of the Python and R programming


languages for scientific computing (data science, machine learning applications, large
scale data processing, predictive analytics, etc.), that aims to simplify package
management and deployment.Anaconda also includes libraries, a package manager,
and additional softwarelike jupyter that lets you use python interactively. These are
what you might call an extension of python.

q3.What is Spyder?

Python has many IDE's like

1. Spyder 2. Jupyter Notebook 3. PyCharm

Spyder,the Scientific Python Development Environment,is a free Integrated

Development environment (|DE) that is included with Anaconda. It includes writing,

editing, interactive testing, debuggingof the programs and introspection features. ...

Spyder is also pre-installed in Anaconda Navigator, which is included in Anaconda. It


integrates the essentials libraries for data science, such as NumPy, SciPy, Matplotlib and
IPython, besides that, it can be extended with plugins.

2
CHARACTER SET

Character Set: Set of valid characters recognized by a language. Python has the

following character set.

Letters
A-Z, a-z

0-9
> Digits
> Special symbols space +-* **\()[]{}/=
/ = ==<,>.""",
&#<=>=@_(underscore)

Whitespaces Blank space, tabs (), carriage return (J), newline, formfed.

Other characters Python can processall ASCII and Unicode characters as part of

data or literals.

Tokens: Smallest individual unit in a program.

An English Sentence

Hurray!", he exclaimed, We are the world champions.

The lexical
types
(1
units

of tokens
1 1111
or tokens
an English sentence - here two
in
are used: words and punctuationcharacters
1/
A Python Program

#A sample program Astring value or string literal

name = "Anya»€ An integer value or integer literal

age = 15<
contribution = 710.754 A floating-point value or floating point literal

print (name, "aged",age, "has contributed", contribution)

Keyword Punctuator characters

Individual lexical units or tokens, together make components of a


expressions etc. In above programn you can see these tokene
. suGn aS statements
keywords,punctuators
or

Python has the following tokens

a. Keywords b. Literals C. Operators

d. ldentifiers e. Punctuators

3
Keywords :These are the words which have some special purpose to the Python interpreter. For eg.:
True, False, None, and,or not. As Python is case sensitive, keywords must be written exactly as given
in Table 3.1.

False class finally is return

None Continue for lambda try

True def from nonlocal while

and del global not with

as elif if
yield

assert else import pass

break except in raise

ldentifiers:These are the names given to the different parts of a program. For eg.:to a variable,

list, dictionary etc. The rules for forming ldentifiers are asfollows:

The first letter should be an underscore or a letter.

Digits from 0 to 9 can come after first character. Al,name1,1name


Special characters like !, @, #, $, %, etc are not allowed except theas first character or

anywhere in name.
ldentifiers are case sensitive.Name, name
It cannot be a keyword or reserved word given in Table 3.1.

They are unlimited in length. However, it is preferred to keep it short and meaningful.

Literals: These are constant values. It can be a

a. String literal

b. Numeric literal

C. Boolean literal

d. None

a. String literal: It is text enclosed


DAV ALA
in quotes. For eg.: 'a',"abc",abc',"a".They can be

represented in two ways:


Single line string:Examples of single line strings are 'a',"abc",'abc', etc.

Escape sequence: These are non-graphic characters that cannot be typed directly from
the keyboard e.g.: backspace, tabs, carriage return etc. These non-graphic characters
can be represented by using the escape sequence. An escape sequenceis represented

by a backslash(\) followed by one or more characters.


||– backslash \t horizontal tab

b backspace \n new line character

I'- single quotes 1"- double quotes

b. Numericliterals: They are two types

Integer: These are whole numbers without any fractional part. It may contain (+),(-) sign.

Commas cannot come in integer constant. For e.eg.: +34,-78

4
Floating point literals: These are numbers with fractional part. .Commas cannot come in these

literals. It may contain (+),(-) sign. It should have atleast one digit with the fractional point.

They have precision of 15 digits. For e.g.: 78.4, -67.98


C. Boolean literals: It has two values: True or False.

d. None: It means absenceof a value or the end of a list. Python does not display anything

when asked to display the value of a variable containing None.

Note: Built-in literals of Python are True, False, None.

Operator Operation Description Example(Try in Lab)

+ Addition Adds two numeric values >>> num1 =5


on either side of the >>> num2 = 6
operator >>> num1 +num2
11

Subtraction Subtracts the operand on the >>> num1 =5


right from the operand on the >>> num2 =6
left >>> num1 -num2
-1

Multiplicatio Multiplies the two values on >>> num1 =5


n both sides of the operator >>> num2 = 6
>>> num1 * num2
30
Division Divides the operand on the left >>> num1 =5
by the operand on the right of >>> num2 =2
the operator and returns the >>> num1/ num2
quotient 2.5

% Modulus Divides the operand on the left >>> num1= 13


by the operand on the right >>> num2 =5
and returns the remainder >>> num1% num2
3
Floor Division Divides the operand on the left>>> num1 =5
by the operand on the right >>> num2 =2
and returns the quotient by >>> num1// num2
removing the decimal part. It is 2
sometimes also called integer >>> num2// num1
division.

k Exponent Raise the base to the power of >>> num1=3


the exponent. That is, multiply >>> num2 = 4
the base as many times as >>> num1 ** num2
given in the exponent 81

Operators: The symbols that trigger someaction on the data are called operators. The different type
of operators are
a. Arithmetic operators c. Relational operators

b. Assignment operators d. Logical operators

a. Arithmetic operators: Python supports arithmetic operators (Table 3.3) 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 the operator.
of
5
>>> str1="Hello"

>>> str2 = "India" 7+8 15 =


>>> str1 + str2 "z" + "8"=78
'Hellolndia'

1*" 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' 7*4 = 28


>>> strl1 *2 "7" *4 = 777
'Indialndia'

Operators (+)and (*) work in similar manner for other sequence data types like list and tuples.
b. Relational operators: They compare two values. They are >, <, >,<=, I=, ==, Conside the given
Python variables num1 = 10, num2 = 0, num3 = 10, str1 ="Good,str2 ="Afternoon"for the following
examples in Table 3.4:

Operator Operation Description Example (Try in Lab)

>>> num1 == num2


If values of two operands are
Equals to False
equal, then the condition
==str2
is
>> str1
True, otherwise it is False.
False

>>> num1 != num2


True
Not equal to If values of two operands are >>> str1 |= str2
not equal, then condition is
True
True, otherwise it is False
>>> numn1 =num3
False

>>> num1> num2


If the value of the left operand
Greater than True
is greater than the value of the
>>> str1> str2 True
right operand, then condition is

True, otherwise it is False.

If the value of the left operand


Less than >>> num1< num3
is less than the value of the
False
right operand, the condition is

true otherwise it is False

String are comparedon the basis of lexicographical ordering.

Boolean True is equivalent to 1(numeric value) & boolean False is equivalent to

0 (numeric value).

Never comparefloating point numbers.Because they are approximately presented in memory


in binary form up to the allowed precision (15 digits). For e.g.:

0.1 +0.1+0.1 == 0.3 is not true in python because of internal rounding error.

c. Assignment operator: Assignment operator assigns or changes the value of the variable on its left.

It is represented as '=. For e.g.: a =7 It means the value 7 has been assigned to variable 'a'.

6
Augmented Assignmentoperator:
%=, //=, and **=,

For eg: a. Num1 =num1+ num2


Similarly,

b.
there are other assignment

num1 + num2
operators like , +=,*=, E,

Operator Operation Description Example (Try in Lab)

>>> num1 == num2


If values of two operands are
Equals to False
equal, then the condition is
>> str1 == str2
True, otherwise it is False.
False

It adds the value of right side >>> num1 = 10


operand to the left side operand >>> num2 =2
and assigns the result to the left >>> num1 += num2
side operand. >>>
Note: x+=y is same as x =X + y num
112
>>> num2
2

It subtracts the value of right >>> num1 = 10


side operand from the left side >>> num2 =2
operand and assigns the result >>> num1 -= num2
to left side operand. >>>
Note:x-= y is same as x = X -y num
18

d. Logical operator: 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.

Operator Operation Description Example (Tryin Lab)


and Logical AND If both operands are >>> num1= 10
True, then condition >>> num2 =-20
becomes True >>> num1 == 10 and num2 == -20
True
>>> num1 == 10 and num2 == 10
False

or Logical OR If any of the two >>> num1= 10


operands are True, then >>> num2 = 2
condition becomes True >>> num1 >= 10 or num2 >= 10
True
>>> num1 <= 5 or num2 >= 10
False

not Logical NOT Used to reverse the >>> num1 = 10


logical state of its >>> not (num1 == 20)
operand True
>>> not (num1 == 10)
False

7
Membership Operators: Membership operator (Table 3.7) is used to check if a value is a member of
the given sequenceor not.

Operator Description Example(Try in Lab)

in Returns Trueif thevariable or value is found in >>> numSeq = [1,2,3]

the specified sequenceand Falseotherwise >>> 2 in numSeq


True
>>>1' in numSeq
False
#1" is a string while

#numSeq contains number 1.


not in Returns True if the variable/value is not found >>> numSeq [1,2,3] =
in the specified sequenceand Falseotherwise >>> 10 not in numSeq
True
>>>1 not in numSeq
False

Associativity:It is the order in which an expression having multiple operators of same precedence
is evaluated. All operators are left associative except exponentiation which has right associativity.

A Parenthesis can be used to override the precedence of operators. The expression within () is

evaluated first. For eg


LHS: 3**2**3 RHS: 3**2 **3
=9**3
=243

Operator Prêcdedence
i. ()
R = 3**8
= 6561

CTY
ii.

ii. %,ll

v. +,

V. >,6,>=,<=,==,!=
vi.

vii.
Not
And
VIDAV
vii. Or

Example 3.5: How


Solution: #precedence
- 20+ 1200 #Step
will

of is more
1
AMBALA
Python evaluate the following expression:
* than that of +
20 + 30 * 40

= 1220

Example 3.6: How will Python evaluate the following expression: (20 + 30) * 40
Solution: Using parenthesis(),we have forced precedence of + to be more than that of *
- (20+30)* 40 # Step 1

=50 *40 # Step 2


=2000 # Step3
Example 3.7 How will the following expression be evaluated: 15.0 /4.0 + (8 +3.0)

Solution: = 15.0/4.0 + (8.0 + 3.0) #Step 1


= 15.0/4.0 + 11.0 #Step 2
8
=3.75 + 11.0 #Step 3
= 14.75

Punctuators: These are the symbolsused in programming languages to organize sentence


structures and indicate the rhythm & emphasis of expressions, statements & program
structures.

Datatypes: 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. Figure 3.6 enlists

the data types available in Python.

Data Types in Python

Numbers Sequence Sets None Mapping

Integer Floating Point Complex String Dictionary

Boolean List

Tuples

Python offers following built-in core datatypes

Numbers
String
List

Dictionary
HAR SCHOOR
CITY
Number: This datatype store numeric values in Python. Core datatypes in Python are

a. Integers

i. Integers
ii. Booleans

MBA
b. Floating point numbers
a. Integer:

Integers :Theyare whole numbers without any fractional part. It can be +ve or -ve.
Length is available by the memory available. For e.g.: +78,-45

Boolean: It has twO values: True or false. True represents 1(numeric value) & boolean
False represents 0 (numeric value).For e.g.:

print(bool(0)) print(bool(1)

Output: False Output: True

b. Floating point numbers:These are numbers with fractional part. .Commas cannot come in these

numbers. It may contain (+),(-) sign. It should have atleast one digit with the fractional point.

They have precision of 15 digits. For e.g.: 78.4, -67.98.

Example 3.1

>>> quantity = 10 >>> Price = -1921.9


>>> typelquantity) >>> type(Price)
<class 'int'> <class 'float'>
Advantages & disadvantages of floating point numbers

They represent a much greater range of values between integers.


Floating point operations usually are slightly slower than integer operations.
Integers will never suffer from precision loss.

Variables of simple data types like integer, float, boolean etc. hold single value. But such variables are

not useful to hold multiple data values, for example, names of the months in a year, names of
students in a class, names and numbers in a phone book or the list of artifacts in a museum. For this,

Python provides sequencedata types like Strings, Lists, Tuples, and mapping data type Dictionaries.

Sequence:A Python sequenceis an ordered collection of items, where each item is indexed by an
integer value. Three types of sequencedata types available in Python are Strings, Lists and Tuples. A

brief introduction to these data types is as follows:


String: Any type of data or characters enclosed in quotes is called string datatype.
Facts aboutstring:
Strings are sequenceof characters which are stored separately in contiguous locations.

They can be accessed by using the index. Each character has a two way index: forward index &

backward index.
If we have a string say, 'COMPUTER.

Forward Direction
2 3 4 5 6 7
Indexing

C M P T E R

-7 -6 -5 4 -3 -2 -1
Backward Direction

Indexing

You can access individual characters of a string.

Name ='Rohit
print(Name[0])

print(Namei4)
will

will
print R

print
B
t
print(Name[5]) will give an error

• Strings are immutablei.e. you cannot assign a value, like

Name[o]= M

But, a new value can be assigned to thesame variable.Fore.g.:

Name = "Mohit"

Variables: Variable is an identifier whose value can change. For example variable age can have

different value for different person. These are named locations that refer to a value & whose
value can be processed during program run. In Python, we can use an assignment statement to

create new variables and assign specificvalues to them.


gender = 'M'
message ="Keep Smiling"
price = 987.9

10
Characteristics of a variable

A variable in Python is not created until you assign a value to

it.
Name = "Rohit" print(x) error
i.
ii.
print(name) X= 20
print(y) print(x) will return 20

Variable name should be unique in a program.


Variables of datatypes integer, floating point, Boolean, string are Variable is an identifier

whose value can change. For examplevariable age can have different value for different person
immutable

15 16 17 18 19 20
Memory
Locations
201 202 203 204 205 206

Age RA 00
Age = 15 variable age point to memory location201

But,

Age = 16
if

Python variable
This is
we write now
variable age point to memory location202

do not have fixed location. Its location changes every time you change the value.
called immutable type variable.Mutable means that in the same memory address new value
TY
can be stored as & when you want.

Multiple Assignments
a = b= c= 10 a= 11, b= 210, c=130
X,y,Z = 1,2,3
X,X =5,6
Y.y= x+ 10, x +16
print(x,y) Output:6 22

Dynamic typing: A variable pointing to a value of certaintype, can be made to point to a value
of differenttype.

x=10
i.
y= x/2 output: 5.0

x= "day"
y=x/2 error

Dynamictyping causes error as shown above.Be cautious while using it because Python does

not raise error for dynamictyping but during calculationsthey raise.

11
Python Program:

Comments # This program calculates value of variables a &


b.

La-10
Statements >Expression
b=20-a

print(a,b)

Indentation

Expreession: It is any legal combination of symbols that represents a value.


Statement: It is a programming instructionthat does something i.e., some action takes place.

Comment: These are the additional readable information to clarify the source code.

Indentation: To show blocks, different indentation levels are used.

Function: A function refers to a set of statements or instructions grouped undera 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 places in a program by simply writing the function name, i.e., by calling that
function.

Python has many predefined functions called built-in functions like print(), input(), int(), float().

PRINTFunction

It auto-converts the items to string datatype.

SEP Argument:It inserts a separator character between the items being printed in a

line. By default, a blank space is inserted between the items. For e.g.: in the statement

print("My", "first""python""program.") will give the output

>>> My first python program.

But if you want to change the separgumentto '@

print("My""first","python""program."sep='@') will give the output

>>> My@first@python@program.

END Argument: By default, a newline character is appended at the end of the line.

print("My"" first","python","program.")

print("Writing in script mode") will give the output

>>> My first python program.


Writing in script mode.

But if want both the sentences in continuity. Iwill change the value of end argument.
I
print("My","first","python","program.",end = ")
print("Writing in script mode") will give the output

>>> My first python program. Writing in script mode.

12
An empty print() function prints a blank line.

INPUTO Eunction:

It returns a value of string datatype.

To get the input from the user interactively. For e.g.:

Name =input("Enter your name:") Enter your name: Rohit


Age =input("Enter your age:") Enter your age: 13
print(Name,age) Rohit 13
print(age+1) ERROR

Datatype conversion functions: Use the functions int() & float() to convert the value to

their respective datatypes. Continuing with the above example

Name = input("Enter your name:") Enter your name: Rohit


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

print(Name,age) Rohit 13
print(age+1) 14

When you are using int() function enter integer type value only and for float() function

enter float type value only, else error will come .For e.g.:

Age = int( input("Enter your age:") Enter your age: 13.5 (ERROR)

Debugging: The process of identifying and removing logical and runtime errors is called
errors
debugging. We need to debug a program so that is can run successfully and generate the desired
output.
Due to errors, a program may not execute or may generate wrong output.:
i) Syntax errors

ii) Logical errors

ii) Runtime errors


SyntaxErrors: Like any programming language, Python has rules that determine how a program is to
be written. This is called syntax. The interpreter can interpreta statement of a program only if it is

syntactically must be in pairs, so the expression (10+12) is


correct. For example, parentheses
syntactically correct, whereas(7+ 11 due to absence of right parenthesis. If any syntax
is not correct
error is present, the interpreter shows error message(s) and stops the execution there. Such errors
need to be removed before execution of the program.

Common Python syntax errors include:

leaving out a keyword

putting a keyword in the wrong place


leaving out a symbol, such as a colon, comma or brackets
misspelling a keyword

incorrect indentation

empty block

Logical Errors: A logical error/bug (called semantic error) does not stop execution but the program
behaves incorrectly and produces undesired /wrong output. Since the program interprets successfully
even when logical errors are present in it, it is sometimes dificult to identify these errors.

13
For example, if we wish to find the average of two numbers 10 and 12 and we write the code as 10+
12/2, it would run successfully and produce the result 16, which is wrong. The correct code to find

the average should have been (10 + 12) /2 to get the output as 11. Here are some examples of

mistakes which lead to logical errors:

using the wrong variable name


indenting a block to the wrong level
using integer division instead of floating-point division

getting operator precedence wrong


making a mistake in a boolean expression

Runtime Error: A runtimne error causes abnormal termination of program while it is executing.

Runtime error is when the statement is correct syntactically, but the interpreter cannot execute it.

For example, we have a statement having division operation in the program. By mistake, if the
denominator value is zero then it will give a runtime error like "division by zero". Some examples of
Python runtime errors:

performing an operation on incompatible types


• using an which has not been defined
identifier

• accessing element, dictionary value or object attribute which


a list doesn't exist
• to accessa
trying which doesn't file exist.

SCHÒE
CITY
CHARU
MDAV
AMBALA

14
CONDITIONAL & ITERATIVE STATEMENTS

There are three type of statements in Python.

a. Empty statement: It does nothing. Simply moves to the next statement in the flow of control. It is

used when a statement is not required by the logic of the program but syntax of the language

requires
it.
For e.g.:

pass

Whenever Python encounters a pass statement, it does nothing and moves to the next statement
in

the flow of control.

b. Simple statement: Single executable statement. For e.g.: a= b+3


c. Compound :Group of statements executed as a unit. For e.g.

if a > b:

print("a is greater than b")

StatementControl Flow

Control Statements: They control the flow of control in a program. Theyare of three types:

a. Sequence: Sequencerefers to hormal flow of control in a program & is the simplest


one. In this construct, the statements are

executed from the beginning to the end one after


the another. When the final statement of the

program is executed the program is done.

False
Condition?
The exit
condition
True
Statement 1

Statement 1

The loop body


Statement 2
Statement 2

3
Statemnent

AMP
The Sequence Construct The Iteration Construct

b. Selection: They test the condition & selectively execute the code depending on the
outcome of the test condition. This construct is also called decision construct.

c. Iteration: They repeat a set of statements till a test condition is satisfied.

15
The Selection Construct

One course-of-action

True
Condition ? Statement 1 Statement

2
False

Statement 1
Anotne
Statement 2
cOurse-of-action
IF Statement: It's a compound statement & its syntax is as follows:
if <cond>:
statement

where,a statement may consist of a single statement, a compound statement, or

just an empty statement. In an if statement the conditional expression evaluates to

True, the statements in the body of the loop areexecuted, otherwise ignored.
Other forms of IF statement
f<cond>. b. if <cond>:
statement(s) statement(s)
else: elif <cond>

When
statement(s)

the conditional statements


DA statement(s)
else

statement(s)

appear, the Python interpreter executes code inside one block that
is selected based on the condition. Number of elif is dependenton the number of conditions to be
checked. If the first condition is false, then the next condition is checked, and so on. If one of the

conditions is true, then the corresponding indented block executes, and the ifstatement terminates.
After that, the statements outside the if..else are executed or the program terminates if there are no
further statements.

Characteristcs of if..else

• The and
if...else elif statements control the program flow.

• The statement
if in programmingis used for decision making.

• The statement
if is evaluated on the basis of the specified condition(s).

• The else block can be attached with the if statement & it is executed if the condition is

false.

• The else block cannot exist without the statement. if

• The statement(s) can be attached with the statement


elif if if there are multiple conditions.
• There no on the number of
is that we can use
limit elifs

16
PYTHON ASSIGNMENT1

Q1. Name the two languages on which Python is based?

Q2. Differentiatebetween the script mode & interactive mode.

Q3. What the file extension of Python file.

Q4. Name the Python distribution we are using in our lab.

Q5. Name some popular IDEs.

Q6. Write a short note on the following:

a. Python b. Anaconda c. Spyder


Q7. Explain the advantages & disadvantages of Python

OL
Q8. Define the following terms with examples.

a. Character set b. Keywords c. Identifiers

d. Tokens e. Operators f. Punctuators

TT
Q9. Write the rules for naming the identifiers. Give examples.

Q10. How many type of tokens are there in Python 2Name & explain them.
Ql1. In how many ways can you give the comment. Give one example of each.

Q12. What are literals ? Give two examples for each of the following:

i. Integer literal String literal iii. Boolean literal iv. Float literal
ii.
Q13. How nany type of literals are there in Python ? Name & explain them.
Q14. Name the built-in literals of Python.

Q15. Write a short note on escape sequence. Give examples.

Ql6. Name the two boolean literals in Python.

Q17. What

Q18. Name
Q19.
is None

different

Differentiate
literal in Python.

type of operators with example.

between the following:


LA
i. and // ii. *&'***

Q20. Write the precedence of operators.

Q21. What is the operator associativity of *** and the rest of operators.
ASSIGNMENT-2

Ql. Name built-in core datatypes of Python.

Q2. Write a short note on number datatype.

Q3. How many integer types are supported by Python. Name them
Q4. What is the numeric value of Boolean True & False.
Q5. What are the advantages & disadvantages of floating point numbers.

Q6. How many precision digits are there in floating point numbers.

Q7. How
Q8. What

Q10. Explain
are string stored

is the use

Q9. What are immutabledatatypes? Name

with an
in

example how
Python?

of sequencedatatype?

string datatype
them.

and numeric datatype


OL
are immutable.

Ql1. Define the term variable.Write its characteristics.

Q12. Name the function used to check the datatype of a variable?

CA
Q13. What is dynamic typing?

Q14. Explain disadvantage of dynamic typing with an example.


Q15. What is a function. Name the functions you have learnt so far.

Q16. What is the datatype of the value returned by the inpu() & print() functions?
Q17. Explain the puposeof SEP and END argumentsof the print() function.

Q18. Which two functions are used to convert string type data to integer & float type data.

Q19.What is Debugging? What is its purpose?

Q20. How many type of errors are there? Name & explain them with examples.

AMB
1
ASSIGNMENT 3

Q1. If a ,b, c,d =15,5, "Pandas", "Numpy"


Find the output for the following expressions:

i. print(a/b, a//b, a %b, sep = "e") print(a*b, a**b, sep =\n")

ii.
ii. print(c*2, c + d, end= " ") iv. print(a>b) v. print(c<d)

vi. print(a>b or c<d) vi. print(a>b and c<d) vii. print(not(a>b) or c>d)
ix. print(cl= d) X. print(0.1+0.3+0.2 = 0.6) xi. print(bool(0))

xi. print(bool(1))

Q2. Expand the following expression: a**=b iia//=b

i.
03.If x,y =1,2
i. = Y,X+y
x,y X=y ii. a,b =1,4 iv. a = "PYTHON"
ii.
print(x.y) y= x+y b,a =a,b print(a[2])

print(x,y) print a,b

V. a= "PYTHON" vi. a = "PYTHON"


print(a[7) a[0] = "J"

Q4. What is the difference between the two statements and i.:
i.
a =6 ii. a == b
i.
Q5. If L1 = (1,4,7,9], then what will be the output forthe following expressions:
5 in L1 ii. 5 not in L1 ii. 6 in L1 iv. 6 not in L1

CITY
i.
Q6. Neha for the following code entered the value 500.50
a = int(input("Enter your fees:")
She got an error. Why?
Q7. Neha wrote following code:
= int(input("Enterthe salary:")

a= a+ 500
print(a)

The above code gave an error. Why?

Q8. Find the errors in the following code:


a. a,b=3,"Spyder"
b.

c.

d.
e.
c= input(float("Enter

print(c)

print(d)

d=a+b
temperature:")

MBALA
Q9. Why you should not use the equality operator(==)operator to determine whether objects of
type float are equal?

Q10. Print the poem in followingformat:

Twinkle, twinkle, little star,

How wonder what you are!


I
Up above the world so high,

Like a diamond in the sky.


Twinkle, twinkle, little star,

How wonder what you are!


I
1
MCQ's

1. Which of the following Boolean expressions is not logically equivalent to the other three?
a) not(-6<0 or-6>10) b) -6>=0 and -6<=10
c) not(-6<10 or-6==10) d) not(-6>10 or-6==10)

2. What will be the output of the following Python code snippet?


print(not(10<20) and not(10>30))
a) True b) False c) Error d) No output

3. What will be the output of the following Python expression?


print(4.00/(2.0-+2.0)

a) Error b) 1.0 c) 1.00 d) 1

4. What will be the value of X in the followingPython expression?


x= 2+9*(3*12)-8)/1o
print(x)

a) 30.0 b) 30.8 c) 28.4 d 27,2


5. Which of the following expressions involves coercion(datatypeconversion)when evaluated in

Python?
a)4.7-1.5 b)7.9*6.3 c)1.7%2 d) 3.4 + 4.6

6. What will be the output


print(24//6%3, 24//4/2)

a) (1,3) b) (0,3)
of the following

c) (1,0)
Python expression?

d) (3,1)
CIT
7. What will be the value of the following Python expression?

LA
print(float(4+int(2.39)%2)

a) 5.0 b) 5 c) 4.0 d) 4

8. Which of the following expressionsresults in an error?

a) float('1') b) int('10') c) float('10.8') d) int('10.8')

9. What will be the value a Python expression?

MBA
a = 4+2**5//10
print(a)

a) 3 b) 7 c) 77 d) 0

10. The expression 2**2**3 is evaluates as: (2**2)**3.

a)True b) False

11. What is the value of the expression 100/25?


a. 0 b. 0.0 C. 4.0 d. 4

12. Which of the following expressions is an example of datatype conversion?


a) 4.0+ float(3) b) 5.3 + 6.3 c) 5.0 +3 d) 3+7

2
Sequence Control Assignment1

Q1. Define the following terms: a. Control statement b. Statement


c. Expression d. Indentation e. Comment
Q2. Name and explain three different type of statements.

Q3. Explain the following control statements with the help of a diagram.

a. Sequence b. Selection

Q4. Write four characteristics of if...else statement.

WRITE THE FOLLOWING PROGRAMS

1. Write a program to find maximum between twO numbers

2. WAP to find maximum between three numbers

3. WAP to check whether a number is negative, positive or zero

WAP to whether a leap year or not

OOL
4. check year is

5. WAP to check whether a number is even or odd

6. WAP to calculate profit or loss.

7. WAP to input any character and check whether it is alphabet, digit or special character

8. WAP to check whether a character is uppercase orlowercasealphabet

9. WAP to input week number and print week day


10. WAP to input month number and print month Name

11. WAP to input marks of five subjects Physics, Chemistry, Biology, Mathematicsand Computer.

12. WAP to calculate percentage and gradeaccording tofollowing:

Percentage>= 90% : Grade A

• Percentage >= : B

BA
80% Grade
Percentage>=70% :Grade C
60%: Grade D
Percentage >=

• Percentage >= 40%: Grade E


Percentage < 40% :Grade F

12. WAP to input basic salary of an employee and calculate its Gross salary according to following:
If BasicSalary <= 10000 then HRA = 20%, DA =80%

If Basic Salary <= 20000then HRA= 25%, DA = 90%


• If Basic Salary> 20000 then HRA =30%, DA =959%

13. The current year and the year in which the employee joined the organization are entered
through the keyboard. If the number of years for which the employee has served the organization
is greater than 3 then a bonus of Rs. 2500/- is given to the employee otherwise no bonus.

14. Given the length and breadth of a rectangle, write a program to find whether the area of the

rectangle is greater than its perimeter. For example, the area of the rectangle with length = 5and
breadth =4 is greater than its perimeter

1
Q15. Tell whether a number is divisible by5 or 11 or both.

Q16 Write a program to calculate the salary as per the following table

Year of

Gender Service Qualifications Salary

Male >= 10 Post - Graduate 15000

>= 10 Graduate 10000

<10 Post -Graduate 10000

< 10 Graduate 7000

Female >= 10 Post - Graduate 12000

100
>= 10 Graduate 9000

< 10 Post - Graduate 10000

<10 Graduate 6000

Q17: Write a program for a simple banking system:


CITY
if the user has a savings account:
if the balance is above $5000,offer them a loan.

if the balance is between $1000 and $5000,offer them a credit card.

if the balance is below $1000,suggest a savings plan.

if the user has a checking account:

if the balance is above$3000, offer them a premium checking account.

if the balance is between $1000 and $3000,suggest a regular checking account.

if the balance is below $1000,recommend low-balance services.

Q18: WAP that calculates the total discount on a shopping cart based on the following
conditions:

if the cart total is over $200:


• if the cart contains more than 5 items, apply a 15% discount.
• if the cart contains 5items or fewer,apply a 10% discount.
3 if the cart total is $100-$200:
• if the cart contains more than 3 items, apply a 10% discount.
• if the cart contains 3 items or fewer, apply a 5% discount.
if thecart total is less than $100,no discount is applied.

2
Q19. WAP that determines whether a person is eligible for a gym membership or not:

ifthe person is 18 or older:


• if they have no medical conditions, they are eligible.
• if they have medical conditions:

• if they have a doctor's approval, they are eligible.

• if they do not have a doctor's approval, they are not eligible.

3 if the person is youngerthan 18, they are not eligible.

Q20. WAP that determines the ticket price fora concert based on the attendee's age &
membership status:

if the attendee is under 12, the ticket price is $10.


if theattendeeis 12-17years old:

• if they are a member, the ticket price is $15.

• if they are not a member, the ticket price is $20.

ifthe attendeeis 18 or older:


• if they are a member, the ticket price is $25.

10OH
• if they are not a member,the ticket price is $30.

Q21. WAP that calculates the insurance premium for a car based on the following conditions:

if the driver is under 25years old:

• if the driver has had no accidents in the last 3 years, the premium is $2000.
• if the driver has had 1-2 accidents, the premium is $2500.
• if the driver has had more than 2accidents, the premium is $3000.
if the driver is 25 years old or older:

if the driver has had no accidents in the last 3years, the premium is $1500.
if the driver has had 1-2 accidents, the premium is $2000.

MAM
if the driver hashad more than 2accidents, the premium is $2500.

You might also like