Class4 (BSD)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Class 4 ( including some left over of class 3)

Entering Expressions into the Interactive Shell

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.

How to Run the Interactive Shell

To start the interactive shell, follow these steps:


1. Open the Mu Editor:

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.

2. Create a New File:

o Click the New button and save the empty file as blank.py.

3. Run the File:

o Click the Run button or press F5.

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

An expression is the simplest type of instruction in Python.

It consists of:
 Values: Numbers, text, or other data (e.g., 2, 4, 'Hello').

 Operators: Symbols that perform operations (e.g., +, -, *, /).

Expressions evaluate to a single value.

>>> 2^3 = 8
5^3
You can use plenty of other operators in Python expressions, too. For example

Operator Operation Example Evaluates to . . .


** Exponent (power 2 ** 3 8
2)
% Modulus/remainder 22 % 8 6
// Integer division 22 // 8 2
/floored quotient
/ Division 22 / 8 2.75
* Multiplication 3*5 15
- Subtraction 5-2 3
+ Addition 2+2 4
The order of operations (also called precedence) of Python math operators is similar
to that of mathematics. The **(exponent) operator is evaluated first; the *, /, //, and %
operators are evaluated next, from left to right; and the + and - operators are
evaluated last (also from left to right). You can use parentheses() to override the
usual precedence if you need to. Whitespace in between the operators and values
doesn’t matter for Python (except for the indentation at the beginning of the line), but
a single space is =

Enter the following expressions into the interactive shell:


>>> 2 + 3 * 6

20

>>> (2 + 3) * 6

30

>>> 48565878 * 578453

28093077826734

>>> 2 ** 8 2x2x2x2x2x2x2x2 = 256

256

>>> 23 / 7

3.2857142857142856

>>> 23 // 7

>>> 23 % 7

>>> 2 + 2

>>> (5 - 1) * ((7 + 1) / (3 - 1))

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:

This is a grammatically correct English sentence.

This grammatically is sentence not English correct a.

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.

 Testing expressions in the interactive shell allows you to identify mistakes


instantly.

 Mistakes won't harm your computer; at most, you'll receive an error message
to help you debug.

The Integer, Floating-Point, and String Data Types


Remember that expressions are just values combined with operators, and they
always evaluate down to a single value. A data type is a category for values, and
every value belongs to exactly one data type. The most common data types in
Python are listed in Table following. The values -2 and 30, for example, are said to
be integer values. The integer (or int) data type indicates values that are whole
numbers. Numbers with a decimal point, such as 3.14, are called floating-point
numbers (or floats). Note that even though the value 42 is an integer, the value 42.0
would be a floating-point number.

Data type Examples


Integers (int) -2, -1, 0, 1, 2, 3, 4, 5
Floating-point numbers (floats) -1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25

Strings 'a', 'aa', 'aaa', 'Hello!', '11cats'


S = ’11CATS’

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:

The + operator joins the two strings.

5+5 = 10

‘islamabad’ + ‘karachi’=

‘Islamabadkarachi’

Error with Different Data Types:

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:

The string 'Alice' is repeated 5 times.


Rules:

 The * operator works only with:

1. A string and an integer (e.g., 'Alice' * 5).

2. Two numeric values (for multiplication).

Python doesn’t allow:


 Multiplying two strings (e.g., 'Alice' * 'Bob').

 Replicating a string a fractional number of times (e.g., 'Alice' *


5.0).

String Concatenation and Replication ( in general)


The meaning of an operator may change based on the data types of the values next
to it. For example, + is the addition operator when it operates on two integers or
floating-point values. However, when + is used on two string values, it joins the
strings as the string concatenation operator.

Enter the following into the interactive shell:

>>> 'Alice' + 'Bob'


'AliceBob'
The expression evaluates down to a single, new string value that combines the text
of the two strings. However, if you try to use the + operator on a string and an integer
value, Python will not know how to handle this, and it will display an error message.

>>> '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.

Some thing to know about interactive shell:


Why Use the Interactive Shell?

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 You don’t need to write an entire program—just type a command and


see the output.
3. Learning and Practice

o For beginners, the shell is like a playground where you can learn
Python’s syntax and features step by step.

o It helps you memorize concepts better because you’re actively doing,


not just reading.
4. Debugging Made Simple

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 This makes fixing errors faster and easier.


5. Quick Calculations and Functions

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

Storing Values in Variables


What is a Variable?
A variable is like a labelled box in your computer’s memory where you
can store a single value. Instead of retyping the same value, you can
store it in a variable and reuse it later.
Assignment Statements
You’ll store values in variables with an assignment statement. An
assignment statement consists of a variable name, an equal sign (called
the assignment operator), and the value to be stored. If you enter the
assignment statement spam = 42, then a variable named spam will have
the integer value 42 stored in it.
Think of a variable as a labeled box that a value is placed in, as in
Following:

For example, enter the following into the interactive shell:


 >>> spam = 42 # Assigns the value 42 to the variable named
'spam'
 >>> spam # Access the value stored in 'spam'
42

 >>> 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:

 >>> spam = 'Hello'


 >>> spam
'Hello'
 >>> spam = 'Goodbye'
 >>> spam
'Goodbye

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)

Variable names are case-sensitive, meaning that spam, SPAM, Spam,


and sPaM are four different variables. Though Spam is a valid variable
you can use in a program, it is a Python convention to start your
variables with a lowercase letter.
Spam SPAM sPaM

Your First Program

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

 Interactive Shell: Displays the >>> prompt and executes instructions


immediately.
 File Editor: No >>> prompt; allows you to type and save multiple instructions
to run as a program.
Steps to Create Your First Program
1. Open the File Editor in Mu

o Click the New button on the top row to open a blank file.

2. Enter the Code


Type the following code into the file editor:

# This program says hello and asks for your name.

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

Save the Program


 Click the Save button and name the file hello.py.
 It’s a good habit to save your work frequently. Use shortcuts:
o Windows/Linux: Ctrl + S

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:

o >>> Hello, world!


o What is your name?
Al
o It is good to meet you, Al
o The length of your name is: 2
o What is your age?
4
o You will be 5 in a year.
>>>

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.

Dissecting Your Program


Now that you’ve written your first program, let’s break it down step by step to
understand how each line works.

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 print() Function


 Purpose: Displays text or other information on the screen.
 Example:

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.

4. Printing the User’s Name


 Combining Strings with Variables:
You can use the + operator to join strings and variables.
Example:

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.

If myName is 'Al', the expression evaluates to:


'It is good to meet you, Al'

This result is passed to print() and displayed.

5. The len() Function


 Purpose: Counts the number of characters in a string.
 Example:

If myName is 'Al', len(myName) evaluates to 2.

Other Examples:

6. Common Error: Mixing Data Types


Python doesn’t allow you to mix strings and integers directly with the + operator.
Example of Error:
Why the Error?
 The + operator can only:
o Add numbers (e.g., 2 + 3)
o Concatenate strings (e.g., 'Hello' + ' World')
Fixing the Error: Convert the integer to a string using str().
Correct Example:

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().

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy