Practice: Python Interpreter and IDE
Q1. Print a greeting
Write a program that prints Hello from the interpreter.
Goal: Run a script that prints.
Q2. Compile and run
Use compile() and exec() to run the source text print(10 + 5).
Goal: Use compile and exec.
Q3. Show the main-program name
Print the value of __name__ in a script that is run directly.
Goal: Understand __name__.
Q4. Main guard
Write a function hello() that prints Hi, then call it only when the file is run directly, using the __name__ check.
Goal: Use the main guard.
Q5. Python 3 check
Print True if the major version of Python is at least 3.
Goal: Check the version.
Q6. Welcome message
Store the name Ravi in a variable, then print Welcome, followed by the name, with a comma and a space.
Goal: Combine variables in print.
Q7. Calculator at the prompt
In the REPL you type 8 * 4 and press Enter. Write a script line that shows the same result.
Goal: Differ REPL and script.
Q8. Type of a code object
Compile the text 'x = 1' in exec mode and print the name of the type of the result.
Goal: Know what compile returns.
Q9. Expression value
What does this script print?
x = 6
y = 7
print(x * y)Goal: Predict simple output.
Q10. Name check
What does this script print when run directly?
if __name__ == '__main__':
print('direct')
else:
print('imported')Goal: Predict __name__.
Q11. Silent line
What does this script print?
x = 5
x + 1
print(x)Goal: Know scripts do not echo values.
Q12. exec with variables
What is printed?
exec('a = 3 * 4')
print(a)Goal: Trace exec.
Q13. Version tuple
What is printed?
print((3, 12) >= (3, 10))Goal: Compare version tuples.
Q14. Two prints, one line
What is printed?
print('Py', end='')
print('thon')Goal: Predict print behaviour.
Q15. Length of a name
What is printed?
name = 'Interpreter'
print(len(name))Goal: Predict len.
Q16. Compile then read
What is printed?
c = compile("print('run')", '<s>', 'eval')
print('before')
eval(c)Goal: Order of compile and exec.
Q17. Fix the missing parentheses
This script fails with a SyntaxError. Fix it so it prints Done.
print 'Done'Goal: Fix a print syntax error.
Q18. Fix the colon
This script has a SyntaxError. Fix it so it prints Direct.
if __name__ == '__main__'
print('Direct')Goal: Fix a missing colon.
Q19. Fix the NameError
The script raises NameError. Fix it so it prints 9.
total = 4 + 5
print(totl)Goal: Fix a misspelled name.
Q20. Explain bytecode
In your own words, explain what bytecode is and who runs it.
Goal: Explain bytecode.