Editing code
Editing
An Editor pane will automatically open every time you open a file. Things to know about the Editor windows:
PyCharm automatically saves your files. No need to explicitly save.
The line numbers on the left side are used to identify individual lines of code in error messages and elsewhere.
Familiar text editing features like Cut and Paste are available in the
Edit
menu at the top or Right-Clicking in an editor window. Learn those keyboard shortcuts!CMD+/
(Mac) orCtrl+/
(Windows, Linux) toggles comments on the current line or selected lines. This is one of my favorite keyboard shortcuts!Suppose your code calls a function defined elsewhere. Hold down
Cmd
(Mac) orCtrl
(Windows, Linux) and hover over the function call. It will turn blue like a link. Left click the link and the function definition in the editor. Very handy! Look up the Go back keyboard shortcut to return your cursor to where you were.Not happy with a variable or function name?
Right-click it > Rename...
It will be renamed everywhere in scope!Use the arrow keys to move the cursor one character at a time. Hold down
Ctrl
(Windows, Linux) orOption
(Mac) while tapping the left- or right-arrows. You will skip entire “words”. Again, very handy. Hold downShift
as well to select those words!
Exercise
Create a new file called fib.py
in your pycharm-test
folder and paste in the following code:
def fibonacci(n):
"""
Computes and returns the Fibonacci sequence of length n.
Assumes n >= 1
"""
if n == 1:
return [1]
if n == 2:
return [1, 1]
result = [1, 1]
for i in range(2,n):
result.append(result[i-1] + result[i-2])
return result
print(fibonacci(1))
print(fibonacci(2))
print(fibonacci(6))
print(fibonacci(10))
- Hold down
Cmd
(Mac) orCtrl
(Windows, Linux) and mouse over one of thefibonacci()
calls at the bottom. Click the link and watch the cursor jump. - Using the keyboard shortcut, comment out the first three
print(...)
calls at the bottom all at once. - Now uncomment them all at once.
Right-click
afibonnaci()
call and rename the symbol. Where does it change in the code?- Hit
Ctrl+Z
orCmd+Z
to undo the rename.
Knowledge check:
- Question: How do you comment/uncomment a block of code with your keyboard?
- Question: What does holding down
Cmd
orCtrl
+ left-clicking on a name in the editor window do? - Exercise: Add a second function to your
fib.py
file namedhello()
that simply printsHello World
when called. Now, try to rename (as described above) thehello
function tofibonacci
, which already exists. Describe what happens.