[go: up one dir, main page]

0% found this document useful (0 votes)
9 views38 pages

ch03

This document provides an overview of constants and variables in Python, including how to write simple programs, read user input, and use identifiers. It covers key concepts such as variable assignment, type casting, and the differences between variables and constants, along with examples and best practices. The document also outlines the software development process and emphasizes the importance of clear naming conventions and data types.

Uploaded by

AKRM YOUSSEF
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views38 pages

ch03

This document provides an overview of constants and variables in Python, including how to write simple programs, read user input, and use identifiers. It covers key concepts such as variable assignment, type casting, and the differences between variables and constants, along with examples and best practices. The document also outlines the software development process and emphasizes the importance of clear naming conventions and data types.

Uploaded by

AKRM YOUSSEF
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Constants and Variables in Python

Computer Programming 1
Program: Intermediate Diploma in Programming and Computer Science

Course Code: APPC121

Amira Alotaibi

College: Applied College

Institution: University Of Jeddah


Outline
▪ Writing a Simple Program
▪ Reading Input from the Console
▪ Identifiers
▪ Variables, Assignment Statements, and Expressions
▪ Simultaneous Assignments
▪ Named Constants
▪ Numeric Data Types and Operators
WRITING A SIMPLE PROGRAM
• Steps to writing a program:
1. Identify the problem
2. Develop an algorithm
3. Write and test the code
• Example: Computing the area of a circle
Algorithm for Computing Area

• Step-by-step algorithm in plain language


• Flowchart of input → computation → output
Listing 2.1 - ComputeArea.py
The algorithm for calculating the area of a circle can be described as follows:
1. Get the circle’s radius from the user.
2. Compute the area by applying the following formula:
area = radius * radius * 𝜋
3. Display the result.
Variable
• In order to store the radius, the program must create a symbol called a
variable.
• A variable is a name that references a value stored in the computer’s
memory.
• You should choose descriptive names for variables
➢ Do not choose “x” or “y”… these have no meaning
➢ Choose names with meaning …“area” or “radius”
Variables

Checking Variable Type


• Use type() to check the type of a variable:

x = 5
print(type(x)) # Output: <class 'int’>

Changing Variable Types (Type Casting)


• Convert between types using int(), float(), str().

x = "10"
y = int(x) # Converts string to integer
Assign value

Variables such as radius and area reference values stored in memory.


•Every variable has a name that refers to a value.
•You can assign a value to a variable using the syntax as shown in line 2. (in
previous example)
•This statement assigns 20 to the variable radius. So now radius references the
value 20.
Trace a program

The following table shows the value in memory for the variables area and
radius as the program is executed.

•This method of reviewing a program is called “tracing a program”.


•It helps you to understand how programs work.
print(item1,…)

• The statement in line 8displays four items on the console.


• You can display any number of items in a print statement using the
following syntax:
print(item1, item2 , ..., itemk)

• If an item is a number, the number is automatically converted to a string


for displaying.
OBTAINING USER INPUT
Reading Input from the Console
• Use input() to accept user input
• Convert input to a number using eval()
• Example: Prompting the user for a radius
• Listing 2.2: ComputeAreaWithConsoleInput.py
Code Example - ComputeAreaWithConsoleInput.py (Listing 2.2)
Reading Multiple Inputs (Listing 2.3)
This program reads three integers and displays their average
Line continuation symbol

• In some cases, the Python interpreter cannot determine the end of the
statement written in multiple lines. You can place the line continuation
symbol (\) at the end of a line to tell the interpreter that the statement is
continued on the next line.
• For example, the following statement

sum = 1 + 2 + 3 + 4 + \
5 + 6
IPO

Most of the programs in early chapter soft his book perform three steps: Input,
Process, and Output, called IPO.
•Input is to receive input from the user.
•Process is to produce results using the input.
•Output is to display the results.
USING IDENTIFIERS
What Are Identifiers?
• Identifiers are names for variables, functions, and objects
• Rules for identifiers:
• Must start with a letter or _ (underscore)
• Can contain letters, numbers, and underscores
• Cannot be a Python keyword (ex: print, if, while … etc)
Example:

• Case sensitive:
Python is case sensitive, area, Area, and AREA are all different identifiers
Examples of Valid & Invalid Identifiers

