- LPU MCA Semester 1
- CAB106
- Unit 1
CAB106 · Unit 1: Python and OOP introduction
Input and output functions and control statements
14 practice questions
Key points
- input returns a str; convert before doing maths
- print has sep and end; f-strings format values
- A loop else runs only when no break happened
- Only empty values, zero and None are falsy
input() reads a line from the keyboard and always returns a string, so convert it with int() or float() before arithmetic. print() accepts sep (placed between items) and end (placed after the last item, default newline). Formatting uses f-strings such as f"{x:.2f}" or "{:>5}".format(s); .2f means two decimals and >5 right-aligns in width 5.
Control flow uses if/elif/else, for over any iterable, and while. range(start, stop, step) stops before stop. break leaves a loop, continue skips to the next pass and pass does nothing. A loop's else block runs only if the loop finished without break. After a for loop the loop variable keeps its last value; if the iterable was empty it is never created.
Truthiness: 0, 0.0, '', [], {}, () and None are falsy; every other value, including the string '0', is truthy. A conditional expression is written a if cond else b.
Exam trap: the else of a loop is not an else for the loop's if. It runs when no break happened, which surprises most beginners.
Try two questions
Which built-in function reads a line of text from the keyboard in Python 3?
- scanf
- cin
- input
- gets
Show the answer
C. input() reads a line from standard input and returns it as a string.
Why not A: scanf is a C library function.
Why not B: cin is the C++ input stream.
Why not D: gets is a C function; Python 3 has no such built-in.