0% found this document useful (0 votes)
72 views30 pages

CH - 1 Getting Started With Python

Python is a general purpose programming language created by Guido van Rossum in 1991, it has a simple syntax and is easy to learn, and it is used widely by organizations like Google, NASA, and others for tasks like scientific programming, web development, and hardware testing.
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)
72 views30 pages

CH - 1 Getting Started With Python

Python is a general purpose programming language created by Guido van Rossum in 1991, it has a simple syntax and is easy to learn, and it is used widely by organizations like Google, NASA, and others for tasks like scientific programming, web development, and hardware testing.
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/ 30

Q1. What is Python?

Python is a programming language created by


Guido Van Rossum at CWI (Centrum Wiskunde
& Informatica) which is a National Research
.
Institute for Mathematics and Computer Science
in Netherlands in I991. Python got its name from
a BBC comedy series from seventies- “Monty
Python‟s Flying Circus”. Python can be used to
follow both Procedural approach and Object
Oriented approach of programming. It is free to
use.
Q2. What are the features of Python?

1. It is a general purpose programming language which can


be used for both scientific and non scientific
programming.
2. It is a platform
. independent programming language.
3. It is a very simple high level language with vast library of
add-on modules.
4. It is excellent for beginners as the language is
interpreted, hence gives immediate results.
5. The programs written in Python are easily readable and
understandable.
6. It is suitable as an extension language for customizable
applications.
7. It is easy to learn and use.
Q3. Which organizations are using Python & for what?

Python language is used by companies in real revenue


generating products, such as:
1. In operations of Google search engine, youtube, etc.
2. Bit Torrent. peer to peer file sharing is written using
Python
3. Intel, Cisco, HP, IBM, etc use Python for hardware
testing.
4. Maya provides a Python scripting API
5. i–Robot uses Python to develop commercial Robot.
6. NASA and others use Python for their scientific
programming task.
Q4. What is a Program?

A program is a sequence of instructions that specifies


how to perform a Computation to solve a problem.
Q5. What is IDLE?

IDLE (GUI integrated) is the standard,


most popular Python development
environment.
. IDLE is an acronym of
Integrated Development
Environment. It lets edit, run, browse
and debug Python Programs from a
single interface. For example:
pycharm is a python IDE.
Q6. What are the modes of working in Python?

Python shell
. can be used in two ways, viz.,
interactive mode and script mode. Where
Interactive Mode, as the name suggests,
allows us to interact with OS; script mode
let us create and edit python source file.
Q7. What is Interactive mode in Python?

Python, in interactive mode, is good enough to learn,


experiment or explore, but its only drawback is that we
cannot save the . statements for further use and we have
to retype all the statements to re-run them.
>>>print “How are you?”
How are you?
>>> is a Python Prompt, which mean python is ready to
accept your command.
. . . is also a mode which means the command is not
complete and requires more input from the user.
Q8. What is Script mode in Python?

To create and run a Python script, we use following steps


in IDLE, if the script mode is not made available by default
with IDLE environment.
1. File>Open OR File>New Window (for creating a new
.
script file)
2. Write the Python code as function i.e. script
3. Save it (^S)
4. Execute it in interactive mode- by using RUN option (^F5)
Otherwise (if script mode is available) start from Step 2

Note: For every updation of script file, we need to repeat


step 3 & step 4
Q9. Write a function in Script mode in Python?
Step 1: File> New Window
Step 2:
def test():
x=2
y=6
z = x+y .
print z
Step 3:
Use File > Save or File > Save As - option for saving the file (By
convention all Python program files have names which end with .py)
Step 4:
For execution, press ^F5, and we will go to Python prompt (in other
window)
>>> test()
8
Alternatively we can execute the script directly by choosing the
RUN option.
Q10. What is an object / a variable?
An objects is used to capture data, which then can be manipulated
by computer to provide information. Variable is a name which refers
to a value. Every object has:
1. An Identity, - can be known using id (object) It is the object's
address in memory and does not change once it has been
created.
2. A type – can .be checked using type (object) It is a set of values,
and the allowable operations on those values. It can be one of
the following: Data Types

Numbers None Sequence Sets Mappings

Integer Floating Point Complex Strings Tuple List Dictionary


