Introductionto Python
Basics of Python programming. Python interpreter-interactive and script mode, the structure
of a program.
Indentation,[Link],variablestypesofoperatorsprecedenceofoperators,
data
Types,mutableand immutabledatatypes,
statements,expressions,evaluationandcomments,inputandoutput statements
Datatypeconversion,debugging.
ControlStatements:if-elseif-elif-else, whileloop,forloop
WhatisPython?
High-levelprogramminglanguage
Easytoread andwrite
Interpretedlanguage(coderunsdirectly,noneedtocompile)
KeyFeatures
Simplesyntax similarto English
Dynamictyping(noneedtodeclarevariabletypes)
Supportsmultipleprogrammingparadigms(procedural,object-oriented,functional)
Extensivestandardlibraryandthird-partymodules
Largecommunityandsupport
InstallingPython
1. Downloadfromtheofficialwebsite([Link])
2. Followtheinstallationinstructions foryouroperating system
RunningPythonCode(InteractiveandScriptmode)
1. Interactivemode:Typepythoninyourterminal/commandprompt
2. Scriptmode: Writecodeinafilewith [Link] extensionand runit usingpython [Link]
ThestructureofaPythonprogram
Asimplepythonprogram toaddtwo numbers
Indentation
Indentationreferstoaddingwhite spacesbeforelinesof codeinapython program.
IndentationinPythonisusedtocreateagroupofstatementsthatareexecutedasablock.
Example:
Identifiers
Namesgiventovariousprogramelementssuchasvariables,functions,classes,etc.
Rules:
o Muststart with aletter(a-z,A-Z) oran underscore (_)
o Followedby letters,digits(0-9), or underscores
o Case-sensitive(e.g. varandVararedifferent)
o Cannotbeareservedkeyword
Keywords
ReservedwordswithspecialmeaninginPython
Cannotbeusedasidentifiers
Examples:False, class,finally,is,return,None,continue,for,lambda,try,etc.
Constants
Fixedvaluesthatdonotchangeduringprogramexecution
Examples:numbers(5,3.14),strings("Hello",'World')
InPython,constants areusuallydefined inalluppercaselettersas aconvention(e.g., PI=3.14)
Variables
Namedstoragelocationsin memoryusedtostore data
Createdbyassigningavalueusingtheassignmentoperator (=)
Examples:x=5,name ="Alice"
Variablenamesshouldbedescriptiveandfollowidentifierrules
Types ofOperators
Arithmetic Operators: + (addition), - (subtraction), * (multiplication), / (division), % (modulus), **
(exponentiation), // (floor division)
Comparison(Relational)Operators:==(equalto),!=(notequalto),>(greaterthan),<(lessthan),
>=(greaterthanor equalto),<=(lessthanorequal to)
Assignment Operators: = (assignment), += (add and assign), -= (subtract and assign), *= (multiply
and assign), /= (divide and assign), %= (modulus and assign), **= (exponent and assign), //= (floor
division and assign)
LogicalOperators:and, or, not
BitwiseOperators:&(AND), |(OR),^(XOR), ~(NOT), <<(leftshift),>>(rightshift)
MembershipOperators:in,notin
IdentityOperators:is,isnot
PrecedenceofOperators
Determinestheorderinwhichoperatorsareevaluatedinanexpression
Operatorswithhigherprecedenceareevaluatedbeforethose withlowerprecedence
Precedenceorder (fromhighesttolowest):
1. ** (exponentiation)
2. ~(bitwiseNOT),+(unaryplus),-(unary minus)
3. *,/, //,% (multiplication,division,floordivision, modulus)
4.+,-(addition, subtraction)
5. >>,<<(rightshift,left shift)
6. &(bitwiseAND)
7. ^(bitwiseXOR)
8. |(bitwise OR)
9.==, !=,>,>=, <,<=(comparison operators)
10.=,+=,-=,*=,/=,%=,**=,//=,&=, |=,^=, >>=,<<=(assignmentoperators)
11. not(logicalNOT)
12. and(logicalAND)
13. or(logicalOR)
Parentheses()canbeusedtooverrideprecedence andforceaspecificorder of evaluation.
DataTypes
NumericTypes
o int:Integervalues(e.g.,1,42, -7)
o float:Floating-point(decimal)values(e.g.,3.14,-0.001)
o complex:Complexnumbers(e.g.,2+3j)
SequenceTypes
o str:Stringofcharacters(e.g.,"hello",'world')
o list:Ordered,mutable collection(e.g.,[1,2,3],['a','b','c'])
o tuple:Ordered,immutablecollection(e.g.,(1,2,3),('a','b','c'))
o range:Sequenceofnumbers(e.g.,range(10),range(1,5))
MappingType
o dict:Key-valuepairs(e.g.,{'name':'Alice','age':25})
SetTypes
o set:Unorderedcollection ofuniqueelements (e.g.,{1,2, 3},{'a','b', 'c'})
Boolean Type
o bool:BooleanvaluesTrueorFalse
None Type
o None:Representstheabsenceof avalue (e.g.,None)
MutableandImmutableDataTypes
MutableDataTypes
o Canbechanged aftercreation(e.g., modifyingelements,adding orremoving elements)
o Examples:
list:my_list= [1,2, 3](can add,remove, orchangeelements)
dict:my_dict={'key': 'value'}(can add,remove,orchangekey-value pairs)
set:my_set= {1,2, 3}(canadd orremove elements)
ImmutableDataTypes
o Cannotbechangedaftercreation(anymodificationcreatesanewobject)
o Examples:
int:my_int =5 (cannot changethe valuedirectly)
float:my_float=3.14(cannot changethevalue directly)
str:my_str="hello"(cannotchangecharactersdirectly)
tuple:my_tuple=(1,2,3)(cannotchange elements)
Statements
Instructionsexecutedby the Pythoninterpreter.
Typesofstatements:
o Expressionstatements:Evaluateanexpression(e.g.,a+b).
o Assignmentstatements:Assignvaluesto variables(e.g.,x=5).
o Controlflowstatements:Directtheflowof execution(e.g.,if,for,while,break,continue).
o Functiondefinition:Defineafunction(e.g.,def my_function():).
Expressions
Combinationsofvariables,operators,and valuesthatyielda result.
Examples:
o Arithmeticexpressions: 2+3.
o Logicalexpressions: aand b.
o Stringexpressions:"Hello" +""+ "World".
Canbepartofalarger statement.
Evaluation
Theprocessofcomputingtheresultofan expression.
Pythonevaluatesexpressionsusingtherulesofprecedence andassociativity.
Comments
Usedto annotate codeandmakeit more understandable.
Single-linecomments:Beginwith #(e.g., #This isacomment).
Multi-linecomments: Enclosedin triplequotes(e.g., '''This isamulti-linecomment''').
InputandOutputStatements
Input:
o input():Readsalineoftext inputfrom theuser(e.g., name=input("Enter yourname: ")).
o Alwaysreturnsa string.
Output:
o print():Outputstextorvariablestotheconsole (e.g.,print("Hello,World!")).
o Canacceptmultipleargumentsseparatedby commas(e.g.,print("Name:",name)).
o Optionalargumentslikesepandendtocustomizetheoutput(e.g.,print("Hello","World", sep="-")).
DataTypeConversion
Convertingonedatatypeto another.
Common functions:
o int():Convertsavaluetoaninteger(e.g.,int("42")).
o float():Convertsavalue toafloat(e.g., float("3.14")).
o str():Convertsavalue toastring(e.g., str(42)).
o list():Convertsa valuetoalist(e.g., list("abc")resultsin ['a','b', 'c']).
o tuple():Convertsavalue toatuple(e.g.,tuple([1,2,3])).
o set():Convertsavaluetoa set(e.g.,set([1, 2,2, 3])).
o dict():Convertsavalueto adictionary(whenapplicable, e.g.,dict([('a',1), ('b', 2)])).
DebugginginPython
Definition:
o Theprocess offinding andfixing errorsor bugsinyourcode.
CommonDebuggingTechniques:
o PrintStatements:Insertprint()statementsinyourcodetocheckvaluesofvariablesand program
flow (e.g., print("Checkpoint reached"), print("Value of x:", x)).
o UsingAssertions:assertstatementtocheckifaconditionisTrue,andifnot,itraisesan AssertionError
(e.g., assert x > 0, "x must be positive").
ControlStatementsinPython
If Statement:
o Executesablock ofcodeif acondition is true.
o Example:
If-Else Statement:
o Executesoneblock of codeif acondition istrue, and anotherblockifit is false.
o Example:
If-elif-elseStatement:
o Checks multiple conditions in sequence, executing the first block of codewherethe condition
is true.
o Example:
WhileLoop:
o Repeatsablockofcode aslongas aconditionis true.
o Example:
o Canusebreaktoexit theloop prematurely.
o Canusecontinueto skipto thenextiteration.
ForLoop
For Loop:
o Iteratesoverasequence(e.g.,list, tuple,string)or rangeof numbers.
o Syntax:
o Example:
ForLoop withBreak and Continue:
o break:Exittheloop prematurely.
o continue:Skipto thenext iteration.
o Example:
TIMETOPRACTICE
MULTIPLECHOICEQUESTIONS
1. Whichof thefollowing isa valid identifier in Python?
A. 2variable
B. variable2
C. variable-2
D. variable2
2. Whichof thefollowing is NOT akeyword inPython?
A. class
B. try
C. value
D. finally
3. What is theresult oftheexpression4+3 *2 in Python?
A. 10
B. 14
C. 20
D. 16
4. Which data typeis mutablein Python?
A. int
B. float
C. tuple
D. list
5. What will bethe output of thefollowing code?print(2 ** 3 ** 2)
A. 64
B. 512
C. 256
D. 128
6. Whichfunctionis usedto readinput fromtheuserin Python?
A. scanf()
B. input()
C. get()
D. read()
7. What will be theoutput of thefollowing code?print (type(5.0))
A. <class'int'>
B. <class'float'>
C. <class'double'>
D. <class'decimal'>
8. Whichofthe followingstatementsisused tocreateaconstantin Python?
A. constantPI=3.14
B. PI=3.14
C. constPI=3.14
D. definePI= 3.14
9. Whichofthe followingisused tocreate acommentin Python?
A. // comment
B. /* comment */
C. <!--comment-->
D. # comment
10. Whatwill betheoutputof thefollowing code? print('Hello '+'World!')
A. Hello World!
B. Hello+ World!
C. HelloWorld!
D. Hello +World!
11. Whichofthefollowing datatypes is immutable?
A. list
B. set
C. dict
D. str
12. Whatis theresult ofbool(0)in Python?
A. True
B. False
C. None
D. 0
13. Whichloopisguaranteedtoexecuteatleast once?
A. for
B. while
C. do-while
D. Noneof the above
14. What isthecorrect syntaxforawhile loopin Python?
A. whilex >0 { ... }
B. while(x >0): ...
C. while x >0: ...
D. while(x >0) {... }
15. Whichofthe following can beused to stop a loop prematurely?
A. stop
B. exit
C. break
D. end
16. Whatwillbe theoutput ofthe followingcode?fori inrange(5): print(i)
A. 0 1 2 3 4
B. 1 2 3 4 5
C. 0 1 2 3 4 5
D. 1 2 3 4
17. Whatwillbetheoutputofthefollowingcode?
for i in range(3):
print(i)
A. 1 2 3
B. 0 1 2
C. 0 1 2 3
D. 12 3 4
18. Whatwillbetheoutputofthefollowingcode?
for i in range(2, 5):
print(i,end='')
A. 2 3 4 5
B. 2 3 4
C. 3 4 5
D. 2 3 4 5 6
19. Whatwillbetheoutputofthefollowingcode?
for i in range(1, 10, 3):
print(i,end=',')
A. 1, 4, 7, 10,
B. 1, 4, 7,
C. 1 4 7
D. 1 4 7 10
20. Whatwillbetheoutputofthefollowingcode? i
=1
while i <5:
print(i) i
+= 1
A. 12345
B. 1234
C. 123
D. 01234
VeryShortAnswer Questions
1. Whatisthe extensionof Pythonfiles?
2. Howdoyou startthePythoninterpreterininteractive mode?
3. Whatis thepurposeofindentation in Python?
4. Givean exampleof avalid identifier in Python.
5. Howdo you assign avalueto a variablein Python?
6. Namethearithmeticoperatorsin Python.
7. Whichoperatorhasthehighestprecedencein Python?
8. Whatdatatypeisreturnedbythe input()function?
9. Howdo you writeasingle-linecomment in Python?
10. Whatistheoutputofprint(3 +4 *2)?
ShortAnswerType Questions
1. Whatisthedifference betweeninteractivemodeand scriptmodein Python?
2. Explainthesignificance ofindentationinPython.
3. Whatareidentifiersin Pythonand what arethe rulesfor naming them?
4. Listfivekeywords inPythonand explaintheiruse.
5. Whatisavariablein Pythonand howis itdifferent froma constant?
6. Explainthedifference betweenthe ==and=operators.
7. Whatarethedifferent typesofoperatorsin Python?
8. Differentiatebetweenmutableandimmutabledata typeswithexamples.
9. Howdo you convert alist to atuplein Python?
10. WriteaPythoncodesnippetthatdemonstratestheuseoftheif-elif-elsestatement.
LongAnswerTypeQuestions
1. [Link],andprovidean example to
illustrate your explanation.
2. [Link] precedence with
examples.
3. Describe the concept of mutable and immutable data types in Python. Provide examples of each type
and discuss scenarios where one might be preferred over the other.
4. What are control statements in Python? Explain with examples the use ofif-else, if-elif-else,
whileloop, and for loop.
5. [Link] conversion.
Assertion-Reasoningbased questions
1. Assertion(A):IndentationismandatoryinPythontodefinetheblockof code.
Reason(R):Pythonusescurlybraces{} toindicate thestart and endof ablock of code.
o [Link] Aand Raretrue, andR isthecorrectexplanation ofA.
o [Link] andRaretrue,butRis notthecorrectexplanationofA.
o C.A is true,but R is false.
o [Link] false, but R is true.
2. Assertion (A):The range()function in a forloop generates asequenceof numbers. Reason (R):The
range() function is used to iterate over a sequence of values with a specified start, stop, and step.
o [Link] Aand Raretrue, andR isthecorrectexplanation ofA.
o [Link] andRaretrue,butRis notthecorrectexplanationofA.
o C.A is true,but R is false.
o [Link] false, but R is true.
3. Assertion(A):VariablesinPythonmustbedeclaredwithaspecificdatatypebeforetheycanbe used.
Reason(R):Pythonisadynamicallytypedlanguage,whichmeansvariablesdonotneedexplicit declaration before
use.
o [Link] Aand Raretrue, andR isthecorrectexplanation ofA.
o [Link] andRaretrue,butRis notthecorrectexplanationofA.
o C.A is true,but R is false.
o [Link] false, but R is true.
4. Assertion(A):InPython,stringsaremutabledata types.
Reason (R): Mutable data types can be changed after they are created, while immutable data typescannot
be modified.
o [Link] Aand Raretrue, andR isthecorrectexplanation ofA.
o [Link] andRaretrue,butRis notthecorrectexplanationofA.
o C.A is true,but R is false.
o [Link] false, but R is true.
5. Assertion(A):Theprint()[Link](R):
Theinput()function in Pythonis used to readastring from theuser.
o [Link] Aand Raretrue, andR isthecorrectexplanation ofA.
o [Link] andRaretrue,butRis notthecorrectexplanationofA.
o C.A is true,but R is false.
o [Link] false,but R is true
Case-Study/Competencybased questions
Case Study 1: You are developing a Python script to convert temperatures between Celsius and Fahrenheit
based on user input. The script should handle data type conversion, validate user inputs, and provide
clear instructions for temperature conversion.
1. Describehow youwouldimplementdatatypeconversion inthetemperatureconversion script.
2. Discussthe use of input and output statements to interact with users and handle different
scenarios(e.g., invalid input).
CaseStudy2:ImagineyouaretaskedwithwritingaPythonscriptforabasiccalculatorthatcan perform addition,
subtraction, multiplication, and division. The program should:
3. Prompttheuser to entertwo numbers.
4. Asktheusertochoose anoperation(addition,subtraction,multiplication,division).
5. Performthechosenoperationanddisplaytheresult.