What is meant by token ? Name the tokens available in Python.
Answer
The smallest individual unit in a program is known as a Token.
Python has the following tokens:
(i) Keywords
(ii) Identifiers
(iii) Literals
(iv) Operators
(v) Punctuators
What are keywords ? Can keywords be used as identifiers ?
Answer
A keyword is a word having special meaning reserved by programming language. These are reserved for special purpose and must not be used as normal identifier names.
What is an identifier ? What are the identifier forming rules of Python ?
Answer
Identifiers are fundamental building blocks of a program and are used as the general terminology for the names given to different parts of the program viz. variables, objects, classes, functions, lists, dictionaries etc.
Identifier forming rules of Python are as follows:
- An identifier is an arbitrarily long sequence of letters and digits.
- The first character must be a letter, the underscore counts as a letter.
- Upper and lower-case letters are different. All characters are significant.
- The digits 0 through 9 can be part of the identifier except for the first character.
- Identifiers are unlimited in length. Case is significant i.e., Python is case sensitive as it treats upper and lower-case characters differently.
- An identifier must not be a keyword of Python.
- An identifier cannot contain any special character except for underscore.
Is Python case sensitive ? What is meant by the term 'case sensitive' ?
Answer
Yes, Python is case sensitive as it treats upper and lower-case characters differently.
Case sensitive means that the language treats uppercase and lowercase letters as distinct.
Which of the following are valid identifiers and why/why not :
Data_rec, _data, 1 data, data1, my.file, elif, switch, lambda, break ?
Answer
Valid Identifiers:
- Data_rec – Identifiers can contain letters and underscores.
- _data – Identifiers can begin with an underscore.
- data1 – Identifiers can contain digits, but they cannot start with a digit.
Invalid Identifiers:
- 1 data – Identifiers cannot begin with a digit and cannot contain spaces.
- my.file – Identifiers cannot contain special characters like dot (.).
- elif –
elifis a Python keyword and cannot be used as an identifier. - switch –
switchis a Python keyword and cannot be used as an identifier. - lambda –
lambdais a Python keyword and cannot be used as an identifier. - break –
breakis a Python keyword and cannot be used as an identifier.
What are literals ? How many types of literals are available in Python ?
Answer
Literals (often refereed to as constant-Values) are data items that have a fixed value.
Python allows several kinds of literals:
- String literals
- Numeric literals
- Boolean literals
- Special literal None
- Literal collections
How many types of integer literals are allowed in Python ? How are they written ?
Answer
Python allows three types of integer literals:
- 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).
- Octal Integer Literals — A sequence of digits starting with 0o (digit zero followed by letter o) is taken to be an octal integer.
- Hexadecimal Integer Literals — A sequence of digits preceded by 0x or 0X is taken to be an hexadecimal integer.
Why are characters , ', " and tab typed using escape sequences ?
Answer
The characters , ', " and tab are typed using escape sequences because they have special meanings and special purposes in Python.
Which escape sequences represent the newline character and backspace character ? An escape sequence represents how many characters ?
Answer
The escape sequence \n represents the newline character, and \b represents the backspace character.
An escape sequence represents one character.
What are string-literals in Python ? How many ways, can you create String literals in Python ? Are there any differences in them ?
Answer
A string literal is a sequence of characters surrounded by quotes.
In Python, one can form string literals by enclosing text in both forms of quotes - single quotes or double quotes.
There is no difference in functionality between single quotes and double quotes; both work in the same way to create string literals.
What is meant by a floating-point literal in Python ? How many ways can a floating literal be represented into ?
Answer
A floating-point literal is a number that includes a fractional part. These numbers can be written in two forms:
Fractional form
Exponent form
Write the following real constants into exponent form : 23.197, 7.214, 0.00005, 0.319.
Answer
The following real constants can be written in exponent form as:
- 23.197 = 2.3197 x 101 = 2.3197E1
- 7.214 = 7.214 x 100 = 7.214E0
- 0.00005 = 5.0 x 10-5 = 5.0E-5
- 0.319 = 3.19 x 10-1 = 3.19E-1
Write the following real constants into fractional form : 0.13E04, 0.417E-04, 0.4E-5, .12E02, 12.E02.
Answer
The following real constants can be written in fractional form as:
- 0.13E04 = 1300
- 0.417E-04 = 0.0000417
- 0.4E-5 = 0.000004
- .12E02 = 12
- 12.E02 = 1200
What are the two Boolean literals in Python ?
Answer
The two Boolean literals in Python are True (Boolean true) and False (Boolean false).
Name some built-in literals of Python.
Answer
Some built-in literals in Python include:
- Numeric Literals
- String Literals
- Boolean Literals
- Special Literal None
Out of the following literals, determine their type whether decimal/octal/hexadecimal integer literal or a floating point literal in fractional or exponent form or string literal or other ?
123, 0.o124, 0xABC, 'abc', "ABC", 12.34, 0.3E-01, '''ftghjkjl''', None, True, False
Answer
The type for each of the given literals are as follows:
- 123 — Decimal Integer Literal
- 0.o124 — Invalid literal (should be 0o124 for octal)
- 0xABC — Hexadecimal Integer Literal
- 'abc' — String Literal
- "ABC" — String Literal
- 12.34 — Floating Point Literal
- 0.3E-01 — Floating Point Literal
- '''ftghjkjl''' — String Literal
- None — Special Literal
- True — Boolean Literal
- False — Boolean Literal
What kind of program elements are the following ?
'a', 4.38925, "a", "main" ?
Answer
The following program elements are classified as:
- 'a' — String Literal
- 4.38925 — Floating Point Literal
- "a" — String Literal
- "main" — String Literal
What will var1 and var2 store with statements : var1 = 2,121E2 and var2 = 0.2,121E2 ? What are the types of values stored in var1 and var2 ?
Answer
var1 = 2,121E2
This statement contains a comma, which is interpreted as a tuple separator. Therefore, var1 will store the tuple (2, 12100).
var2 = 0.2,121E2
The comma indicates that var2 will store a tuple. The value 0.2 is the first element, and 121E2 evaluates to 12100. Thus, var2 will store (0.2, 12100).
The types of values stored in both var1 and var2 are tuple.
What is an expression in Python ?
Answer
An expression is any legal combination of symbols that represents a value.
What is a statement in Python ? How is a statement different from expression ?
Answer
A statement is a programming instruction that does something i.e., some action takes place.
While an expression represents a value or a computation, a statement is a programming instruction that performs an action, meaning some action takes place. While an expression is evaluated, a statement is executed, which also indicates that some action occurs. Additionally, it is not necessary for a statement to result in a value; it may or may not yield a result.
What is a comment ? In how many ways can you create comments in Python ?
Answer
Comments are the additional readable information, which is read by the programmers but ignored by Python interpreter.
In Python, comments can be created in two ways:
Single-Line Comments
Multi-Line Comments
How would you create multi-line comment in Python ?
Answer
In Python, a multi-line comment can be created using triple quotes. We can use either triple single quotes (''') or triple double quotes (""").
What is the difference between full-line comment and inline comment ?
Answer
| Full-line comment | In-line comment |
|---|---|
| A full-line comment occupies an entire line and begins with the hash symbol (#). | An inline comment is placed on the same line as a statement or expression, following the code. |
| It is used to explain or document a specific section of code and is often placed above the code block it refers to. | It is typically used for brief explanations or clarifications about that specific line of code. |
| For example : # This function calculates the square of a number def square(x): return x ** 2 | For example : result = square(5) # Calculate the square of 5 |
What is a block or suite in Python ? How is indentation related to it ?
Answer
A group of statements which are part of another statement or a function are called block or code-block or suite in Python.
Python uses indentation to create blocks of code. Statements at same indentation level are part of same block/suite.
What is a variable ?
Answer
Named labels, whose values can be used and processed during program run, are called variables.
Why is a variable called symbolic variable ?
Answer
Variables, called as symbolic variables, serve the purpose. They are called symbolic variables because these are named labels.
Create variables for the following:
(i) to hold a train number
(ii) to hold the name of a subject
(iii) to hold balance amount in a bank account
(iv) to hold a phone number
Answer
(i) train_number = 12345
(ii) subject_name = "Python"
(iii) balance_amount = 1500.75
(iv) phone_number = 9876543210
What do you mean by dynamic typing of a variable ? What is the caution you must take care of ?
Answer
A variable pointing to a value of a certain type, can be made to point to a value/object of different type. This is called Dynamic Typing.
Although Python allows changing the types of a variable, the programmer is responsible for ensuring that the correct types are used for specific operations to avoid errors.
What happens when you try to access the value of an undefined variable ?
Answer
When we try to access the value of an undefined variable in Python, a NameError is raised. This error indicates that the variable has not been defined or assigned a value before it is being accessed.
What is wrong with the following statement ?
Number = input("Number")
Sqr = Number*Number
Answer
The issue with the statement is that the input() function in Python always returns a value as a string. Consequently, when we attempt to perform the multiplication Number * Number, it results in string concatenation rather than numeric multiplication.
The corrected code is:
Number = int(input("Number: "))
Sqr = Number * NumberWrite Python code to obtain the balance amount.
Answer
balance_amount = float(input("Enter the balance amount: "))
print("The balance amount is:", balance_amount)Enter the balance amount: 123.3
The balance amount is: 123.3
Write code to obtain fee amount and then calculate fee hike as 10% of fees (i.e., fees x 0.10).
Answer
fee_amount = float(input("Enter the fee amount: "))
fee_hike = fee_amount * 0.10
print("The fee hike is:", fee_hike)Enter the fee amount: 1000
The fee hike is: 100.0
Special meaning words of Pythons, fixed for specific functionality are called .......... .
- Identifiers
- functions
- Keywords
- literals
Answer
Keywords
Reason — A keyword is a word having special meaning reserved by programming language.
Names given to different parts of a Python program are .......... .
- Identifiers
- functions
- Keywords
- literals
Answer
Identifiers
Reason — Identifiers are fundamental building blocks of a program and are used as the general terminology for the names give to different parts of the program viz. variables, objects, classes, functions, lists etc.
Data items having fixed value are called .......... .
- Identifiers
- functions
- Keywords
- literals
Answer
literals
Reason — Literals (often referred to as constant-Values) are data items that have a fixed value.
Which of the following is/are correct ways of creating strings ?
- name = Jiya
- name = 'Jiya'
- name = "Jiya"
- name = (Jiya)
Answer
name = 'Jiya', name = "Jiya"
Reason — A string is a sequence of characters surrounded by quotes (single or double or triple quotes). Therefore, both name = 'Jiya', name = "Jiya" are correct.
Which of the following are keyword(s) ?
- name
- input
Answer
print, input
Reason — In Python, print and input are keywords because they are built-in functions used for output and input operations, respectively.
Which of the following are valid identifiers ?
- my name
- _myname
- myname
- my-name
Answer
_myname, myname
Reason — Valid identifiers in Python must start with a letter (a-z or A-Z) or an underscore (_), followed by letters, digits, or underscores. Therefore, _myname and myname are valid identifiers.
Which of the following are literals ?
- myname
- "Radha"
- 24.5
- 24A
Answer
"Radha", 24.5
Reason — Literals are fixed values assigned directly to a variable in Python. "Radha" is a string literal, and 24.5 is a floating-point literal.
Escape sequences are treated as .......... .
- strings
- characters
- integers
- none of these
Answer
characters
Reason — An escape sequence represents a single character in Python.
Which of the following is an escape sequence for a tab character ?
- \a
- \t
- \n
- \b
Answer
\t
Reason — \t is the escape sequence for a tab character in Python.
Which of the following is an escape sequence for a newline character ?
- \a
- \t
- \n
- \b
Answer
\n
Reason — \n is the escape sequence for a newline character in Python.
Which of the following is not a legal integer type value in Python ?
- Decimal
- Octal
- Hexadecimal
- Roman
Answer
Roman
Reason — In Python, integers can be represented in decimal, octal, and hexadecimal number systems. However, Roman numerals are not a legal integer type in Python.
Which of the following symbols are not legal in an octal value ?
- 7
- 8
- 9
- 0
Answer
8, 9
Reason — Octal values use digits from 0 to 7. Therefore, 8 and 9 are not legal in an octal number system.
Value 17.25 is equivalent to
- 0.1725E-2
- 0.1725E+2
- 1725E2
- 0.1725E2
Answer
0.1725E+2, 0.1725E2
Reason — The value 17.25 can be represented in exponent form as 0.1725E+2 or 0.1725E2. Both forms indicate that the decimal point is moved two places to the right, resulting in 17.25.
Value 0.000615 is equivalent to
- 615E3
- 615E-3
- 0.615E3
- 0.615E-3
Answer
0.615E-3
Reason — The value 0.000615 is equivalent to 0.615E-3. This notation indicates that the decimal point is moved three places to the left, yielding 0.000615.
Which of the following is/are expression(s) ?
- a+b-5
- a
- -5
- b-5
Answer
a+b-5, b-5
Reason — An expression is any legal combination of symbols that represents a value. Both a+b-5, b-5 are expressions because they involve variables and arithmetic operations.
The lines beginning with a certain character, and which are ignored by a compiler and not executed, are called ..........
- operators
- operands
- functions
- comments
Answer
comments
Reason — Comments are additional readable information, which is read by the programmers but ignored by Python interpreter. They begin with symbol # and end with the end of physical line.
Which of the following can be used to create comments ?
- //
- #
- '''
- ''' . . . '''
Answer
#, ''' . . . '''
Reason — In Python, comments can be created using the # symbol for single-line comments. Multi-line comments can be created using triple quotes (''' ... ''' or """ ... """).
Which of the following functions print the output to the console ?
- Output()
- Print()
- Echo()
- print()
Answer
print()
Reason — In Python, the function print() is used to output data to the console.
Select the reserved keyword in Python.
- else
- import
- all of these
Answer
all of these
Reason — In Python, else, import, and print are all reserved keywords. Reserved keywords are predefined by the language and cannot be used as identifiers for variables or functions.
The input() returns the value as .......... type.
- integer
- string
- floating point
- none of these
Answer
string
Reason — The input() function in Python always returns the value as a string.
To convert the read value through input() into integer type, ..........() is used.
- floating
- float
- int
- integer
Answer
int
Reason — The int() function is used to convert a value into an integer type in Python. The input() function returns a string type, so int() is needed to convert that string into an integer.
To convert the read value through input() into a floating point number, ..........() is used.
- floating
- float
- int
- integer
Answer
float
Reason — The float() function is used to convert a value into a floating point number in Python. The input() function returns a string type, so float() is needed to convert that string into a floating point number.
To print a line a text without ending it with a newline, .......... argument is used with print().
- sep
- newline
- end
- next
Answer
end
Reason — The end argument is used with the print() function specifies the character or string to print at the end of the output.
The default separator character of print() is ..........
- tab
- space
- newline
- dot
Answer
space
Reason — The default separator character of the print() function is a space. It is used to separate multiple arguments when printing them.
To give a different separator with print() .......... argument is used.
- sep
- separator
- end
- tab
Answer
sep
Reason — The sep argument is used with the print() function to specify a different separator between multiple arguments.
A keyword is a reserved word carrying special meaning and purpose.
Identifiers are the user defined names for different parts of a program.
Literals are the fixed values.
Operators are the symbols that trigger some computation or action.
An expression is a legal combination of symbols that represents a value.
Non-executable, additional lines added to a program, are known as comments.
In Python, the comments begin with # character.
Python is a case sensitive language.
The print() function prints the value of a variable/expression.
The input() function gets the input from the user.
The input() function returns the read value as of string type.
To convert an input()'s value in integer type, int() function is used.
To convert an input()'s value in floating-point type, float() function is used.
Strings can be created with single quotes, double quotes and triple quotes.
Keywords can be used as identifier names.
Answer
False
Reason — Keywords are the words that convey a special meaning to the language compiler/interpreter. These are reserved for special purpose and must not be used as normal identifier names.
The identifiers in Python can begin with an underscore.
Answer
True
Reason — Valid identifiers in Python must start with a letter (a-z or A-Z) or an underscore (_), followed by letters, digits, or underscores.
0128 is a legal literal value in Python.
Answer
False
Reason — 0128 is not a legal literal value in Python because it starts with a leading zero and contains a digit (8) that is not valid in an octal (base 8) representation.
0x12EFG is a legal literal value in Python.
Answer
False
Reason — 0x12EFG is not a legal literal value in Python because it contains non-hexadecimal characters (G). Hexadecimal literals can only include the digits 0-9 and the letters A-F (or a-f).
0123 is a legal literal value in Python.
Answer
True
Reason — 0123 is a legal literal in Python as an octal number.
Variables once assigned a value can be given any other value.
Answer
True
Reason — Variables in Python are mutable, meaning once assigned a value, they can be reassigned any other value at any time.
Variables are created when they are first assigned their value.
Answer
True
Reason — In Python, variables are created at the moment they are first assigned a value, allowing for dynamic variable declaration.
Python variables support dynamic typing.
Answer
True
Reason — Python supports dynamic typing, allowing a variable that holds a value of one type to be reassigned to a value of a different type during execution.
You can rename a keyword.
Answer
False
Reason — We cannot rename a keyword in Python because keywords are reserved words with predefined meanings.
String values in Python can be single line strings, and multi-line strings.
Answer
True
Reason — String values in Python can be single-line strings enclosed in single or double quotes, and multi-line strings enclosed in triple quotes.
A variable can contain values of different types at different times.
Answer
True
Reason — In Python, a variable can hold values of different types at different times due to dynamic typing.
Expressions contain values/variables along with operators.
Answer
True
Reason — Expressions in Python consist of values, variables, and operators, which are combined to perform calculations, resulting in a value.
Assertion (A): Python provides these tokens: keywords, identifiers, literals, punctuators, operators and comments.
Reasoning (R): A token is the smallest individual unit in a program.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
Python provides tokens such as keywords, identifiers, literals, punctuators, operators, and comments. The smallest individual unit in a program is known as a Token or a lexical unit.
Assertion (A): A Python program can contain executable and non-executable items.
Reasoning (R): The comments are the non-executable parts of a program.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
A Python program can contain both executable code and non-executable items (like comments). Comments are a form of non-executable parts, providing additional readable information to clarify the source code, which is read by the programmers but ignored by Python interpreter.
Assertion (A): In Python, a variable can hold values of different types at different times.
Reasoning (R): A variable's data type once assigned, remains fixed throughout the program.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
A is true but R is false.
Explanation
Python supports dynamic typing, allowing a variable that holds a value of one type to be reassigned to a value of a different type during execution. A variable's data type is not fixed; it can change when the variable is reassigned to a different value of another type.
Assertion (A): In Python, blocks are represented through indentation.
Reasoning (R): Blocks in Python, are the compound statements.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true but R is not the correct explanation of A.
Explanation
In Python, blocks of code are represented through indentation, which defines the scope of loops, functions, classes, etc. Blocks in Python, are the compound statements because they can contain multiple statements that are executed together.
Assertion (A): Python supports dynamic typing of variables.
Reasoning (R): A variable can hold values of different types at different times, in a program.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
Python supports dynamic typing of variables, allowing a variable that holds a value of one type to be reassigned to a value of a different type during execution.
What are tokens in Python ? How many types of tokens are allowed in Python ? Examplify your answer.
Answer
The smallest individual unit in a program is known as a Token. Python has following tokens:
- Keywords — Examples are import, for, in, while, etc.
- Identifiers — Examples are MyFile, _DS, DATE_9_7_77, etc.
- Literals — Examples are "abc", 5, 28.5, etc.
- Operators — Examples are +, -, >, or, etc.
- Punctuators — ' " # () etc.
How are keywords different from identifiers ?
Answer
Keywords are reserved words carrying special meaning and purpose to the language compiler/interpreter. For example, if, elif, etc. are keywords. Identifiers are user defined names for different parts of the program like variables, objects, classes, functions, etc. Identifiers are not reserved. They can have letters, digits and underscore. They must begin with either a letter or underscore. For example, _chk, chess, trail, etc.
What are literals in Python ? How many types of literals are allowed in Python ?
Answer
Literals are data items that have a fixed value. The different types of literals allowed in Python are:
- String literals
- Numeric literals
- Boolean literals
- Special literal None
- Literal collections
Can nongraphic characters be used in Python ? How ? Give examples to support your answer.
Answer
Yes, nongraphic characters can be used in Python with the help of escape sequences. For example, backspace is represented as \b, tab is represented as \t, carriage return is represented as \r.
How are floating constants represented in Python ? Give examples to support your answer.
Answer
Floating constants are represented in Python in two forms — Fractional Form and Exponent form. Examples:
- Fractional Form — 2.0, 17.5, -13.0, -0.00625
- Exponent form — 152E05, 1.52E07, 0.152E08, -0.172E-3
How are string-literals represented and implemented in Python ?
Answer
A string-literal is represented as a sequence of characters surrounded by quotes (single, double or triple quotes). String-literals in Python are implemented using Unicode.
Which of these is not a legal numeric type in Python ? (a) int (b) float (c) decimal.
Answer
decimal is not a legal numeric type in Python.
Which argument of print( ) would you set for:
(i) changing the default separator (space) ?
(ii) printing the following line in current line ?
Answer
(i) sep
(ii) end
What are operators ? What is their function ? Give examples of some unary and binary operators.
Answer
Operators are tokens that trigger some computation/action when applied to variables and other objects in an expression. Unary plus (+), Unary minus (-), Bitwise complement (~), Logical negation (not) are a few examples of unary operators. Examples of binary operators are Addition (+), Subtraction (-), Multiplication (*), Division (/).
What is an expression and a statement ?
Answer
An expression is any legal combination of symbols that represents a value. For example, 2.9, a + 5, (3 + 5) / 4.
A statement is a programming instruction that does something i.e. some action takes place. For example:
print("Hello")
a = 15
b = a - 10
What all components can a Python program contain ?
Answer
A Python program can contain various components like expressions, statements, comments, functions, blocks and indentation.
What do you understand by block/code block/suite in Python ?
Answer
A block/code block/suite is a group of statements that are part of another statement. For example:
if b > 5:
print("Value of 'b' is less than 5.")
print("Thank you.")What is the role of indentation in Python ?
Answer
Python uses indentation to create blocks of code. Statements at same indentation level are part of same block/suite.
What are variables ? How are they important for a program ?
Answer
Variables are named labels whose values can be used and processed during program run. Variables are important for a program because they enable a program to process different sets of data.
What do you understand by undefined variable in Python ?
Answer
In Python, a variable is not created until some value is assigned to it. A variable is created when a value is assigned to it for the first time. If we try to use a variable before assigning a value to it then it will result in an undefined variable. For example:
print(x) #This statement will cause an error for undefined variable x
x = 20
print(x)The first line of the above code snippet will cause an undefined variable error as we are trying to use x before assigning a value to it.
What is Dynamic Typing feature of Python ?
Answer
A variable pointing to a value of a certain type can be made to point to a value/object of different type.This is called Dynamic Typing. For example:
x = 10
print(x)
x = "Hello World"
print(x)What would the following code do : X = Y = 7 ?
Answer
It will assign a value of 7 to the variables X and Y.
What is the error in following code : X, Y = 7 ?
Answer
The error in the above code is that we have mentioned two variables X, Y as Lvalues but only give a single numeric literal 7 as the Rvalue. We need to specify one more value like this to correct the error:
X, Y = 7, 8Following variable definition is creating problem X = 0281, find reasons.
Answer
Python doesn't allow decimal numbers to have leading zeros. That is the reason why this line is creating problem.
"Comments are useful and easy way to enhance readability and understandability of a program." Elaborate with examples.
Answer
Comments can be used to explain the purpose of the program, document the logic of a piece of code, describe the behaviour of a program, etc. This enhances the readability and understandability of a program. For example:
# This program shows a program's components
# Definition of function SeeYou() follows
def SeeYou():
print("Time to say Good Bye!!")
# Main program-code follows now
a = 15
b = a - 10
print (a + 3)
if b > 5: # colon means it's a block
print("Value of 'a' was more than 15 initially.")
else:
print("Value of 'a' was 15 or less initially.")
SeeYou() # calling above defined function SeeYou()From the following, find out which assignment statement will produce an error. State reason(s) too.
(a) x = 55
(b) y = 037
(c) z = 0o98
(d) 56thnumber = 3300
(e) length = 450.17
(f) !Taylor = 'Instant'
(g) this variable = 87.E02
(h) float = .17E - 03
(i) FLOAT = 0.17E - 03
Answer
- y = 037 (option b) will give an error as decimal integer literal cannot start with a 0.
- z = 0o98 (option c) will give an error as 0o98 is an octal integer literal due to the 0o prefix and 8 & 9 are invalid digits in an octal number.
- 56thnumber = 3300 (option d) will give an error as 56thnumber is an invalid identifier because it starts with a digit.
- !Taylor = 'Instant' (option f) will give an error as !Taylor is an invalid identifier because it contains the special character !.
- this variable = 87.E02 (option g) will give an error due to the space present between this and variable. Identifiers cannot contain any space.
- float = .17E - 03 (option h) will give an error due to the spaces present in exponent part (E - 03). A very important point to note here is that float is NOT a KEYWORD in Python. The statement float = .17E-03 will execute successfully without any errors in Python.
- FLOAT = 0.17E - 03 (option i) will give an error due to the spaces present in exponent part (E - 03).
How will Python evaluate the following expression ?
(i) 20 + 30 * 40
Answer
    20 + 30 * 40
⇒ 20 + 1200
⇒ 1220
(ii) 20 - 30 + 40
Answer
    20 - 30 + 40
⇒ -10 + 40
⇒ 30
(iii) (20 + 30) * 40
Answer
    (20 + 30) * 40
⇒ 50 * 40
⇒ 2000
(iv) 15.0 / 4 + (8 + 3.0)
Answer
    15.0 / 4 + (8 + 3.0)
⇒ 15.0 / 4 + 11.0
⇒ 3.75 + 11.0
⇒ 14.75
Find out the error(s) in following code fragments:
(i)
temperature = 90
print temperatureAnswer
The call to print function is missing parenthesis. The correct way to call print function is this:print(temperature)
(ii)
a = 30
b=a+b
print (a And b)Answer
There are two errors in this code fragment:
- In the statement
b=a+bvariable b is undefined. - In the statement
print (a And b), And should be written as and.
(iii)
a, b, c = 2, 8, 9
print (a, b, c)
c, b, a = a, b, c
print (a ; b ; c)Answer
In the statement print (a ; b ; c) use of semicolon will give error. In place of semicolon, we must use comma like this print (a, b, c)
(iv)
X = 24
4 = XAnswer
The statement 4 = X is incorrect as 4 cannot be a Lvalue. It is a Rvalue.
(v)
print("X ="X)Answer
There are two errors in this code fragment:
- Variable X is undefined
- "X =" and X should be separated by a comma like this
print("X =", X)
(vi)
else = 21 - 5Answer
else is a keyword in Python so it can't be used as a variable name.
What will be the output produced by following code fragment (s) ?
(i)
X = 10
X = X + 10
X = X - 5
print (X)
X, Y = X - 2, 22
print (X, Y) Output
15
13 22
Explanation
X = 10⇒ assigns an initial value of 10 to X.X = X + 10⇒ X = 10 + 10 = 20. So value of X is now 20.X = X - 5⇒ X = 20 - 5 = 15. X is now 15.print (X)⇒ print the value of X which is 15.X, Y = X - 2, 22⇒ X, Y = 13, 22.print (X, Y)⇒ prints the value of X which is 13 and Y which is 22.
(ii)
first = 2
second = 3
third = first * second
print (first, second, third)
first = first + second + third
third = second * first
print (first, second, third)Output
2 3 6
11 3 33
Explanation
first = 2⇒ assigns an initial value of 2 to first.second = 3⇒ assigns an initial value of 3 to second.third = first * second⇒ third = 2 * 3 = 6. So variable third is initialized with a value of 6.print (first, second, third)⇒ prints the value of first, second, third as 2, 3 and 6 respectively.first = first + second + third⇒ first = 2 + 3 + 6 = 11third = second * first⇒ third = 3 * 11 = 33print (first, second, third)⇒ prints the value of first, second, third as 11, 3 and 33 respectively.
(iii)
side = int(input('side') ) #side given as 7
area = side * side
print (side, area)Output
side7
7 49
Explanation
side = int(input('side') )⇒ This statements asks the user to enter the side. We enter 7 as the value of side.area = side * side⇒ area = 7 * 7 = 49.print (side, area)⇒ prints the value of side and area as 7 and 49 respectively.
What is the problem with the following code fragments ?
(i)
a = 3
print(a)
b = 4
print(b)
s = a + b
print(s)Answer
The problem with the above code is inconsistent indentation. The statements print(a), print(b), print(s) are indented but they are not inside a suite. In Python, we cannot indent a statement unless it is inside a suite and we can indent only as much is required.
(ii)
name = "Prejith"
age = 26
print ("Your name & age are ", name + age)Answer
In the print statement we are trying to add name which is a string to age which is an integer. This is an invalid operation in Python.
(iii)
a = 3
s = a + 10
a = "New"
q = a / 10Answer
The statement a = "New" converts a to string type from numeric type due to dynamic typing. The statement q = a / 10 is trying to divide a string with a number which is an invalid operation in Python.
Predict the output:
(a)
x = 40
y = x + 1
x = 20, y + x
print (x, y)Output
(20, 81) 41
Explanation
x = 40⇒ assigns an initial value of 40 to x.y = x + 1⇒ y = 40 + 1 = 41. So y becomes 41.x = 20, y + x⇒ x = 20, 41 + 40 ⇒ x = 20, 81. This makes x a Tuple of 2 elements (20, 81).print (x, y)⇒ prints the tuple x and the integer variable y as (20, 81) and 41 respectively.
(b)
x, y = 20, 60
y, x, y = x, y - 10, x + 10
print (x, y)Output
50 30
Explanation
x, y = 20, 60⇒ assigns an initial value of 20 to x and 60 to y.y, x, y = x, y - 10, x + 10
⇒ y, x, y = 20, 60 - 10, 20 + 10
⇒ y, x, y = 20, 50, 30
First RHS value 20 is assigned to first LHS variable y. After that second RHS value 50 is assigned to second LHS variable x. Finally third RHS value 30 is assigned to third LHS variable which is again y. After this assignment, x becomes 50 and y becomes 30.- print (x, y) ⇒ prints the value of x and y as 50 and 30 respectively.
(c)
a, b = 12, 13
c, b = a*2, a/2
print (a, b, c)Output
12 6.0 24
Explanation
a, b = 12, 13⇒ assigns an initial value of 12 to a and 13 to b.c, b = a*2, a/2⇒ c, b = 12*2, 12/2 ⇒ c, b = 24, 6.0. So c has a value of 24 and b has a value of 6.0.print (a, b, c)⇒ prints the value of a, b, c as 12, 6.0 and 24 respectively.
(d)
a, b = 12, 13
print (print(a + b))Output
25
None
Explanation
a, b = 12, 13⇒ assigns an initial value of 12 to a and 13 to b.print (print(a + b))⇒ First print(a + b) function is called which prints 25. After that, the outer print statement prints the value returned by print(a + b) function call. As print function does not return any value so outer print function prints None.
Predict the output
a, b, c = 10, 20, 30
p, q, r = c - 5, a + 3, b - 4
print ('a, b, c :', a, b, c, end = '')
print ('p, q, r :', p, q, r)Output
a, b, c : 10 20 30p, q, r : 25 13 16
Explanation
a, b, c = 10, 20, 30⇒ assigns initial value of 10 to a, 20 to b and 30 to c.p, q, r = c - 5, a + 3, b - 4
⇒ p, q, r = 30 - 5, 10 + 3, 20 - 4
⇒ p, q, r = 25, 13, 16.
So p is 25, q is 13 and r is 16.print ('a, b, c :', a, b, c, end = '')⇒ This statement printsa, b, c : 10 20 30. As we have given end = '' so output of next print statement will start in the same line.print ('p, q, r :', p, q, r)⇒ This statement printsp, q, r : 25 13 16
Find the errors in following code fragment
(a)
y = x + 5
print (x, Y)Answer
There are two errors in this code fragment:
- x is undefined in the statement
y = x + 5 - Y is undefined in the statement
print (x, Y). As Python is case-sensitive hence y and Y will be treated as two different variables.
(b)
print (x = y = 5)Answer
Python doesn't allow assignment of variables while they are getting printed.
(c)
a = input("value")
b = a/2
print (a, b)Answer
The input( ) function always returns a value of String type so variable a is a string. This statement b = a/2 is trying to divide a string with an integer which is invalid operation in Python.
Find the errors in following code fragment : (The input entered is XI)
c = int (input ( "Enter your class") )
print ("Your class is", c)Answer
The input value XI is not int type compatible.
Consider the following code :
name = input ("What is your name?")
print ('Hi', name, ',')
print ("How are you doing?")was intended to print output as
Hi <name>, How are you doing ?
But it is printing the output as :
Hi <name>,
How are you doing?
What could be the problem ? Can you suggest the solution for the same ?
Answer
The print() function appends a newline character at the end of the line unless we give our own end argument. Due to this behaviour of print() function, the statement print ('Hi', name, ',1) is printing a newline at the end. Hence "How are you doing?" is getting printed on the next line.
To fix this we can add the end argument to the first print() function like this:
print ('Hi', name, ',1, end = '')
Find the errors in following code fragment :
c = input( "Enter your class" )
print ("Last year you were in class") c - 1Answer
There are two errors in this code fragment:
c - 1is outside the parenthesis of print function. It should be specified as one of the arguments of print function.- c is a string as input function returns a string. With
c - 1, we are trying to subtract a integer from a string which is an invalid operation in Python.
The corrected program is like this:
c = int(input( "Enter your class" ))
print ("Last year you were in class", c - 1) What will be returned by Python as result of following statements?
(a) >>> type(0)
Answer
<class 'int'>
(b) >>> type(int(0))
Answer
<class 'int'>
(c) >>>.type(int('0')
Answer
SyntaxError: invalid syntax
(d) >>> type('0')
Answer
<class 'str'>
(e) >>> type(1.0)
Answer
<class 'float'>
(f) >>> type(int(1.0))
Answer
<class 'int'>
(g) >>>type(float(0))
Answer
<class 'float'>
(h) >>> type(float(1.0))
Answer
<class 'float'>
(i) >>> type( 3/2)
Answer
<class 'float'>
What will be the output produced by following code ?
(a) >>> str(print())+"One"
Output
NoneOne
Explanation
print() function doesn't return any value so its return value is None. Hence, str(print()) becomes str(None). str(None) converts None into string 'None' and addition operator joins 'None' and 'One' to give the final output as 'NoneOne'.
(b) >>> str(print("hello"))+"One"
Output
hello
NoneOne
Explanation
First, print("hello") function is executed which prints the first line of the output as hello. The return value of print() function is None i.e. nothing. str() function converts it into string and addition operator joins 'None' and 'One' to give the second line of the output as 'NoneOne'.
(c) >>> print(print("Hola"))
Output
Hola
None
Explanation
First, print("Hola") function is executed which prints the first line of the output as Hola. The return value of print() function is None i.e. nothing. This is passed as argument to the outer print function which converts it into string and prints the second line of output as None.
(d) >>> print (print ("Hola", end = " "))
Output
Hola None
Explanation
First, print ("Hola", end = " ") function is executed which prints Hola. As end argument is specified as " " so newline is not printed after Hola. The next output starts from the same line. The return value of print() function is None i.e. nothing. This is passed as argument to the outer print function which converts it into string and prints None in the same line after Hola.
Carefully look at the following code and its execution on Python shell. Why is the last assignment giving error ?
>>> a = 0o12
>>> print(a)
10
>>> b = 0o13
>>> c = 0o78
File "<python-input-41-27fbe2fd265f>", line 1
c = 0o78
^
SyntaxError : invalid syntax Answer
Due to the prefix 0o, the number is treated as an octal number by Python but digit 8 is invalid in Octal number system hence we are getting this error.
Predict the output
a, b, c = 2, 3, 4
a, b, c = a*a, a*b, a*c
print(a, b, c)Output
4 6 8
Explanation
a, b, c = 2, 3, 4⇒ assigns initial value of 2 to a, 3 to b and 4 to c.a, b, c = a*a, a*b, a*c
⇒ a, b, c = 2*2, 2*3, 2*4
⇒ a, b, c = 4, 6, 8print(a, b, c)⇒ prints values of a, b, c as 4, 6 and 8 respectively.
The id( ) can be used to get the memory address of a variable. Consider the adjacent code and tell if the id( ) functions will return the same value or not(as the value to be printed via print() ) ? Why ?
[There are four print() function statements that are printing id of variable num in the code shown on the right.
num = 13
print( id(num) )
num = num + 3
print( id(num) )
num = num - 3
print( id(num) )
num = "Hello"
print( id(num) )Answer
num = 13
print( id(num) ) # print 1
num = num + 3
print( id(num) ) # print 2
num = num - 3
print( id(num) ) # print 3
num = "Hello"
print( id(num) ) # print 4For the print statements commented as print 1 and print 3 above, the id() function will return the same value. For print 2 and print 4, the value returned by id() function will be different.
The reason is that for both print 1 and print 3 statements the value of num is the same which is 13. So id(num) gives the address of the memory location which contains 13 in the front-loaded dataspace.
Consider below given two sets of codes, which are nearly identical, along with their execution in Python shell. Notice that first code-fragment after taking input gives error, while second code-fragment does not produce error. Can you tell why ?
(a)
>>> print(num = float(input("value1:")) )
value1:67
TypeError: 'num' is an invalid keyword argument for this function
(b)
>>> print(float(input("valuel:")) )
value1:67
67.0
Answer
In part a, the value entered by the user is converted to a float type and passed to the print function by assigning it to a variable named num. It means that we are passing an argument named num to the print function. But print function doesn't accept any argument named num. Hence, we get this error telling us that num is an invalid argument for print function.
In part b, we are converting the value entered by the user to a float type and directly passing it to the print function. Hence, it works correctly and the value gets printed.
Predict the output of the following code :
days = int (input ("Input days : ")) * 3600 * 24
hours = int(input("Input hours: ")) * 3600
minutes = int(input("Input minutes: ")) * 60
seconds = int(input("Input seconds: "))
time = days + hours + minutes + seconds
print("Total number of seconds", time)If the input given is in this order : 1, 2, 3, 4
Output
Input days : 1
Input hours: 2
Input minutes: 3
Input seconds: 4
Total number of seconds 93784
What will the following code result into ?
n1, n2 = 5, 7
n3 = n1 + n2
n4 = n4 + 2
print(n1, n2, n3, n4)Answer
The code will result into an error as in the statement n4 = n4 + 2, variable n4 is undefined.
Correct the following program so that it displays 33 when 30 is input.
val = input("Enter a value")
nval = val + 30
print(nval)Answer
Below is the corrected program:
val = int(input("Enter a value")) #used int() to convert input value into integer
nval = val + 3 #changed 30 to 3
print(nval)Write a program that displays a joke. But display the punchline only when the user presses enter key.
(Hint. You may use input( ))
print("Why is 6 afraid of 7?")
input("Press Enter")
print("Because 7 8(ate) 9 :-)")Why is 6 afraid of 7?
Press Enter
Because 7 8(ate) 9 :-)
Write a program to read today's date (only del part) from user. Then display how many days are left in the current month.
day = int(input("Enter day part of today's date: "))
totalDays = int(input("Enter total number of days in this month: "))
daysLeft = totalDays - day
print(daysLeft, "days are left in current month")Enter day part of today's date: 16
Enter total number of days in this month: 31
15 days are left in current month
Write a program that generates the following output :
5
10
9
Assign value 5 to a variable using assignment operator (=) Multiply it with 2 to generate 10 and subtract 1 to generate 9.
a = 5
print(a)
a = a * 2
print(a)
a = a - 1
print(a)5
10
9
Modify above program so as to print output as 5@10@9.
a = 5
print(a, end='@')
a = a * 2
print(a, end='@')
a = a - 1
print(a)5@10@9
Write the program with maximum three lines of code and that assigns first 5 multiples of a number to 5 variables and then print them.
a = int(input("Enter a number: "))
b, c, d, e = a * 2, a * 3, a * 4, a * 5
print(a, b, c, d, e)Enter a number: 2
2 4 6 8 10
Write a Python program that accepts radius of a circle and prints its area.
r = float(input("Enter radius of circle: "))
a = 3.14159 * r * r
print("Area of circle =", a)Enter radius of circle: 7.5
Area of circle = 176.7144375
Write Python program that accepts marks in 5 subjects and outputs average marks.
m1 = int(input("Enter first subject marks: "))
m2 = int(input("Enter second subject marks: "))
m3 = int(input("Enter third subject marks: "))
m4 = int(input("Enter fourth subject marks: "))
m5 = int(input("Enter fifth subject marks: "))
avg = (m1 + m2+ m3+ m4 + m5) / 5;
print("Average Marks =", avg)Enter first subject marks: 65
Enter second subject marks: 78
Enter third subject marks: 79
Enter fourth subject marks: 80
Enter fifth subject marks: 85
Average Marks = 77.4
Write a short program that asks for your height in centimetres and then converts your height to feet and inches. (1 foot = 12 inches, 1 inch = 2.54 cm).
ht = int(input("Enter your height in centimeters: "))
htInInch = ht / 2.54;
feet = htInInch // 12;
inch = htInInch % 12;
print("Your height is", feet, "feet and", inch, "inches")Enter your height in centimeters: 162
Your height is 5.0 feet and 3.7795275590551185 inches
Write a program to read a number n and print n2, n3 and n4.
n = int(input("Enter n: "))
n2, n3, n4 = n ** 2, n ** 3, n ** 4
print("n =", n)
print("n^2 =", n2)
print("n^3 =", n3)
print("n^4 =", n4)Enter n: 2
n = 2
n^2 = 4
n^3 = 8
n^4 = 16
Write a program to find area of a triangle.
h = float(input("Enter height of the triangle: "))
b = float(input("Enter base of the triangle: "))
area = 0.5 * b * h
print("Area of triangle = ", area)Enter height of the triangle: 2.5
Enter base of the triangle: 5
Area of triangle = 6.25
Write a program to compute simple interest and compound interest.
p = float(input("Enter principal: "))
r = float(input("Enter rate: "))
t = int(input("Enter time: "))
si = (p * r * t) / 100
ci = p * ((1 + (r / 100 ))** t) - p
print("Simple interest = ", si)
print("Compound interest = ", ci)Enter principal: 15217.75
Enter rate: 9.2
Enter time: 3
Simple interest = 4200.098999999999
Compound interest = 4598.357987312007
Write a program to input a number and print its first five multiples.
n = int(input("Enter number: "))
print("First five multiples of", n, "are")
print(n, n * 2, n * 3, n * 4, n * 5)Enter number: 5
First five multiples of 5 are
5 10 15 20 25
Write a program to read details like name, class, age of a student and then print the details firstly in same line and then in separate lines. Make sure to have two blank lines in these two different types of prints.
n = input("Enter name of student: ")
c = int(input("Enter class of student: "))
a = int(input("Enter age of student: "))
print("Name:", n, "Class:", c, "Age:", a)
print()
print()
print("Name:", n)
print("Class:", c)
print("Age:", a)Enter name of student: Kavya
Enter class of student: 11
Enter age of student: 17
Name: Kavya Class: 11 Age: 17
Name: Kavya
Class: 11
Age: 17
Write a program to input a single digit(n) and print a 3 digit number created as <n(n + 1)(n + 2)> e.g., if you input 7, then it should print 789. Assume that the input digit is in range 1-7.
d = int(input("Enter a digit in range 1-7: "))
n = d * 10 + d + 1
n = n * 10 + d + 2
print("3 digit number =", n)Enter a digit in range 1-7: 7
3 digit number = 789
Write a program to read three numbers in three variables and swap first two variables with the sums of first and second, second and third numbers respectively.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
print("The three number are", a, b, c)
a, b = a + b, b + c
print("Numbers after swapping are", a, b, c)Enter first number: 10
Enter second number: 15
Enter third number: 20
The three number are 10 15 20
Numbers after swapping are 25 35 20