Boolean
3. A value to bind value to a variable, we use assignment
operator (=). This is also known as building of a variable.
Example: >>> pi = 3.1415 Here, value on RHS of “=‟ is assigned to
newly created “pi‟ variable.
Q11. What are variable naming conventions?
A variable name:
1. Can be of any size
2. Have allowed characters, which are a-z, A-Z, 0-9 and
underscore (_)
3. Should begin with an alphabet or underscore.
4. Should not .be a keyword.
It is a good practice to follow these identifier naming
conventions:
1. Variable name should be meaningful and short
2. Generally, they are written in lowercase letters
3. Variables are created when they are first assigned a
value.
4. Variables must be assigned a value before using them in
expression.
5. Variables refer to an object and are never declared ahead
of time.
Q12. What are keywords?
They are the words used by Python interpreter
to recognize the structure of program. As these
words have specific meaning for interpreter,
they cannot be used for any other purpose. A
partial list of. keywords in Python 2.7 is
and def from not
while as elif global
or with assert else
if pass yield break
except import print class
exec in raise continue
finally is return
for lambda try
Q13. What are things keep in mind while writing python
statements?
1. Write one python statement per line (Physical Line). Although it is possible
to write two statements in a line separated by semicolon.
2. Comment starts with “#‟ outside a quoted string and ends at the end of a
line. Comments are not part of statement. They may occur on the line by
themselves or at. the end of the statement. They are not executed by
interpreter.
3. For a long statement, spanning multiple physical lines, we can use “/‟ at the
end of physical line to logically join it with next physical line. Use of the “/‟
for joining lines is not required with expression consists of ( ), [ ], { }
4. When entering statement(s) in interactive mode, an extra blank line is
treated as the end of the indented block.
5. Indentation is used to represent the embedded statement(s) in a
compound/ Grouped statement. All statement(s) of a compound statement
must be indented by a consistent no. of spaces (usually 4)
6. White space in the beginning of line is part of indentation, elsewhere it is
not significant.
Q14. What are operators & operands?

Operators are special symbols which represents


computation. They are applied on operand(s),
which can be. values or variables. Same operator
can behave differently on different data types.
Operators when applied on operands form an
expression. Operators are categorized as
Arithmetic, Relational, Logical and Assignment.
Value and variables when used with operator
are known as operands.
Q15. What are arithmetic operators?

Symbol Description Example 1 Example 2


+ Addition >>>55+45 >>> ‟Good‟ + ‟Morning‟
100 GoodMorning
- Subtraction >>>55-45 >>> 30 – 80
. 10 -50
* Multiplication >>>55*45 >>> „Good‟ * 3
2475 GoodGoodGood
/ Division >>> 17/5 17/5.0 17.0/5 >>> 25/3
3 3.5 3.4 8
% Remainder / >>> 17%5 >>> 23%2
Module 2 1
** Exponentiation >>> 2* *3 16* * .5 >>> 2* * 8
8 4.0 256
// Integer Division >>> 7.0 / /2 >>>3 / /2
3.0 1
Q15. What are relational operators?
Sym Description Example 1 Example 2
bol
< Less than >>>7<10 True >>>‟Hello‟< „Goodbye‟ False
>>> 7<5 False >>>'Goodbye'< 'Hello„ True
>>> 7<10<15 True
. >>>7<10 and 10<15 True
> Greater than >>>7>5 True >>>”Hello‟> “Goodbye‟ True
>>>10<10 False >>>'Goodbye'> 'Hello„ False
<= less than >>> 2<=5 True >>>'Goodbye' <= 'Hello„ True
equal to >>> 7<=4 False >>>‟Hello‟<= „Goodbye‟ False
>= Greater than >>>10>=10 True >>>‟Hello‟>= “Goodbye‟ True
equal to >>>10>=12 False >>>'Goodbye' >= 'Hello„ False
! =, Not equal to >>>10!=11 True >>>‟Hello‟!= “HELLO‟ True
<> >>>10!=10 False >>>‟Hello‟!= “Hello” False
== Equal to >>>10==10 True >>>”Hello‟ == “Hello‟ True
>>>10= = 11 False >>> ‟Hello‟ ==“Good Bye‟False
Q15. What are logical operators?
Symbol Description

or If any one of the operand is true, then the


condition
. becomes true.
and If both the operands are true, then the condition
becomes true.

not Reverses the state of operand/condition.


Q15. What are assignment operators?
Assignment Operator combines the effect of arithmetic and
assignment operator

Sym Description Example Explanation


bol
= Assigned values from right >>>x=12*
.
side operands to left >>>
variable y=‟greetings‟
we will use it as initial value of x for following examples
+= added and assign back the >>>x+=2 The operand/expression/
result to left operand constant written on RHS of
operator is will change the
value of x to 14
-= subtracted and assign back x-=2 x will become 10
the result to left operand
*= multiplied and assign back x*=2 x will become 24
the result to left operand
Q15. What are assignment operators?
Assignment Operator combines the effect of arithmetic and assignment
operator

Sym Description Example Explanation


bol
/= divided and assign back the x/=2 x will become 6
.
result to left operand
%= taken modulus using two x%=2 x will become 0
operands and assign the
result to left operand
**= performed exponential x**=2 x will become 144
(power) calculation on
operators and assign value
to the left operand
//= performed floor division on x / /= 2 x will become 6
operators and assign value
to the left operand
Q16. What are Expressions?

An expression is a combination of value(s) (i.e. constant),


variable and operators. It generates a single value, which by
itself is an expression.
.
Example: Value/ Operands
2+2
Operator
The expression is solved by Computer and gets it value. In
the above example, it will be 4, and we say the expression is
evaluated.
Note: Expression values in turn can act as, Operands for
Operators
Q17. What are the precedence of operators?

Precedence of operators is applied to find out which operator /sub


expression should be evaluated first. Precedence of operator - Listed
from high precedence to low precedence.

