Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
55 views
38 pages
MMMM
Uploaded by
SHRADDHA SINGH
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save mmmm For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
55 views
38 pages
MMMM
Uploaded by
SHRADDHA SINGH
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save mmmm For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 38
Search
Fullscreen
OMPUTER pee SCIENCE with . Miia yinons Textbook for Class XII * Programming & Computational Thinking * Computer Networks * Data Management (SQL, Django) * Society, Law and Ethics SUMITA ARORA %PADHAAIL Contents 1” Python Revision Tour 1-36 1.1 Introduction 1.2. Tokensin Python 1.21 Keywords 2 41.2.2 Identifiers (Names) 2 1.23 LiteralsValues 3 1.24 Operators 4 1.25 Punctuators 4 13. Barebones ofa Python Program 14. Variablesand Assignments 1.4.1 Dynamie Typing 6 14.2 Multiple Assignments 6 15. Simple Input and Output 16 Data Types 1.7. Mutable and Immutable Types 1.8. Expressions 1.81 Evaluating Arithmetic Operations 14 1.82 Evaluating Relational Expressions 15 1.83 Evaluating Logical Expressions 16 184 Type Casting (Explicit Type Conversion) 16 1.85 Math Library Functions 16 19 Statement Flow Control 1.10 Theif Conditionals 1.10.1Plain if Conditional Statement 19 1.10.2The ifelse Conditional Statement 20 1.10.3Theifelif Conditional Statement 20 1.104Nested if Statements 22 4.10.5Storing Conditions 22 1.11 Looping Statements LILI The for Loop 23 1.112 The while Loop 25 1.12 jump Statements ~ break and continue ‘The break Statement 25 The continue Statement 26 1.13. More on Loops 1.13.1 Loop else Statement 27 1.13.2 Nested Loops 28 2 10 12 4 18, 19 23 25 27PADHAAIL 4 Ls _ Python A Revision Tour tn Wis Charter 1.1 Introduction 18 Expressions 1.2. Tokens in Python 1.9. Statement Flow Control 1.3. Barebones of a Python Program 1.10. The if Conditionals 1.4 Variables and Assignments 1.11 Looping Statements 15 Simple input and Output 1.12. Jump Statements ~ break and continue 1.6. Data Types 1.13 More on Loops. 1.7. Mutable and Immutable Types 1.1 INTRODUCTION You must have enjoyed learning Python in class XI. Python programming language, developed by Guido Van Rossum in early 1990s, has become a very popular programming language among beginners as well as developers. The journey of Python that you started in class XI will continue in class XII as well. In class XH, you shall learn more about Python and some advanced concepts. Before we start with newer topics and concepts in Python, let us revise all that you have learnt in class XI. And this chapter will be doing just the same, i, take you to the revision tour of Python that you learnt in your previous class.PADHAAIL 2 COMPUTER SCIENCE WITH PYTHON — x) 1.2 TOKENS IN PYTHON The smallest individual unit in a program is known as a Token ora lexical unit. Python has following tokens : ‘The smallest individual unit in a ‘program is known as a Token or y a lexical unit. (i) Keywords i) Identifiers (Names) (ii) Literals (iv) Operators (v) Punctuators # A sample Python program for al_in range(1,_1 punctuators if a%2 a: ewer ‘iterals pring NO operators ‘dents Figure 1.1 Some tokens in a Python program. Let us revise our understanding of tokens. 1.2.1 Keywords PKERWORD I | Keywords are predefined words with special meaning to the 1A keyword is a word hee] language compiler or interpreter. These are reserved for special meaing, reserved by special purpose and must not be used as normal identifier _ programming language. names, Python programming language contains the following keywords : False assert’ «del «= for —in or while None break elif = from is pass with True class else global lambda raise yield and continue except if nonlocal retum as def finally import not ty 1.2.2. Identifiers (Names) Identifiers are the names given to different parts of the program viz. variables, objects, classes, functions, lists, dictionaries and so forth, The naming rules for Python identifiers can be summarized as follows : © Variable names must only be a non-keyword word with no spaces in between, © Variable names must be made up of only letters, numbers, and underscore (_). © Variable names cannot begin with a number, although they can contain numbers.PADHAAIL Chapter 1 : PYTHON REVISION TOUR 3 The following are some The following are some invalid identifiers : valid identifiers : DATA-REC contains special character - (hyphen) pee DATES 777 (other than A - Z, a-z and _ (underscore) ) se aa 2scict Starting with a digit = a break reserved keyword zarez9_H013_3k ated My.file contains special character dot (..) 1.2.3 Literals/Values Literals are data items that have a fixed/constant value. Python allows several kinds of literals, which are being given below. (i) String Literals A string literal is a sequence of characters surrounded by quotes (single or double or triple quotes). String literals can either be single line strings or multi-line strings. © Single line strings must terminate in one line i.e,, the clos same line as that of the opening quotes. (See below) 18 quotes should be on the © Multiline strings are strings spread across multiple lines. With single and double quotes, each line other that the concluding line has an end character as \ (backslash) but with triple quotes, no backslash is needed at the end of intermediate lines. (see below) : >>> Text = "Hello World” «—__ Single line sing Multi-line sing "Hello ¢——_ No backslash needed een No backslash In strings, you can include non-graphic characters through escape sequences. Escape sequences are given in following table : Escape ‘What it does Escape What it does _[Non-graphic character] _ sequence [Non-graphic character] W Backslash (\) \r Carriage Return (CR) v Single quote (’) \t Horizontal Tab (TAB) \ Double quote (") \ woox Character with 16-bit hex value 200% (Unicode only) \a ASCII Bell (BEL) \Uwoooax | Character with 32-bit hex value i sa0000Xxx (Unicode only) ASCII Backspace (BS) Ww “| ASCII Vertical Tab (VT) ASCII Formfeed (FF) \ooo Character with octal value 000 New line character \xhh | | Character with hex value hh Character named name in the : Unicode database (Unicode only) | }4 (i) Numeric Literals (ii) Boolean Literals (iv) Special Literal None COMPUTER SCIENCE WITiRARHAAI Sa 4 Numeric literals are numeric values and these can be one of the following types : (a) int (signed integers) offen called numbers with no decimal point. ‘The integer literals can be written in: ger beginning with digits 19. 6S 1234, 4100 ete. peginning with 0o (zero followed by letter 0) ¢.g., 0035, 0077 te. and 9 are invalid digits. th Ox (zero followed by letter X) eg, 0x73, ters for hexadecimal numbers are 0-9 and just integers or ints, are positive or negative wig le ‘© Decimal form : an inte} © Octal form : an integer Here do remember that for Octal, 8 © Hexadecimal form : an integer beginning wil OxAF ete. Here remember that valid digits/let AF. (b) Floating Point Literals. Floating point literals or real literals floats represent real numbers vad are written with a decimal point dividing the integer and fractional parts are numbers having fractional parts. These can be written in fractional form e.g., -13.0, .75, 7. ete. or in Exponent form e.g, 0.17E5, 3.£2, .6E# etc. erals are of the form a+b], where a and b are floats and J (or j) represents (Complex number lit. fe real part of the number, and is the imaginary AL which is an imaginary number). a is the part. the two Boolean values i., True (Boolean. ‘A Boolean literal in Python is used to represent one of her have value as True or as False. true) or False (Boolean false). A Boolean literal can eit Python has one special literal, which is None. The None literal is used to indicate absence of value. Python can also store literal collections, in the form of tuples and lists etc. 1.2.4 Operators Operators are tokens that trig; and oth ger some computati i i i % tokens that \putation / action when applied to variables er The operators can be arithmetic operators (+, ~ *, /, %, ™, /), bitwise operators (&, 1) shift operators (<<, >), identity operators (is, is not), relational operators (>, <, >=) < = 15), logical tin), and operators (and, of), assignment ope: eml poe ermenc Ns i (i arithmetic-assignment operators (may oni ee PS ee =, I=). 1.2.5 Punctuators Punctu piece fara bie used in programming languages to organize sentence eel and emphasis of expressions, statements, and program Most common punctuators of Python programming language a re : TaN) (1{}@, 2.7CChopter 1: PYTHON REVISION TOUR 1.3 BAREBONES OF A PYTHON PROGRAM. A Python program may contain various elements such as comments, statements, expressions etc. Let us talk about the basic structure of a Python program. j# This program shows a program’ s components # Definition of function SeeYou() follows Conmens& def Seevou() : + Function (tegin with #) print ("Time to say Good Bye !'|") #Main program-code follows now a= 15 Statement ——— ees sete Expressions print a a i af bos # colon means it’s a block yy print ("Value of ‘a was more than 15 initially.") Inline comments (comment beginning Ise: in the middle ofa line) “a print ("Value of 'a' was 15 or less initially.”) Function call — co evou() # calling above defined function Seevou() Indentation «7 (see indented lines ‘As you can see that the above sample program contains various components like : © Expressions, which are any legal combination of symbols that represents a value. © Statements, which are programming instructions. © Comments, which are the additional readable information to clarify the source code. ‘Comments can be single line comments, that start with # and multi-line comments that can be either triple-quoted strings or multiple # style comments. © Functions, which are named code-sections and can be reused by specifying their names (function calls). © Block(s) or suite(s), which is a group of statements which are part of another statement or a function: All statements inside a block or suite are indented at the same level, 1.4 VARIABLES AND ASSIGNMENTS Variables represent labelled storage locations, whose values can be manipulated during program run. In Python, to create a variable, just assign to its name the value of appropriate type. For ‘example, to create a variable namely Student to hold student's name and variable age to hold student's age, you just need to write somewhat similar to what is shown below : | Student ="Jacob’ Age =16PADHAAIL COMPUTER SCIENCE WITH PYTHON _ yy low. eate labels referring to these values as shown below. Python will internally cre (ja) 1.4.1. Dynamic Typing In Python, as you have learnt, a variable is defined by assigning to it some value (of a particular type such as numeric, string etc). For instance, after the statement : X=1e We can say that variable x is referring to a value of integer type. / Later in your program, if you reassign a value of some other type to variable x, Python will not complain (no error will be raised), e.g., x=10 EX A variable pointing oa value of prde@) 8 Certain type, can be made to| x ‘110 World” point to a value/object of| print(x) different type. This is called| : Dynamic Typing. Above code will yield the output as : | Hello World So, you can think of Python variables as labels associated with objects (literal values in our case here); with dynamic typing, Python makes a label refer to new. value with new assignment (Fig. 1.2). Following figure illustrates it, ria ‘Er —ee] X= "Hello Wortg” x Figure 1.2 Dynamic typing in Python variables, Dynamic Typing vs. Static Typing Dynamic typing is different from Static Typing. In Static typin, i it m ng - '& a data type is attached with, variable when it is defined first and itis fixed, That is, data type ofa Wicebe cannot be changed in static typing whereas there is no such restriction in dynamic typing, which is supported by 1.4.2 Multiple Assignments Python is very versatile with assignments, Let's see how, 1. Assigning same value to multiple variables, Y i i Variables in a single statement, 2, BY Sn assign Same value to multiple a=b=c=i0 will assign value 10 to all three vatiables 4, bye,PADHAAIL Chapter | + PYTHON REVISION TOUR Thee 2. Assigning multiple values to multiple variables. You can even assign multiple values to multiple variables in single statement, eg., X,Y, 2= 10, 28, 30 Tewill assign the values order wise, ie, first variable is given first value, second variable the second value and so on. That means, above statement will assign value 10 to x, 20 to y and 30 to z. If you want to swap values of x and y, you just need to write as follows : YAY In Python, assigning a value to a variable means, variable’s label is referring to that value. val =3 val =6 3000 3 [for statement i val = 3] %_2000 * Ll | tor taenee ral val * Memory address (8000) Memory address (2048] storing Variable val stores values at same location + storing value Sis assigned a —_value G is assigned a label as (memory-address) and changes values 1 label as val {for statement val = 6]. stored in it, val for statement val= 3] Now val no longer is referencing to memory location 3000. Literal values are having a fixed location and variable (2) In traditional programming languages arias vafossrice tear a table) like CiC+* etc. (©) In Python programming language Figure 1.3 How variables are stored in traditional programming languages and in Python, 1.5 SIMPLE INPUT AND OUTPUT In Python 3.x, to get input from user interactively, you can use built-in function input( ). The function input( ) is used in the following manner : variable_to_hold_the_value = input (
) For example, name = input (‘What is your name ?") The above statement will display the prompt as : tn [3]: name Wh 's your name 7]PADHAAIL COMPUTER SCIENCE WITH PYTHON ~ 3 tums a value of String type. Python offers two functions int() qe pat) function abS¥4 Ze «received through input() into int nq and float() to be used with input( ) to convert the value: float types. You can : Read in the value using input( ) function. : and i ‘use int() or float() function with the read value to change the type of input value to int or float respectively. You can also combine these two steps in a single step too, ie., as :
= int( input(
) )
= float( input(
) ) Ant input(*vnat is your age?) )[% What 1s your age ? 16 ad 20 22): type(marks) Out{24]: Float fan [22]: type(a out(22]: int / While inputting integer values using int() with input(), make sure that the value being entered must be int type compatible, Similarly, while inputting floating point values using float( ) with input(), make sure that the value being entered must be float type compatible (e.g, ‘abc’ cannot be converted to int or float, hence it is not compatible). Output Through print( ) Statement The print() function of Python 3.x is a way to send output to standard output device, which is normally a monitor. | The simplified syntax to use print( ) function is as follows : Print(*objects, [ sep =‘ ’ or
end = “\n* or
])9 “objects means it can be one or multiple comma separated objects to be printed. Let us consider some simple examples first : print ("hello") a string print (17.5) # a number print (3.14159*(r#p)) # the result of a calculation, which will 4 be performed by Python and then printed #out (assuming that sone number has been # assigned to the variable r) #multiple conma separated expressions print ("I\’m", 1245, "years old.")PADHAAIL Chapter 1: PYTHON REVISION TOUR ne The print statement has a number of features : © it auto-converts the items to strinj igS i.e, if you are printing a numeric value, it will automatically convert it into e 1 quivalent string and print it ; for numeric expressions, it first evaluates them and then converts the result to string, before printing, © i inserts spaces between items automatically because the default value of sep argument (separator character) is space(’’) Consider this code : Four diferent srng objects with no Print ("My", “name”, "is", "anit") <7 spt them ae being primed will print ; ‘But the output tne has automatically spaces inser in My name 1s amit. «~~ setween them becautedeful ep character isa space, You can change the value of separator character with sep argument of print() as per this : The code : print ("My", "name", “is” “amit.", sep='.. will print 4 ; This rime the print) separated the items My..smame...is...Amit. tghellrags with given sep character, which io.” © it appends a newline character at the end of the line unless you give your own end argument. Consider the code given below : print ("My name is Anit.") print ("I am16 years old") It will produce output as : or blan My name is Amit. 1 am 16 years old ment with a print() function then the print() will print the line If you explicitly give an end ar; ied with the end argument, and not the newline character, e.g, and end it with the string spe the code print("My name is Amit. ", end= ‘$?) print ("I am 6 years old. ") will print output as: This time the print() ended the lne with given end “4 character, which i'§ here: And becuse ites not My name is Amit. $1 am16 years old. — newline, nu! ine was printed from her itself. Write a program to input a number and print its cube. num = float (input(‘Enter a nunber: ')) ‘num_cube = num * num * num print(*The cube of", num, is’, num_cube)PADHAAII 10 COMPUTER SCIENCE WITH PYTHON - xi | J 1.2 Write a program to input a number and prin ts square root. reoram num = float (input( ‘Enter a number: ')) num_sqrt = num ** 0.5 print( ‘The square root of, num, 'is', num_sqrt) a PYTHON : BASIC INPUT/OUTPUT Progress In Python 1.1 ni ‘This ‘PriP” session is aimed at revising various concepts you learnt in Class XI. Science with Python and fill it there in PriP 1.1 under Chapter 1 after practically doing it on the computer. Please check the practical component-book — Progress in Computer ) popibece 1.6 DATA TYPES Data types are means to identify type of data and set of valid operations for it. Python offers following built-in core data types : (i) Numbers (if) String (ii) List (jo) Tuple (v) Dictionary. (i) Data types for Numbers Python offers following data types to store and process different types of numeric data : (a) Integers © Integers (signed) © Booleans (®) Floating-Point Numbers (©) Complex Numbers (a) Integers. There are two types of integers in Python : ( Integers (signed). It is the normal integer representation of whole numbers. Python 3.x provides single data type (int) to store any integer, whether big or small. It is signed representation, ie, the integers can be positive as well as negative. (i) Booleans. These represent the truth values False and True, The Boolean type is a subtype of plain integers, and Boolean values False and True behave like the values 0 and 1, respectively. (+) Floating Point Numbers. In Python, floating point numbers represent machine-level double precision floating point numbers (15 digit precision). The range of these numbers is limited by underlying machine architecture subject to available (virtual) memory. (© Complex Numbers. Python represents complex numbers in the form A+Bj Complex ‘numbers are a composite quantity made of two parts: the real part and the imaginary part, both of which are represented internally as float values (floating point numbers).PADHAAI CChopter 1: PYTHON REVISION TOUR You can retrieve the two components using attribute references. For a complex number z : © zzeal gives the real part. © zimag gives the imaginary part as a float, not as a compiex vaiue Table 1.1 The Range of Pyth 1m Ntunbers Range ited range, subject to available (virtual) memory only | Floating point an unlimited range, subject to available (virtual) memory on umbers chi Complex Same as floating point numbers because the real and numbers imaginary parts are represented as floats (i) Data Type for Strings All strings in Python 3.x are sequences of pure Unicode characters. Unicode is a system designed to represent every character from every language. A string can hold any type of known characters ie, letters, numbers, and special characters, of any known scripted language. Following are all legal strings in Python : “abed” , 1234", ‘$%°&’, '7227', "SABES" , “aBy", ad’, Nopeac” A Python string is a sequence of characters and each character can be individually accessed using its index. (i) Lists A List in Python represents a group of comma-separated values of any datatype between square brackets e.¢., following are some lists : (1, 2,3, 4,5] (a, ‘ei, ] ['Neha’, 102, 79.5] In list too, the values internally are numbered from 0 (zero) onwards ie, first item of the list is internally numbered as 0, second item of the list as 1, 3rd item as 2 and so on. (iv) Tuples Tuples are represented as group of comma-separated values of any date type within parentheses, e.g, following are some tuples : s(t, 2, 3,4, 5) a= (2,4, 6, 8) r= (ae, ) h= (7, 8, 9,'R,'B'C)PADHAAIL COMPUTER SCIENCE WITH PYTHON ~ yy (v) Dictionaries The dictionary is an unordered set of comma-separated key : value pairs, within {}, withthe requirement that within a dictionary, no two keys can be the same (ie, there are unique keys within a dictionary), For instance, following are some dictionaries : {dire 2a: js’ 4, ‘Us 5} >>> vowels = {'a': 1, 'e: 2, 3, ‘0:4, ‘U's 5} >>> vowels] SN te 0 61,2 an athe of sony vol 2 103.343 sf ae opciee Following figure summarizes the core data types of Python. Core Data Types | Numbers None Sequences Mappings | | | Integer Floating Complex Sting Tuple List Dictionary 1 point { | Boolean 1.7 MUTABLE AND IMMUTABLE TYPES The Python data objects can be broad] ly categorized into two — mutable and immutable types, in simple words changeable or modifiabl le and non-modifiable types. Immutable Types The immutable types are those that can never change their value in place. In Python, the following types are immutable : integers, floating pont munbers, Bolan tring, tuples. In immutable types, the variable names are stored as references to a value-object. Each time you change the value, the variable’s referenc © memory address changes. See following explanation for sample code given below : © Initially these three statements are executed : pes . All variabtes having same value reference and the tame % q 4 tate bet en pg 1 lah ee integer rePADHAAIL Figure 1.4 © When the next set of statements execute, ie, 8 qer then these variable names are made to point to different integer objects. Figure 1.5, Mutable Types Mutability means that in the same memory address, new value can be stored as and when you want. The types that do not support this property are immutable types. The mutable types are those whose values can be changed in place. Only three types are mutable in Python. ‘These are : lists, dictionaries and sets. To change a member of a list, you may write : Chk = (2, 4, 6] Chk[1] = 48 It will make the list namely Chk as [2, 40, 6].14 18 PADHAAIL COMPUTER SCIENCE WITH PYTHON — yu) EXPRESSIONS. A th expression in Pythe a bination of operators, literals and variables. in Python is any valid combina ie A : ons, logical expressions, compound expressions etc. REE Arithmetic expressions involve numbers (integers, floatingy point numbers, complex numbers) and arithmetic operators, felipe eid €g4245°3,-8* 6/5 and atoms. An expression is An expression having literals and/or variables of any valid Saree Cee ee type and relational operators is a relational expression. For a example, these are valid relational expressions : xy, yee, zl=x, q, X
2, xasyl=z An expression having literals and/or variables of any valid type and logical operators is a logical expression. For example, these are valid logical expressions : aorb, bandc, aandnotb, notcornotb Python also provides two string operators + and *, when combined with string operands and integers, form string expressions. Following are some legal string expressions : "and" + "then" #would result into ‘andthen' - concatenation "and" *2 #would result into ‘andand' - replication 1.8.1 Evaluating Arithmetic Operations ‘To evaluate an arithmetic expression (with operator and operands), Python follows these rules : © Determines the order of evaluation in an expression considering the operator precedence. © As per the evaluation order, for each of the sub-expression (generally in the form of
e.g., 13 % 3) = Evaluate each of its operands or arguments, ™ Performs any implicit conversions (c.g., arithmetic on mixed types). For implicit given after the rules, = Compute its result based on the operator, = Replace the subex evaluation. Promoting int to float or bool to int for conversion rules of Python, read the text Pression with the computed result and carry on the expression & Repeat till the final result is obtained. In a mixed arithmetic expression, Python converts all operands wy : Is up to the type of the largest operand (type promotion). In the simplest form, an expression is like opt Heit op2 aly or p“*a), Here, if both arguments are standacd numeric types, the following coercions are applied : © If either argument is a complex number, converted to complex ; © Otherwise, if either ar number, the other is con the other is rgument is a floating point verted to floating point ; © No conversion if both operands without programmer ; nto are integers, 3PADHAAIL Chopler I: PYTHON REVISION TOUR 15 Table operator precedence Description | 0 Parentheses (grouping) Highest Exponentiation x Bitwise nor Positive, negative (unary + , -) Multiplication, division, floor division, remainder + Addition, subtraction Bitwise AND Bitwise XOR Bitwise OR £) <2, >, >=, <> Comparisons (Relational operators), identity operators is, is not not x Boolean NOT and Boolean AND Boolean OR Lowest Example 1.1. Consider below given expressions what. What will be the final result and final data type ? (@) a, b=3,6 (b+) a, b=3,6 © a,b c=b/a cab//a c=b%a Ans. (a) In expression c= 6/3 bs/ya c=2.0 1 | int int hah = Here, the operator i which abv —_— gives atte pres * Floating pt () In expression () Inexpression c=6//3 b s/f a O%3 b & a cna | i 8 | i int int float int eis = int float 1.8.2 Evaluating Relational Expressions All comparison operations in Python have the same priority, which is lower than that of any arithmetic operations. All relational expressions (comparisons) yield Boolean values only i., True or False. Further, chained expressions like a
q) and(q
() function of appropriate data type, in the following manner :
(expression) where
is the data type to which you want to [IveE CASTING | type-cast your expression. The explicit conversion of an For example, if we have (a =3 and b = 5.0), then cpeent to a specific type is int(b) called type casting. will cast the data-type of the expression as int. 1.8.5 Math Library Functions Python's standard librar i . y ry provides a module namely math for math related functions that work with all number types except for complex numbers,PADHAAI CChopter 1 : PYTHON REVISION TOUR 7 In order to work with functions of math module, first import it no » You need to first import it to your program bj giving statement as follows as the top line of your Python script : " eee import math Then you can use math library's functions as math.
. Table 1.2 Some Mathematical Functions in math Module 3 Prototype | UO | Genera ee Description Example 1. | cel | mathceil(aum) The ceil() function returns the | math.cel(1.03) gives 2.0 smallest integer not less than num. | math.ceil(-103) gives ~10. 2. | sqrt math.sqrt (num) The sqrt( ) function retums the | math.sqrt (81.0) gives 9.0. square root of mum. If num <0, domain error occurs. 3. [exp | math.exp(arg) The exp()) function returns the | math.exp(2.0) gives the value natural logarithm e raised to the | of e, arg power. 4. | fabs | math.fabs (num) The fabs( ) function returns the | math.fabs(1.0) gives 1.0 absolute value of num. math.fabs(-10) gives 1.0. 5. | floor | math.floor (num) The floor ) function retums the | math.floor (1.03) gives 1.0 largest integer not greater than | math,floor(-103) gives -20. num. 6 | log | math.log (num, [base] | The log( ) function returns the | math.log(1.0) gives the natural natural logarithm for num. A | logarithm for 1.0, domain error occurs if num is | mathog(1024, 2) will give Tregative and a range error Occurs | tog rithm of 1024 to the base 2. if the argument mum is zero. 7. | logi0 | math.logi0 (num) The Jogi0( ) function returns | math.logl0(1.0) gives base 10 the base 10 logarithm for num. | logarithm for 1.0, A domain error occurs if num is negative and a range error occurs if the argument is zero. 8. | pow | math.pow (base, exp) | The pow() function returns base | math.pow (3.0, 0) gives value of raised to exp power ic, base exp. | 3° ‘A domain error occurs if base =0| math.pow(40, 2.0) gives value and exp <=0; also if base
(
) STATEMENT FLOW CONTROL In a program, statements may be executed sequentially, selectively or iteratively. Every programming language provides constructs to support sequence, selection or iteration. A conditional is a statement set which is executed, on the basis of result of a condition. A loop is a statement set which is executed repeatedly, until the end condition is satisfied. 1. Compound Statement A compound statement represents a group of statements executed as a unit, The compound statements of Python are written in a specific pattem as shown below :
:
v1: PYTHON REVISION TOUR ‘The conditionals and the loops are compound statements, i: For all compound statements, following points hold : ® The contained statements are not written in the same column as the control statement, rather they are indented to the right and together they are called a block. © The first line of compound statement, ie, they contain other statements. , its header contains a colon (;)at the end of it. For example : nuat = int (input(“Enter nunberi")) fund = int (input ("Enter nunbert")) iF mum2 < numd : <————— The colon (:) atthe end of header line smears itis compound statement ‘t=num2* nun2 tat+10 Tre contained statemens within if are indented to thevight print (nun2, num, t) 2. Simple Statement Compound statements are made of simple statements. Any single executable statement is a simple statement in Python. 3. Empty Statement The simplest statement is the empty statement ie, a statement which does nothing. In Python an empty statement is the pass statement. It takes the following form : pass Wherever Python encounters a pass statement, Python does nothing and moves to next statement in the flow of control. 1.10 THE IF CONDITIONALS The if conditionals of Python come in multiple forms : plain if conditional, if-else conditional and if-elif conditionals. 1.10.1. Plain if Conditional Statement An if statement tests a particular condition; if the condition evaluates to true, a course-of-action is followed ie, a statement or set-of-statements is executed. If the condition is false, it does nothing : The syntax (general form) of the if statement is as shown. below : Af
print ("A has more than B has” print("Their difference is", (a-b)) 1.10.2. The if-else Conditional Statement y PADHAAIL COMPUTER SCIENCE WITH PYTHON — This form of if statement tests a condition and if the condition evaluates to true, it carries out statements indented below if and in case condition evaluates to false, it carries out statements indented below else. ‘The syntax (general form) of the if-else statement is as shown below : if
: statement [statements] else: statement [statements] { “expression 2S 0B of ale Re 7 | we | Body of if | For example, consider the following code fragments using if-else conditionals : if a >=: <———__ re colon (:) isin both: the if print(a, “is zero or a positive nunber") else: print(a, “is a negative number") 1.10.3 The if-elif Conditional Statement header as well a elie line The statements inif-block and else are indented Sometimes, you want to check a condition when control reaches else, i.e., condition test in the form of else if. To serve such conditions, Python provides if-elif and if-elif-else statements. The general form of these statements is : [GF
: Af
: and elif
= 160 : print("Batsman scored a century") elif runs >= 50: print("Batsman scored a fifty") else: print ("Batsman has neither scored a century nor fifty") if num<@: print(num, "is a negative number.") elif num==0 : print(num, "is equal to zero.") else: print(num, “is a positive number.) digit number. m nun = int(input("Enter a number (0..999) : ")) if num < 0: print( "Invalid entry. Valid range is @ to 999. elif num< 10: print("Single digit nunber is entered”) elif num< 100: print("Two digit number is entered") elif num <= 999: print(“Three digit number is entered") else: print ("Invalid entry. Valid range is @ to 999.") Sample runs of this program are given below : enter a nunber (0..999) : -3 Invalid entry. valid range is 0 to 999. Enter a number (0..999) : 4 Single digit number is entered ne, enter a number (0..999) : 100 Three digit number is entered paneer Enter a number (0..999) : 10 Two digit number is entered Enter a number (0..999) : 3000 Invalid entry. valid range is 0 to 999. aon, | D 1.3. Write a program that inputs an integer in range 0 - 999 and then prints ifthe integer entered is a 1/23 Ja oe1.10.5. Storing Con PADHAAI COMPUTER SCIENCE WITH PYTHON ~ xy 1.10.4 Nested if Statements Sometimes you may need to test additional conditions. For such situations, Python also supports nested-if form of if. A nested if is an if that has another if in its if's body or in elif’s body or in its else’s body. Consider the following example code using nested-if statements : x= int(input(“Enter First number :*)) y= int(input(“Enter second number :")) z= int(input("Enter third number :")) min = mid = max = None if x
999: print(“Invalid entry. Valid range is @ to 999.") else: if nun < 16: print(“Single digit nusber is entered”) else: if num< 168; print("Two digit number is entered”) else: print(“Three digit nunber is entered”) The sample run of this program is just the same as previous program. 1.11 LOOPING STATEMENTS Python provides too kinds of loops : for loop and while loop to represent counting loop and conditional loop respectively. 1.11.1. The for Loop The for loop of Python is designed to process the items of any sequence, such as alist or a string, one by one. The General Form of for loop The general form of for loop is as given below : for
in
: statements_to_repeat For example, consider the following loop : for element in [10, 15, 20, 25] : print(element +2, end='") ‘The above loop would give output as : RW 22 27 © The above-given for loop executes a sequence of statements for each of the elements of given sequence (10, 15, 20, 25]. © Tokeep the count, it uses a control variable (clement in above case) in that takes a different value on each iteration. Firstly value 10, then the next value of sequence, 15, then 20 and lastly 25.PADHAAI COMPUTER SCIENCE WITH PYTHON ~ yy The range( ) based for loop For number based lists, you can specify range) function to represent a list as in : for val in range(3, 18) : print(val) 16, 17] with which for loop will Inthe above loop, range(3, 18) will first generate a list [3, 4,5 work, You need not define loop variable (val above) beforehand in a for loop. As mentioned, a range() produces an integer number sequence. There are three ways to define a range , incrementing by 1 range(stop) Helements from @ — to stop-’ Helements from start to stop-1, incrementing by 1 range(start, stop) elements from start to stop-1, incrementing by step range(start, stop, step) © The start value is always part of the range. The stop value is never part of the range. The step shows the difference between two consecutive values in the range. © If start value is omitted, it supposed to be 0. Ifthe step is omitted, itis supposed to be 1. Consider some examples of range( ) as given below : range(7) 0,1, 2, 3,4, 5,6 range(S, 12) 5, 6,7, 8,9, 18, 12 range(5, 13, 2) 5,7,9,11 range(10, 4, -1) 10, 9, 8,7,6,5 | range(1@, 4) no value For example, the next program shows the cube of the numbers from 15 to 20 ; Write a program to print cubes of numbers in the range 15 to 20. for 4 inrange(15, 21 print("Cube of number", i, end=' *) print("is", i #3) Cube of number 15 is 3375 | Cube of number 16 is 4096 Cube of number 17 is 4913 |) Cube of number 18 is 5832 Cube of number 19 is 6859 Cube of number 20 is 8000 1.7 Write a program to print square root of every alternate number in the range 1 to 10. a for 4 in range(1, 10, 2) : Print( "square root of", 4, "is", (1 **0.5))PADHAAI | f ahd ee 25 1.11.2 The while Loop A while loop is a conditional loop that will repeat the instructions within itself as long as a conditional remains true (Boolean True or truth value true). The general form of Python while loop is : while
: ‘oop-body where the loop-body may contain a single statement or multiple statements or an empty statement (i.e, pass statement). The loop iterates while the logical Expression evaluates to true. When the expression becomes false, the program control passes to the line after the loop-body. ? 1.8 Write a program that multiplies two integer numbers without using the * operator, using repeated addition. Ad = int (input ("Enter First number n2 = int (input ("Enter second nuaber : product = @ count = na. while count >@ count = count - 1 product = product +2 print (“The product of", ni, “and”, n2, "is", product) Enter first nusber : 4 Enter second nusber : 5 ‘The product of 4 and 5 is 20 In general, the while loop is used when it is not possible to know in advance how many times the loop will be executed, but the termination condition is known. The while loop is an entry-controlled loop as it has a control over entry in the loop in the form of test condition. 1.12 JUMP STATEMENTS — break AND continue Python offers two jump statements ~ break and continue ~ to be used within loops to jump out of loop-iterations. The break Statement A break statement terminates the very loop it lies within. Execution resumes at the statement immediately following the body of the terminated statement.PADHAAIL COMPUTER SCIENCE WITH PYTHON while
+ for
in
. + if
; Gre skipped and next : " iteration bein Af
+ 4 continue : continue | statement 2 | i statement 2 statement 3 i; statenent 3 . statenent 4 statement 4 Trabove hops, contnoe wa awa Inte caren eaten anne loon ann ee Figure 1.7 The working of a continue statement,coopter 1 + PYTHON REVISION TOUR 1.13 MORE ON LOOPS There are two more things you need to know about loops the loop else clause and nested loops. 1.13.1. Loop else Statement Python loops have an optional else clause. Complete syntax of Python loops along with else clause is as given below : for
in
: while
in
| | statenene > ; iheop statenent_| |_statenent bo Dates 2 Salonen __ , { statenent > Statements. _, f statenent > ‘outside the loop statement: ‘outside the loo statement: statenent statenent Figure 1.8 Control flow in Python loops. Consider following example : for ain range (1,4): ifaB==0: break print ("Element is", end = print(a) else: print("énding loop after printing all elements of sequence"). PADHAAII 7 COMPUTER SCIENCE WITH PYTHON — The above will give the following output : ‘This nei printed because theese Element is 1 clause of given for loop executed when Elenent is 2 the for loop was terminating, normaly Element is 3 Ending loop after printing a11 elements of sequence. — If, in above code, you change the line ifa%B==0: with ifak2== Then the output will be : El i Sees TT Notice that for a = 2, the break got executed and loop terminated. Hence stone element got printed (or e™= 1) The else clause works identically in while 4% beak terminated the loop, the ele clause also did A Int execute, 80 no line after the pratng of elements. loop, i.e, executes if the test-condition goes {false and in case of break statement, the Joop-else clause is not executed. 1.13.2 Nested Loops A loop may contain another loop in its body. This form of a loop is called nested loop. But in a nested loop, the inner loop must terminate before the outer loop. ‘The following is an example of a nested loop : for iin range(1, 6) : for jinrange (1, 4): print("*", end='') print() In nested loops, a break statement will terminate the very loop it appears in. That is, if break statement is inside the inner loop then only the inner loop will terminate and outer loop will continue. If however, the break statement is in outer loop, the outer loop will terminate. Progress In Python 1.3 ‘This ‘PriP” session is aimed at revising various concepts you learnt in Class XI. 4 Please check the practical component-book — Progress in Computer : Science with Python and fill it there in.PriP 1.3 under Chapter 1 after practically doing it on the computer, 4 pertece,PADHAAI | 29 chapter 1 : PYTHON REVISION TOUR Let Us REVISE | ent Statements are the instructions given to the computer to perform any kind of action. Python statements can be on one of these types : empty statement, single statement and compound statement. ‘A.compound statement represents a group of statements executed os a unit. eae Every compound statement of Python has a header and an indented body below the header. Some exumples of compound statements are : functions, if statement, while statement etc. Python provides one selection statement if in many forms ° * The statements that allow a set of instructions to be performed repeatedly are iteration statements. Pyth loop. provides two looping constructs —for and while, Te for loop isa counting loop and while isa conditional ‘The while loop is an entry-controlled loop as it has a control over entry inthe loop In the form of test condition. Loops in Python can have else clause (00. The else clause of a loop is executed in the end of the loop only when loop terminates normally. ‘The break statement can terminate a loop immediately and the control passes over tothe statement following the statement containing break In nested loops, a break statement terminates the very loop it appears in. ‘The continue statement abandons the current iteration of the loop by skipping over the rest ofthe statements in the loop-body. It immediately transfers control to the beginning ofthe next iteration of the loop. Solved Problems Ln 1. What is the difference between a keyword and an identifier ? Solution. Keyword is a special word that has a special meaning and purpose. Keywords are reserved and are a few. For example, if, elif, else etc. are keywords. Identifier is the user-defined name given to a part of a program viz. variable, object, function ete. Identifiers are not reserved. These are defined by the user but they can have letters, digits and a symbol underscore. They must begin with either a letter or underscore. For instance, chk, chess, trial etc. are identifiers in Python. What are literals in Python ? How many types of literals are allowed in Python ? Solution. Literals mean constants i.,, the data items that never chan; un. Python allows five types of literal (String literals (iii) Boolean literals ge their value during a program (i) Numeric literals (io) Special Literal None (®) Literal Collections like tuples, lists etc. How many ways are there in Python to represent an integer literal 2 Solution. Python allows three types of integer literals : (@) Decimal (base 10) integer literals (Y) Octal (base 8) integer literals (©) Hexadecimal (base 16) integer literalsPADHAAIL COMPUTER SCIENCE WITH PYTHON ~ yy (@) Decimal Integer Literals. An integer literal consisting of a sequence of digits is taken to be decimal integer literal unless it begins with 0 (digit zero). For instance, 1234, 41, +97, -17 are decimal integer literals. () Octal Integer Literals. A sequence of digits starting with 0 (digit zero) is taken to be an octal integer. For instance, decimal integer 8 will be written as 010 as octal integer. (89 =10s) and decima| integer 12 will be written as 014 as octal integer (12) =145} (©) Hexadecimal Integer Literals. A sequence of digits preceded by Ox or OX is taken to be an hexadecimal integer. For instance, decimal 12 will be written as OXC as hexadecimal integer. Thus number 12 will be written either as 12 (as decimal), 014 (as octal) and OXC (as hexadecimal), 4. How many types of strings are supported in Python 2 Solution, Python allows two string types : (Single line Strings Strings that are terminated in single line (ii) Multiline Strings Strings storing multiple lines of text. 5. What is None literal in Python ? Solution. Python has one special literal called None. ‘The None literal is used to indicate something that has not yet been created. It is a legal empty value in Python. 6. The following code is not giving desired output. We want to input value as 20 and obtain output as 40. Could _you pinpoint the problem ? Nurber = input( "Enter Number" ) DoubleTheNumber = Number * 2 Print (DoubleTheNunber) Solution, The problem is that input( ) returns value as a string, so the input value 20 is returned as string ‘20’ and not as integer 20. So the output is 2020 in place of required output 40. Also Print is not legal statement of Python ; it should be print. 7. Why is following code giving errors ? name = "Rehman" print ("Greetings !!!") print("Hello", name) print("How do you do ?") j Solution. The problem with above code is inconsistent indentation. In Python, we cannot indent @ statement unless itis inside a suite and we can indent only as much as required. Thus, corrected code will be : name = "Rehman" print ("Greetings !!1*) print("Hello", name) print("How do you do ?"Chopter 1: PYTHON REVISION TOUR 10. u 12. 13. 4. What are data types ? What are Python's built-in core data types ? Solution. The real life data is of many types. So to represent various types of real-life data, programming languages provide ways and facilities to handle these, which are known as data types. Python's built-in core data types belong to : © Numbers (integer, floating-point, complex numbers, Booleans) © String wo List © Tuple = Dictionary Which data types of Python handle Numbers ? Solution. Python provides following data types of handle numbers (version 3.x) : (i) Plain integers (ii) Long integers (iii) Boolean (iv) Floating-point numbers (») Complex numbers Why is Boolean considered a subtype of integers ? Solution. Boolean values True and False internally map to integers 1 and 0. That is, internally True is considered equal to 1 and False as equal to 0 (zero). When 1 and 0 are converted to Boolean through bool( ) function, they return True and False. That is why Booleans are treated as a subtype of integers. What is the role of comments and indentation in a program ? Solution. Comments provide explanatory notes to the readers of the program. Compiler or interpreter ignores the comments but they are useful for specifying additional descriptive information regarding the code and logic of the program. Indentation makes the program more readable and presentable. Its main role is to highlight nesting of groups of control statements. What is a statement ? What is the significance of an empty statement ? Solution. A statement is an instruction given to the computer to perform any kind of action. Anempty statement is useful in situations where the code requires a statement but logic does not. To fill these two requirements simultaneously, empty statement is used. Python offers pass statement as an empty statement, If you are asked to label the Python loops as determinable or non-determinable, which Inbel would you give to which loop ? Justify your answer. Solution. The ‘for loop’ can be labelled as determinable loop as number of its iterations can be determined beforehand as the size of the sequence, it is operating upon. ‘The ‘while loop’ can be labelled as non-determinable loop, as its number of iterations cannot be determined beforehand. Its iterations depend upon the result of a test-condition, which cannot be determined beforehand. There are two types of else clauses in Python. What are these tvo types of else clauses ? Solution. The two types of Python else clauses are : (@) else in an if statement () else in a loop statement ‘The else clause of an if statement is executed when the condition of the if statement results into false The else clause of a loop is executed when the loop is terminating normally ic, when its test-condition has gone false for a while loop or when the for loop has executed for the last value in sequence.15. 16. 17, PADHAAIL COMPUTER SCIENCE WITH PYTHON — yy Writea program that asks the user to input number of seconds and then expresses it in terms of many minutes and seconds it contains. Solution, figet the nunber of seconds from the user nunseconds = input("Enter number of seconds") : ‘nunseconds_int = int(numseconds) #extract the nunber of minutes using integer division Nunminutes = numseconds_int//60 extract the number of seconds remaining since the last minute using the modulo emainingseconds = numseconds_int % 60 print(minutes:', nunminutes) print(‘seconds:', remainingseconds) Write a program that repeatedly asks from users some numbers until string ‘done’ is typed. The program should print the sum of all numbers entered, Solution, Unknown Number of Nunber's to Sum total =0 5 = input (‘Enter a number or “done”: ") while s !='done' : num = int(s) total = total + nun input ‘Enter a number or "done": *) print ‘The sum of entered numbers is', total) Write a program to print a square multiplication table as shown below : 2 ice cei Wate WE BRU er ase.) Bie A628. 40" aad ae: agen Bac 6 99 2 is ap ia 2 le e 8 12 16 2 om. 8. soe 5 10 15 2 2 0385s }6 2 1% 4 3 3% 2 48 5h |e ee a re ey 5% 68 Bis A024 SB 240. 2 pV 056 gg (et oe scat AROS ABS AAR SI Seas at i: Solution, for row in range(1, 10): for col in range(1, 16): prod = row * col if prod < 10: print(’ ', prod, else: print(prod,**, end=' *) yend=""') This adds a space if the number is Single digit print( )PADHAAI == Chapter 1: PYTHON REVISION TOUR 33 4 GLOSSARY J eae Block A group of consecutive stotements having same indentation level. Coercion Implicit Type Conversion. Constant A data item thot never changes its value during a program run. Explicit Type Conversion Forced doto type conversion by the user. ‘empty statement A statement thot appears in the code but does nothing. Identifier Nome given by user for @ port of the program. Implicit Type Conversion Automatic Internal Conversion of dato type (lower fo higher type) by Python. Keyword Reserved word having special mecning ond purpose. Lexical Unit Other name of token. erat Constant. operator Symbol/word thet Wiggers on action or operation Token The smallest individual unit in @ program. Type Casting Explicit Type Conversion. Variable Nomed stored location whose value can be manipulated during program run. Assignments A a a Type A : Short Answer Questions/Conceptual Questions 1. What are tokens in Python ? How many types of tokens are allowed in Python ? Exemplify your answer. 2. How are keywords different from identifiers ? 3. What are literals in Python ? How many types of literals are allowed in Python ? 4. Can nongraphic characters be used and processed in Python ? How ? Give examples to support your answer. 5. Out of the following, find those identifiers, which cannot be used for naming Variables or Functions ina Python program : [CBSE D 2016) Price*Qty, class, For, do, 4thCol, totally, Row31, _Amount 6. How are floating constants represented in Python ? Give examples to support your answer. 7. How are string-literals represented and implemented in Python ? 8, What are operators ? What is their function ? Give examples of some unary and binary operators. 9. What is an expression and a statement ? 10. What all components can a Python program contain ? 11, What are variables ? How are they important for a program ? 12. Describe the concepts of block or suite and body. What is indentation and how is it related to block and body 7 13, What are data types ? How are they important ? 14. How many integer types are supported by Python ? Name them. 15, What are immutable and mutable types ? List immutable and mutable types of Python. 16. What is the difference between implicit type conversion and explicit type conversion ?PADHAAIL COMPUTER SCIENCE wiry, , . : 1ON J one that cannot change after being created. Give three reasons 4 47, An immutable data type i immutable data. / 418, What is entry controlled loop ? Which loop is entry controlled loop in Python ? 49. Explain the use of the pass statement, Ilustrate it with an example. il red, Indicate the data type of 420, Below are seven segments of code, each with a part colour Pe ofeach oly part by choosing the correct type of data from the following type. re of str (a) int (R) float (@) bool (4) stt_@) function (fist of int) (Af temp < 32: (o) if n%2=20: print ("Freezing") print ("Freezing") (i) L= ['Hiya’, Zoya’, ‘Preet’] . (oi) L=inputline.split( ) prant(Lia) while L !=() + \ diy m=O print(L) for i in range (3) : =Uf:] 1M. append(i) print(M) (wii) converts the read into words L=[ ‘Hiya’, ‘Zoya’, ‘Preet! ] Go) LePtys, oye, Preet prin (.[6] +L} ) n= len (L) if'Donald in [1 : a]: print(L) Type B : Application Based Questions Bs 1. Fill in the missing lines of code in the following code. The code reads in a limit amount and a list prices and prints the largest price that is less than the limit, You can assume that all prices and the li are positive numbers. When a price 0 is entered the program terminates and prints the largest price is less than the limit. ‘Read the Limit Limit = float(input("Enter the Linit")) max_price = 0 # Read the next price % next_price = float(input("Enter 2 price or @ to stop:")) while next_price > @: ‘write your code here> Read the next price
if max_price > 0:
else :
2, Predict the outputs of the following programs : (@ count = while count < 10: print(‘Hello') count +21 i plChopter 1: PYTHON REVISION TOUR () x=10 @ = x=(1,2,3) y=® counter = @ while x > y: while counter < len(x): print(x, y) print (x[counter] *%) xex-1 for y in x: yeytl print(y *"* ') counter += 1 (© keepgoing = True x= 100 (&) for x in'lamp': while keepgoing: print(str.upper(x)) print(x) fl as © xe'one if x50: y="twot counter =@ keepgoing = False @ Ss while x < 50: print(x) (for xin [1,2,3,4,5]: while counter < Len(x): print(x{counter], y[counter]) counter +=1 (m) _x="apple, pear, peach” y=x.split(", ") print (x) for ziny: () forp inrange(1,10): print(z) print(p) (nm) x="apple, pear, peach, grapefruit’ (@) for zinrange( 500,500,100): y=x.split(, *) print(z) for ziny: ifz cin: ened print(str.lower(z)) yes else: for i in range(x-y* 2): Seto tupeer(e)) print("%", 4) () c=8 for x in range(1@): for y in range(5): cred print(c) 3. Find and write the output of the following python code : for Nane in [*Jayes', ‘Ramya’, ‘Taruna’, ‘Suraj’ print (Name) if Name[2] break else: print ("Findshed!") print (“Got it!*) [CBSE D 2015)PADHAAIL 4 COMPUTER SCIENCE With, PYTHON, oi 36 and what's the output ? ray times will the following for 100P execute an’ . mate vr eange(-17, 2 (ij) for 4 in range(1,3,4): for j in range (3): for San rangtieny int (* int(1, J) 5, Is the loop in the ote below infinite ? How do you know (CF sure) before you run it ? m3 nes while n< 10: men-1 ne2*n-m print(n, m) Type C : Programming Practice/Knowledge based Questions 4. Write a program to print one of the words negative, 99 ‘or positive, according to whether variable is sarthan zero, zero, or greater than zero, respectively. | 2. Write a program that returns True if the input number is an even number, False otherwise. | 3, Write a Python program that calculates and prints the number of seconds in a year. 44, Write a Python program that accepts two integers from the user and prints a message saying if fist | number is divisible by second number or if it is not. ber in a year in the range 2 to 365 and asks the fist day 5. Write a program that asks the user the day num! ‘Then the program should display the day on the of the year ~ Sunday ot Monday or Tuesday ete. day-number that has been input. 6 One foot equals 12 inches. Write a returns this length written in inches. Writ ‘eturns this value. Write a third function that accepts a number of inches an‘ Thee these three functions to write a program that asks the user for a number of corresponding number of inches. 7. Write a program that reads an integer N from the keyboard computes and displays the numbers from N to (2* N) if N is nonnegative. If N is a negative number, then it’s the numbers from (2* N) to N. The starting and ending points are included in the sum. Write a program that reads a date as an integer in the format MMDDYYYY. The program will all # function that prints print out the date in the format
,
You might also like
ACKNOWLEDGEMENT
PDF
No ratings yet
ACKNOWLEDGEMENT
19 pages
P5 Library P5
PDF
No ratings yet
P5 Library P5
22 pages
Chemistry Practical - 18 Class-12
PDF
No ratings yet
Chemistry Practical - 18 Class-12
4 pages
Detection of PH
PDF
No ratings yet
Detection of PH
2 pages
Results
PDF
No ratings yet
Results
1 page
Chemicals Required
PDF
No ratings yet
Chemicals Required
1 page
Apparatus Required
PDF
No ratings yet
Apparatus Required
1 page
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (643)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2289)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (233)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (836)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4.5/5 (1856)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (298)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (943)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (144)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brené Brown
4/5 (1175)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (629)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M.L. Stedman
4.5/5 (815)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1267)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (903)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (919)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4.5/5 (4103)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (244)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4.5/5 (1139)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2546)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (2885)
Little Women
From Everand
Little Women
Louisa May Alcott
4.5/5 (2369)