Valid Invalid
student_age 2value (cannot start with a number)
_privateVar class (reserved keyword)
totalAmount total-amount (contains -)
ASSIGNING DATA TO VARIABLES
• Variables are used to reference ( values that may be changed in the
program
• In the previous programs, we used variables to store values: area,
radius, average
• They are called variables because their values can be changed

Variable Assignment
• The ( = ) operator assigns values
• Example:
Dynamic Typing in Python

• Python automatically detects data types


• Example:
Expression

• An expression represents a computation involving values, variables, and operators that,


taken together, evaluate to a value. For example, consider the following code:

• You can use a variable in an expression. A variable can also be used in both sides of
the = operator.
• For example, x = x + 1
• In this assignment statement, the result of x + 1 is assigned to x. If x is 1 before the
statement is executed, then it becomes 2 after the statement is executed.
Note

• In mathematics, x = 2 * x + 1 denotes an equation. However, in Python, x =


2 *x + 1 is an assignment statement that evaluates the expression 2 * x +
1 and assigns the result to x.
• If a value is assigned to multiple variables, you can use a syntax like this:
i=j=k=1
• which is equivalent to
k=1
j=k
i=j
Scope of a variable
• Every variable has a scope .
• The scope of a variable is the part of the program where the variable can be referenced
• A variable must be created before it can be used
• For example, the following code is wrong

To fix it, you may write the code like this:


Caution

A variable must be assigned a value before it can be used in an expression.


For example:
interestRate= 0.05
interest = interestrate* 45

This code is wrong , because interestRate is assigned a value 0.05 , but


interestrate is not defined .
Python is case sensitive : interestRate and interestrate are two different
variables
SIMULTANEOUS ASSIGNMENT
Assigning Multiple Variables at Once
• Python allows multiple assignments in one line
• Example:
Swapping Variable Values
• Swapping variable values is a common operation in programming and simultaneous
assignment is very useful to perform this operation.
• Consider two variables: x and y . How do you write the code to swap their values? A
common approach is to introduce a temporary variable as follows:

x = 1
y = 2
temp = x # Save x in a temp variable
x = y # Assign the value in y to x
y = temp # Assign the value in temp to y
• But you can simplify the task using the following statement to swap the values of x and y

x, y = y, x # Swap x with y
Obtaining Multiple Input In One Statement

Simultaneous assignment can also be used to obtain multiple input in one statement
For Example:
CONSTANTS

What Are Constants?


• Constants hold fixed values that don’t change
• Convention: Use UPPERCASE for constants
Example of Constants:
Benefits of Using Constants

1. Improves code readability.


2. Prevents accidental modification.
3. Makes updates easier (change in one place).
Difference Between Variables & Constants

Feature Variables Constants


Value Changes Yes No
Naming Convention Lowercase Uppercase
Example radius = 5 PI =3.14159
Numeric Data Types

• The information stored in a computer is generally referred to as data.


• There are two types of numeric data: integers and real numbers.
• Integer types (int for short) are for representing whole numbers.
• Real types are for representing numbers with a fractional part.
• Inside the computer, these two types of data are stored differently.
• Real numbers are represented as floating-point(or float) values.
Numeric Data Types

• How do we tell Python whether a number is an integer or a float


• A number that has a decimal point is a float even if its fractional part is 0
• For example, 1.0 is a float but 1 is an integer
• In the programming terminology, numbers such as 1.0 and 1 are called literals
• A literal is a constant value that appears directly in a program
Data Types in Python

• Numeric: int, float


• String: str
• Boolean: bool
• List, Tuple, Dictionary, Set
TYPE CONVERSION & ROUNDING

Using int() and round()


• Convert float to int: int(value)
• Round numbers: round(value)

Example Code:
GETTING SYSTEM TIME

Using time.time()
SOFTWARE DEVELOPMENT PROCESS

Steps in Software Development


• Problem Analysis → Algorithm Design → Coding → Testing
Code Example - ComputeLoan.py (Listing 2.8)
Summary & Q&A

• Learned about variables, constants, operators, and expressions


• Practiced user input, type conversion, and software development
• Open discussion and final questions

You might also like