OPERATOR DESCRIPTION
.
** Exponentiation (raise to the power)
+, - Unary plus and minus
*, /, %, / / Multiply, divide, modulo and floor division
+,- Addition and Subtraction
<,<=, >, >= Comparison operator
%=, /=, //=.+-, -=, *= Assignment operators
not, and, or Logical operators
Q18. What are the different types of statements?

A Python statement is a unit of comma.


code that the Python interpreter Compound statements : are also
can execute. There are two types of called group statements. They
statements: are sometimes called nested block.
1. Simple statements Statement belonging to a block are
Example of simple. statement are: indented (usually by 4 spaces).
>>> x=5 Leading whitespace at the
>>> area=x**2 #assignment stmnt beginning of logical line is used to
>>>print x #print statement determine the indentation level of
5 line. That means statement(s)
>>>print area which go together must have same
25 indentation level. Example
>>> print x, area if i<0:
5 25 print “i is negative”
Note: To print multiple items in else:
same line, separate them with print “i is non-negative”
Q19. What are input and output?
Program need to interact with end Syntax for input() is:
user to accomplish the desired task, Variable = input ([prompt])
this is done using Input-Output Example:
facility. Input means the data entered x = input ('enter data:')
by user (end user) of the program. In Enter data: 2+ ½.0
python, raw_input(). and input ( Will supply 2.5 to x
) functions are available for input. Print: This statement is used to
Syntax of raw_input() is: display results.
Variable = raw_input ([prompt]) Syntax:
Example: print expression/constant/variable
>>>x = raw_input ('Enter your name: ') Example:
Enter your name: ABC >>> print "Hello"
Example: Hello
y = int(raw_input ("enter your roll
no"))
will convert the accepted string into
integer before assigning to 'y'.
Q20. What are comments in Python?

Comments: As the program gets bigger and more


complicated, it becomes difficult to read it and difficult
to look at a piece of code and to make out what it is
doing by just looking
. at it. So it is good to add notes to
the code, while writing it. These notes are known as
comments. In Python, comments start with '#' symbol.
Anything written after # in a line is ignored by
interpreter. For more than one line comments, we use
the following;
Place '#' in front of each line, or
Use triple quoted string. ( """ """)
Q21. What are functions in Python?

Functions in Python: A function is named sequence of


statement(s) that performs a computation. It contains line
of code(s) that are executed sequentially from top to
bottom by Python . interpreter. They are the most important
building block for any software in Python. For working in
script mode, we need to write the Python code in functions
and save it in the file having .py extension. Functions can be
categorized as belonging to
1. Modules
2. Built in
3. User Defined
Q22. What are modules in Python?

Module:
A module is a file containing Python definitions (i.e.
functions) and statements. Standard library of Python is
extended as module(s)
. to a Programmer. Definitions from
the module can be used into code of Program. To use these
modules in a program, programmer needs to import the
module. Once we import a module, we can reference (use)
to any of its functions or variables in our code. There are
two ways to import a module in our program, they are :
 import
 from
Q23. What is import statement in Python?
Import: It is simplest and number")
most common way to use y = math.sqrt(x)
modules in our code. a = math.pow(x,2)
Syntax: print "Square Root
.
import modulename1 [, value=",y
module name 2, ---------] print "square value=",a
Example: Input any number output:
and to find square and Enter any number25
square root. Square Root value= 5.0
Example: square value= 625.0
import math
x = input ("Enter any
Q24. What is from statement in Python?
From statement: It is used to get a x=input("Enter any number")
specific function in the code y=sqrt(x) #without using math
instead of complete file. If we know a=pow(x,2) #without using math
beforehand which function(s), we print "Square Root value =",y
will be needing, then we may use print "square value =",a
'from'. For modules having large Enter any number100
number of functions,
. it is Square Root value = 10.0
recommended to use from instead square value = 10000.0
of import. The functions available in math
Syntax module are:
>>> from modulename import ceil() floor() fabs() exp() log()
functionname [, functionname…..] log10() pow() sqrt() cos() sin() tan()
from modulename import * degrees() radians()
will import everything from the file. Some functions from random
Example: Input any number and to module are:
find square and square root. random() randint() uniform()
Example: randrange()
from math import sqrt,pow
Q25. What are built-in functions in Python?

Built in functions are the function(s) that are built


into Python and can be accessed by Programmer.
These are always available and for using them, we
don't have to . import any module (file). Python has a
small set of built-in functions as most of the
functions have been partitioned to modules. This
was done to keep core language precise.
abs() max() min() bin() divmod() len() range()
round() bool() chr() float() int() long() str( ) type( )
id( ) tuple( )
Q26. What are user-defined functions in Python?
In Python, it is also possible for programmer to write their own function(s).
These functions can then be combined to form module which can be used in
other programs by importing them. To define a function, keyword 'def' is used.
After the keyword comes an identifier i.e. name of the function, followed by
parenthesized list of parameters and the colon which ends up the line, followed
by the block of statement(s)
. that are the part of function.
Syntax:
def NAME ([PARAMETER1, PARAMETER2, …..]):
#Square brackets include optional part of statement
statement(s)
Example: To find simple interest using function.
Example:
def SI(P,R,T):
return(P*R*T)
Output:
>>> SI(1000,2,10)
20000

You might also like