Class4 (BSD)
Class4 (BSD)
Class4 (BSD)
The interactive shell is a tool that allows you to type Python instructions one at a
time and see the results instantly. This is an excellent way to learn Python and
experiment with its features.
o Windows: Open the Start menu, type “Mu,” and select the app.
o macOS: Go to the Applications folder and double-click the Mu app.
o Click the New button and save the empty file as blank.py.
o The interactive shell will appear as a new pane at the bottom of the Mu
editor window with a >>> prompt.
Enter 2 + 2 at the prompt to have Python do some simple math. The Mu window
should now look like this:
>>> 2 + 2
4 >>>
Expressions
In Python, 2 + 2 is called an expression, which is the most basic kind of
programming instruction in the language. Expressions consist of values (such as 2)
and operators (such as +), and they can always evaluate (that is, reduce) down to a
single value. That means you can use expressions any where in Python code that
you could also use a value.
In the previous example, 2 + 2 is evaluated down to a single value, 4. A single value
with no operators is also considered an expression, though it evaluates only to itself,
as shown here:
>>> 2
It consists of:
Values: Numbers, text, or other data (e.g., 2, 4, 'Hello').
>>> 2^3 = 8
5^3
You can use plenty of other operators in Python expressions, too. For example
20
>>> (2 + 3) * 6
30
28093077826734
256
>>> 23 / 7
3.2857142857142856
>>> 23 // 7
>>> 23 % 7
>>> 2 + 2
16.0
In each case, you as the programmer must enter the expression, but Python does
the hard part of evaluating it down to a single value. Python will keep evaluating
parts of the expression until it becomes a single value, as shown here:
These rules for putting operators and values together to form expressions are a
fundamental part of Python as a programming language, just like the grammar rules
that help us communicate. Here’s an example:
The second line is difficult to parse because it doesn’t follow the rules of English.
Similarly, if you enter a bad Python instruction, Python won’t be able to understand it
and will display a SyntaxError error message, as shown here
You can always test to see whether an instruction works by entering it into the
interactive shell. Don’t worry about breaking the computer: the worst that could
happen is that Python responds with an error message. Professional software
developers get error messages while writing code all the time.
Key Takeaway
Errors like SyntaxError are common and part of the coding process.
Mistakes won't harm your computer; at most, you'll receive an error message
to help you debug.
Python programs can also have text values called strings, or strs (pronounced
“stirs”). Always surround your string in single quote (') characters (as in 'Hello' or
'Goodbye cruel world!'). so Python knows where the string begins and ends. You can
even have a string with no characters in it, ‘ ‘, called a blank string or an empty
string. We are going to study about String more in later classes as its a little
controversial topic.
If you ever see the error message SyntaxError: EOL while scanning string literal,
you probably forgot the final single quote character at the end of the string,
such as in this example:
String Concatenation
What is it? Concatenation combines two strings into one continuous string.
Operator: +
Example:
5+5 = 10
‘islamabad’ + ‘karachi’=
‘Islamabadkarachi’
If you try to concatenate a string with a non-string (like an integer), Python raises an
error:
To fix this, you can explicitly convert the integer to a string using str():
String Replication
What is it? Replication repeats a string multiple times.
Operator: *
Example:
>>> 'Alice' + 42
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
'Alice' + 42
TypeError: can only concatenate str (not "int") to str
The error message can only concatenate(link) str (not "int") to str means that Python
thought you were trying to concatenate an integer to the string 'Alice'. If you want it to
run, Your code will have to explicitly convert the integer to a string because Python
cannot do this automatically. (Converting data types is an awesome thing and we will
learn about it in our next classes when we talk about the str(), int(), and float()
functions.)
The * operator multiplies two integer or floating-point values. But when the * operator
is used on one string value and one integer value, it becomes the string replication
operator. Enter a string multiplied by a number into the interactive shell to see this in
action.
>>> 'Alice' * 5
'AliceAliceAliceAliceAlice'
The expression evaluates down to a single string value that repeats the original
string a number of times equal to the integer value. String replication is a useful trick,
but it’s not used as often as string concatenation. The * operator can be used with
only two numeric values (for multiplication), or one string value and one integer value
(for string replication). Otherwise, Python will just display an error message, like the
following:
It makes sense that Python wouldn’t understand these expressions: you can’t
multiply two words, and it’s hard to replicate an arbitrary string a fractional number of
times.
1. Instant Feedback
o The interactive shell allows you to type Python instructions and see the
results immediately.
o This instant feedback helps you quickly understand how Python works.
2. Experimentation
o It’s perfect for trying out small pieces of code or testing how a specific
function or operation behaves.
o For beginners, the shell is like a playground where you can learn
Python’s syntax and features step by step.
o When you encounter an error in your code, you can test individual lines
or commands in the shell to pinpoint where the issue lies.
o You can use the shell as a calculator or for running small snippets of
Python code, like checking logic, formulas, or expressions.
6. Improved Workflow
o For larger programs, you can use the interactive shell to test small
components before adding them to your script, saving time and effort.
In the next class, we'll explore how to store values in variables and use
assignment statements. You'll learn how variables can hold different
types of data and how to update or overwrite values in them. We'll also
cover the rules for naming variables, ensuring your code stays organized
and readable. Finally, we'll go over the basics of writing and running your
first Python program, with an emphasis on using functions like print()
and input() for interaction. You'll get hands-on experience working with
variables, expressions, and simple user input!
Class 4
>>> spam = 40
>>> spam
40
>>> eggs = 2
>>> spam + eggs
42
>>> spam + eggs + spam
82
>>> spam = spam + 2
>>> spam
42
2. Variables in Expressions
You can use variables in mathematical expressions or combine
them with other variables:
A variable is initialized (or created) the first time a value is stored in it.
After that, you can use it in expressions with other variables and values .
When a variable is assigned a new value , the old value is forgotten,
which is why spam evaluated to 42 instead of 40 at the end of the
example. This is called overwriting the variable. Enter the following code
into the interactive shell to try overwriting a string:
Just like the box in Figure below, the spam variable in this
example stores 'Hello' until you replace the string with 'Goodbye'.
When a new value is assigned to a variable, the old one is forgotten.
Variable Names
A good variable name describes the data it contains. Imagine that you
moved to a new house and labelled all of your moving boxes as Stuff.
You’d never find anything! Most of the our use generic variable names
like spam, eggs, and bacon, which come from the Monty Python “Spam”
sketch. But in your programs, a descriptive name will help make your
code more readable.
Though you can name your variables almost anything, Python does
have some naming restrictions. Table below has examples of legal
variable names. You can name a variable anything as long as it obeys
the following three rules:
• It can be only one word with no spaces.
• It can use only letters, numbers, and the underscore (_) character.
• It can’t begin with a number.
Valid and Invalid Variable Names
Valid Names Invalid Names
current_balance current-balance (hyphens are not
allowed)
currentBalance current balance (spaces are not allowed
account4 4account (can’t begin with a number)
_42 42 (can’t begin with a number)
TOTAL_SUM TOTAL_$UM (special characters like $
are not allowed)
hello 'hello' (special characters like ' are not
allowed)
While the interactive shell is good for running Python instructions one at a time, to
write entire Python programs, you’ll type the instructions into the file editor. The file
editor is similar to text editors such as Notepad or TextMate, but it has some features
specifically for entering source code. To open a new file in Mu, click the New button
on the top row.
The window that appears should contain a cursor awaiting your input, but it’s
different from the interactive shell, which runs Python instructions as soon as you
press enter. The file editor lets you type in many instructions, save the file, and run
the program. Here’s how you can tell the difference between the two
o Click the New button on the top row to open a blank file.
print('Hello, world!')
print('What is your name?') # Ask for the user's name
myName = input() # Store the name input in a
variable
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName)) # Display the length of the name
print('What is your age?') # Ask for the user's age
myAge = input() # Store the age input in a variable
print('You will be ' + str(int(myAge) + 1) + ' in a year.') # Show age next
year
Once you’ve saved, let’s run our program. Press the F5 key. Your program should
run in the interactive shell window. Remember, you have to press F5 from the file
editor window, not the interactive shell window. Enter your name when your program
asks for it.
The program’s output in the interactive shell should look something like this:
When there are no more lines of code to execute, the Python program terminates;
that is, it stops running. (You can also say that the Python pro gram exits.) you dont
have to put } like we do in C programming or C++.
You can close the file editor by clicking the X at the top of the window. To reload a
saved program, select File4Open... from the menu. Do that now, and in the window
that appears, choose hello.py and click the Open button. Your previously saved
hello.py program should open in the file editor window.
1. Comments
What are Comments?
o Comments are notes in your code that Python ignores when running
the program.
o They start with a # and explain what the code does.
Python ignores comments, and you can use them to write notes or remind yourself
what the code is trying to do. Any text for the rest of the line following a hash mark
(#) is part of a comment.
Sometimes, programmers will put a # in front of a line of code to tem porarily remove
it while testing a program. This is called commenting out code, and it can be useful
when you’re trying to figure out why a program isn’t working. You can remove the #
later when you are ready to put the line back in.
Python also ignores the blank line after the comment. You can add as many blank
lines to your program as you want. This can make your code easier to read, like
paragraphs in a book
The line print('Hello, world!') means “Print out the text in the string 'Hello, world!'.”
When Python executes this line, you say that Python is calling the print() function
and the string value is being passed to the function. A value that is passed to a
function call is an argument. Notice that the quotes are not printed to the screen.
They just mark where the string begins and ends; they are not part of the string
value.
How It Works:
The text inside ' ' is called a string.
The quotes are not displayed—they simply indicate the beginning and end of
the string.
Blank Lines: Use print() with empty parentheses to create a blank line.
3. The input() Function
Purpose: Waits for the user to type something and press Enter.
Example:
The value entered by the user (e.g., 'Al') is stored in the variable myName.
Remember that expressions can always evaluate to a single value. If 'Al' is the value
stored in myName on line, then this expression evaluates to 'It is good to meet you,
Al'. This single string value is then passed to print(), which prints it on the screen.
Other Examples:
Key Takeaways
1. Comments: Use # to add notes or disable lines temporarily.
2. print(): Displays strings or values on the screen.
3. input(): Collects input from the user.
4. len(): Counts characters in a string.
5. Data Types Matter: Always match data types, or convert them using functions
like str().