0% found this document useful (0 votes)
38 views37 pages

Python Calculator Code Example

This document provides an overview of programming concepts like variables, data types, operators, and comments. It includes examples of a simple calculator program in Python and discusses topics like variable naming rules, data types like integers, floats and strings, arithmetic operators, and using comments to document programs. It also shows how to write a program to calculate the area of a rectangle and suggests adding functionality to calculate the perimeter or width given other values.

Uploaded by

Sky Fire
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)
38 views37 pages

Python Calculator Code Example

This document provides an overview of programming concepts like variables, data types, operators, and comments. It includes examples of a simple calculator program in Python and discusses topics like variable naming rules, data types like integers, floats and strings, arithmetic operators, and using comments to document programs. It also shows how to write a program to calculate the area of a rectangle and suggests adding functionality to calculate the perimeter or width given other values.

Uploaded by

Sky Fire
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

Programming Element

Prepared By Dr Goh Wan Inn


Example of Simple Calculator Program
using Python Language
# This program is to make a simple calculator comment
import os
print (“Additional Calculator of Two Input Number")
print ("")
Display
prompt
num1 = float (input("Enter first number: ")) Gathering input
num2 = float (input("Enter second number: ")) prompt
sum=num1+num2 Process statement
print (num1, "+", num2, "=", sum) Displaying output
[Link] ("PAUSE")

Computer Programming 2
The print Object
• This produces multiple line of output:

print (“I am ”)
print (“Iron Man”)

Computer Programming 5
The print Object
• Another way of producing multiple-line text using
\n

print (“I am\nIron Man ”)

Computer Programming 6
The output Object

Computer Programming 8
Computer Programming 9
Computer Programming 10
Variables and Literals
Variables
• Variable: a storage location in memory

– Has a name and a type of data it can hold


– Python allow programmer use variable without
declaring it.
– Can directly assigned/initialized any value into those
variables.
– Automatically select appropriate data type according to
the value.
Variable automatically assigned as int data type
num1 = 10

11
Variables and
Literals Variables

Way of declaring variable


while asking for input.
Variable num1 assigned to
hold float data type

Computer Programming 12
Variables and Literals
• Literal: a value that is written into a program’s code.

"hello, there" (string literal)


12 (integer literal)

Computer Programming 13
Variables and Literals

15 is an integer literal
This is a string literal
Output Display

Total number of green apple is 15

Computer Programmng
14
Identifiers
• An identifier is a programmer-defined name for
some part of a program: variables, functions, etc.
• You cannot use any of the C++ key words as an
identifier. These words have reserved meaning.

15
Variable Names
• A variable name should represent the purpose of
the variable. For example:

itemsOrdered

The purpose of this variable is to hold the number of


items ordered.

16
Identifier Rules
• The first character of an identifier must be an
alphabetic character or and underscore ( _ ),
• After the first character you may use
alphabetic characters, numbers, or
underscore characters.
• Upper- and lowercase characters are distinct

17
Rules of naming variables
Explanation Example
Variable name should START
either with letter of underscore. score, _number
Cannot start with number.
The reminding character CAN
consist of letters, numbers and total_sales, marks1
underscore.
Should NOT made of reserved and (reserved word),
words and contain any symbols. password& (contain symbol)
May NOT contain spaces of total sales (not valid since has
naming variable names. space between total & sales)
Names are CASE SENSITIVE with totalsales is not same with
uppercase and lowercase. Totalsales

Computer Programming 18
Valid and Invalid Identifiers
IDENTIFIER VALID? REASON IF INVALID

totalSales Yes

total_Sales Yes

[Link] No Cannot contain .

4thQtrSales No Cannot begin with digit

totalSale$ No Cannot contain $

Computer Programming 19
Data Types
Numeric Data Type Character Data Type
❑int ❑string (str)
❑float
❑long Bool Data Types
❑complex ❑True
❑False

Computer Programming 20
Numeric Data Type - int
• Plain integers of positive or negative whole
numbers
• E.g. : 10, -10
• Assign for suitable variable application, such
as number of student (num_student),
number of car (num_car) and etc.

num_student = int (input(“Enter number of student =“)

Computer Programming 21
Numeric Data Type - long
• Long integer with infinite size
• Similar with int, except the are followed by
letter “L”
• E.g. : 10L, -10L

Computer Programming 22
Numeric Data Type - float
• Represent real numbers.

• E.g.
12.45 -3.8

• Stored in a form similar to scientific notation (6.022e23)

• All floating-point numbers are signed

Computer Programming 23
Numeric Data Type - complex
• Use to represent complex number
• Represent by formula a+bi, where a and b are floats, while
i is the
−1
• E.g. : 10+28i

Computer Programming 24
Character Data Type - str

state = str (input("Enter State: "))


print (“State is: ", state)

state = “Singapore”
print (state)

Computer Programming 25
bool Data Type
• Represents values that are true or false
• bool variables are stored as small integers
• false is represented by 0, true by 1:
bool allDone = true;
bool finished = false;allDone finished
1 0

Computer Programming 26
Variable Assignments
• An assignment statement uses the = operator to
store a value in a variable.
item = 12;
• This statement assigns the value 12 to the item
variable.
• The variable receiving the value must appear on
the left side of the = operator.
• This will NOT work:
// ERROR!
12 = item;
Computer Programming 27
Variable Initialization
• To initialize a variable means to assign it a
value and automatically defined with
appropriate data type

length = 12; #Integer data types

Computer Programming 28
Multiple Variable Assignment in the Same Line

Computer Programming 29
Arithmetic Operators

• Used for performing numeric calculations


• C++ has unary, binary, and ternary
operators:
– unary (1 operand) -5
– binary (2 operands) 13 - 7
– ternary (3 operands) exp1 ? exp2 : exp3

Computer Programming 30
Binary Arithmetic Operators
SYMBOL OPERATION EXAMPLE VALUE OF
ans
+ addition ans = 7 + 3; 10

- subtraction ans = 7 - 3; 4

* multiplication ans = 7 * 3; 21

/ division ans = 7 / 3; 2

% modulus ans = 7 % 3; 1

Computer Programming 31
A Closer Look at the / Operator

Computer Programming 32
Program Documentation / Comments

Computer Programming 33
Computer Programming 34
Computer Programming 35
Computer Programming 36
Program to calculate area of rectangular

37
And now??

• Add on the program to


calculate perimeter.

Computer Programming 38
Computer Programming 39
Let’s go for extra miles!
Change to calculate the width required
for an area of rectangular
Hint: ask the area and length required
from user.

Area = length*width

Computer Programming 40

Common questions

Powered by AI

Understanding the rules for valid and invalid identifiers in programming is crucial to error prevention. Python requires that identifiers start with a letter or underscore, with subsequent characters including letters, numbers, or underscores . For instance, a name like '4thQtrSales' is invalid because it begins with a digit . Similarly, names containing special symbols like '$' or reserved words are prohibited . Adhering to these rules prevents syntax errors and enhances code portability, maintainability, and clarity. Misnamed identifiers can cause compilation failures and obscure the developer's intent, leading to logical errors extremely difficult to debug.

Python handles variable initialization and assignment seamlessly by using the '=' operator, thereby automatically defining an appropriate data type based on the assigned value . For instance, 'item = 12' assigns the integer 12 to 'item' and simultaneously sets its type to 'int' . This process is crucial because it directly impacts the variable's usage throughout the program. Proper initialization ensures that variables hold valid, expected values, preventing errors from uninitialized variables. It fosters efficient memory usage and program reliability by making sure that each variable has a correctly assigned and pre-defined role in the code logic.

In programming, properly naming variables is crucial for readability and maintainability. A variable name should represent its purpose, such as 'itemsOrdered' for the number of items ordered . Names must start with an alphabetic character or an underscore, and subsequent characters can include alphabets, numbers, or underscores . Importantly, names are case-sensitive, meaning 'totalsales' and 'Totalsales' are distinct . Good naming conventions prevent confusion over the variable's use or function, thus making code easier to read and maintain. Conventions such as avoiding reserved words or special symbols also help prevent errors . Such thoughtful naming ensures clarity, making modifications and debugging more straightforward.

Arithmetic operations in Python can be performed using operators such as '+', '-', '*', '/', and '%' on numeric data types like 'int', 'float', or 'complex' . Each operation functions differently depending on data type; for instance, division of two integers results in a float if division is not exact . Understanding the data types involved is crucial because it impacts the result's data type and precision. For example, using modulus on integers gives remainder but may not behave as expected with floats due to precision issues . Misunderstanding these nuances can lead to logic errors and inaccuracies, particularly in programs requiring precise calculations.

Multiple variable assignments in the same line allow Python programmers to declare and initialize multiple variables efficiently. This can be done using syntax such as 'a = b = c = 0' , which assigns the value 0 to all three variables 'a', 'b', and 'c'. This technique streamlines code, eliminating redundancy and minimizing the potential for errors caused by multiple, separate assignment statements. It optimizes the workflow by reducing lines of code and simplifying the initialization process. This method is particularly useful for initializing similar or related variables, thereby enhancing code readability and simplicity.

Python supports several numeric data types such as 'int', 'float', 'long', and 'complex' for different applications . 'Int' holds plain integers and is ideal for countable entities like number of students . 'Float' handles real numbers and is used when precision is required, e.g., in scientific computations . 'Long', an advanced feature, supports integers of infinite size, which is beneficial for computations requiring high precision . 'Complex' numbers, represented as a+bi, support mathematical operations involving imaginary numbers . The choice of numeric type affects memory usage, computing time, and precision, hence it is crucial to select the appropriate type for the task to ensure efficiency and accuracy.

Python uses dynamic typing, which means that a variable's data type is determined automatically based on the assigned value . This allows programmers to assign a value to a variable without declaring its data type explicitly. For instance, assigning a floating-point value to a variable automatically makes it a 'float', as shown with 'num1 = float(input(...))' . This feature simplifies code and enhances flexibility, as type declarations do not constrain variable assignments. However, it requires developers to be cautious as it might lead to runtime errors if types are not handled carefully, since type mismatches won't be caught at compile-time.

Enhancing a simple Python calculator program can involve adding more arithmetic operations such as subtraction, multiplication, and division alongside modulus operations . Additionally, incorporating features like error handling for invalid inputs (e.g., non-numeric or dividing by zero) can improve robustness. Implementing functionality to handle multiple calculations in sequence or support for floating-point and complex numbers could be considered. A user interface, either text-based or graphical, can improve interactivity. Extending the calculator to perform scientific calculations or store previous calculations for recall and comparison would also enhance functionality, making it versatile and user-friendly beyond simple arithmetic operations.

Comments in Python serve as in-line documentation within the code, aiding developers in understanding the program's structure and logic. They are essential for explaining complex calculations, the purpose of a code block, or any non-obvious mechanisms that the code implements . Comments improve code readability and maintainability, helping new developers understand the original intent and functionality without deciphering the entire code base. They are also invaluable during debugging, allowing programmers to annotate what each part of the code is supposed to achieve. Without adequate commenting, even simple programs can become obscure and difficult to extend or modify over time.

Operator precedence determines the order in which operations are executed in Python, impacting the evaluation of expressions. Operators with higher precedence are evaluated before those with lower precedence. For example, in the expression '3 + 4 * 5', multiplication has a higher precedence than addition, so the multiplication is performed first, resulting in 3 + 20 = 23 [implied from Source 3]. Understanding operator precedence is crucial as it affects the accuracy and expected outcomes of calculations. Ignoring precedence can lead to incorrect results, necessitating the use of parentheses to explicitly define order when the default order does not align with the programmer's intent.

You might also like