Reading Input from the Console eval function. variable = input("Enter a value: ") The value entered is a string. You can use the function eval to evaluate.

Slides:



Advertisements
Similar presentations
Mathematical Functions, Strings, and Objects. Introduction ■ To solve mathematics problems by using the functions in the math module (§3.2). ■ To represent.
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Chapter 2 Elementary Programming
Types and Arithmetic Operators
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
CS 1400 Chapter 2 sections 1, 2, 4 – 6, 8,
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Chapter 3 Assignment and Interactive Input. 2 Objectives You should be able to describe: Assignment Operators Mathematical Library Functions Interactive.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3 Numerical Data.
 2002 Prentice Hall. All rights reserved. 1 Intro: Java/Python Differences JavaPython Compiled: javac MyClass.java java MyClass Interpreted: python MyProgram.py.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
 2002 Prentice Hall. All rights reserved. 1 Chapter 2 – Introduction to Python Programming Outline 2.1 Introduction 2.2 First Program in Python: Printing.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
Chapter 2 Elementary Programming 1. Introducing Programming with an Example Listing 2.1 Computing the Area of a Circle This program computes the area.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 2 Elementary Programming.
Chapter 3 COMPLETING THE BASICS Programming Fundamentals with C++1.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
1 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 2 Primitive Data Types and Operations.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
INF120 Basics in JAVA Programming AUBG, COS dept Lecture 02 Title: Elementary Java Programming Reference: Farrell Ch 1, Liang Ch 2.
VARIABLES Introduction to Computer Science 1- COMP 1005, 1405 Instructor : Behnam Hajian
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
Agenda  Commenting  Inputting Data from Keyboard (scanf)  Arithmetic Operators  ( ) * / + - %  Order of Operations  Mixing Different Numeric Data.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Input, Output, and Processing
1 Chapter 2 Elementary Programming. 2 Objectives  To write Java programs to perform simple calculations  To obtain input from the console using the.
Computer Science 101 Introduction to Programming.
How to start Visual Studio 2008 or 2010 (command-line program)
Keeping it Neat: Functions and JavaScript Source Files Chapter 7.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
Liang, Introduction to Java Programming1 Primitive Data Types and Operations Gang Qian Department of Computer Science University of Central Oklahoma.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Variables, Expressions and Statements
Math, Data Types. Python Math Operations OperationOperator Addition + Subtraction – Multiplication * Division (floating point) / Division (integer) //
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 2 Primitive Data Types and Operations.
Debugging, Escape Command, More Math. It’s your birthday!  Write a program that asks the user for their name and their age.  Figure out what their birth.
A First Program CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Credits: a significant part of.
Programming Fundamentals with C++1 Chapter 3 COMPLETING THE BASICS.
Data Types and Conversions, Input from the Keyboard CS303E: Elements of Computers and Programming.
Top-Down Stepwise Refinement (L11) * Top-Down Stepwise Refinement * Cast Operator * Promotion (Implicit Conversion) * Unary Operator * Multiplicative Operator.
Data Types and Conversions, Input from the Keyboard If you can't write it down in English, you can't code it. -- Peter Halpern If you lie to the computer,
29 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
Exercise 1 #include int main() { printf(“Hello C Programming!\n”); return 0; } 1.Run your Visual Studio 2008 or Create a new “project” and add.
Last Time…. Operators Arithmetic Operators Assignment Operators Increment/Decrement Operators Relational Operators Logical Operators Expression Statements.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Math, Data Types. Python Math Operations OperationOperator Addition + Subtraction – Multiplication * Division (floating point) / Division (integer) //
Chapter 2 Elementary Programming
Chapter Topics The Basics of a C++ Program Data Types
Chapter 2 Elementary Programming
Chapter 3 Assignment and Interactive Input.
Data Types and Conversions, Input from the Keyboard
Variables, Expressions, and IO
Chapter 2 Elementary Programming
Introduction to Programming
Data types, Expressions and assignment, Input from User
OUTPUT STATEMENTS GC 201.
Chapter 2 Elementary Programming
Chapter 3 Numerical Data
Reading Input from the Keyboard
CS2011 Introduction to Programming I Elementary Programming
Presentation transcript:

Reading Input from the Console eval function

variable = input("Enter a value: ") The value entered is a string. You can use the function eval to evaluate and convert it to a numeric value. For example, eval("34.5") returns 34.5, eval("345") returns 345, eval("3 + 4") returns 7, and eval("51 + (54 * (3 + 2))") returns 321. Listing 2.2 rewrites Listing 2.1 to prompt the user to enter a radius.

ComputeAreaWithConsoleInput.py # Prompt the user to enter a radius radius =eval(input("Enter a value for radius: ")) # Compute area area = radius * radius * # Display results print("The area for the circle of radius", radius, "is", area)

eval function s = input("Enter a value for radius: ") # Read input as a string radius = eval(s) # Convert the string to a number

ComputeAverage.py # Prompt the user to enter three numbers number1 = eval(input("Enter the first number: ")) number2 = eval(input("Enter the second number: ")) number3 = eval(input("Enter the third number: ")) # Compute average average = (number1 + number2 + number3) / 3 # Display result print("The average of", number1, number2, number3, "is", average)

Variables, Assignment Statements, and Expressions Variables are used to reference values that may be changed in the program

Variables, Assignment Statements, and Expressions 2 # Compute the first area radius = 1.0 radius 1.0 area = radius * radius * area print("The area is", area, "for radius", radius) # Compute the second area radius = 2.0 radius 2.0 area = radius * radius * area print("The area is", area, "for radius", radius)

multiple variables i = j = k = 1 which is equivalent to k = 1 j = k i = j

Simultaneous Assignments Python also supports simultaneous assignment in syntax like this: Var1, var2,..., varn = exp1, exp2,..., expn 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 x, y = y, x # Swap x with y

ComputeAverageWithSimultaneousAs signment.py # Prompt the user to enter three numbers number1, number2, number3 = eval(input( "Enter three numbers separated by commas: ")) # Compute average average = (number1 + number2 + number3) / 3 # Display result print("The average of", number1, number2, number3 "is",average)

Named Constants # Assign a radius radius = 20 # radius is now 20 # Compute area PI = area = radius * radius * PI # Display results print("The area for the circle of radius", radius, "is", area) There are three benefits of using constants: 1.You don’t have to repeatedly type the same value if it is used multiple times. 2.If you have to change the constant’s value (e.g., from 3.14 to for PI), you 3.need to change it only in a single location in the source code. Descriptive names make the program easy to read.

Numeric Data Types and Operators Python has two numeric types—integers and floating-point numbers for working with the operators +, -, *, /, //, **, and %.

DisplayTime.py # Prompt the user for input seconds = eval(input("Enter an integer for seconds: ")) # Get minutes and remaining seconds minutes = seconds // 60 # Find minutes in seconds remainingSeconds = seconds % 60 # Seconds remaining print(seconds, "seconds is", minutes, "minutes and", remainingSeconds, "seconds")

Scientific Notation

Augmented Assignment Operators count = count + 1 count += 1 The += operator is called the addition assignment operator.

Type Conversions and Rounding If one of the operands for the numeric operators is a float value, the result will be a float value int(value)

SalesTax.py # Prompt the user for input purchaseAmount = eval(input("Enter purchase amount: ")) # Compute sales tax tax = purchaseAmount * 0.06 # Display tax amount with two digits after decimal point print("Sales tax is", int(tax * 100) / 100.0)

Case Study: Displaying the Current Time The problem is to develop a program that displays the current time in Greenwich Mean Time (GMT) in the format hour:minute:second, such as 13:19:18. The time() function in the time module returns the current time in seconds with millisecond precision elapsed since the time 00:00:00 on January 1, 1970 GMT, as shown in Figure 2.1. This time is known as the UNIX epoch. The epoch is the point when time starts was the year when the UNIX operating system was formally introduced. For example, time.time() returns , which means seconds and 205 milliseconds.

You can use this function to obtain the current time, and then compute the current second, minute, and hour as follows. 1. Obtain the current time (since midnight, January 1, 1970) by invoking time.time() (for example, ). 2. Obtain the total seconds totalSeconds using the int function (int( ) ). 3. Compute the current second from totalSeconds % 60 ( seconds % 60 8, which is the current second). 4. Obtain the total minutes totalMinutes by dividing totalSeconds by 60 ( seconds // minutes). 5. Compute the current minute from totalMinutes % 60 ( minutes % 60 31, which is the current minute). 6. Obtain the total hours totalHours by dividing totalMinutes by 60 ( minutes // hours). 7. Compute the current hour from totalHours % 24 ( hours % 24 17, which is the current hour). Listing 2.7 gives the complete program.

ShowCurrentTime.py import time currentTime = time.time() # Get current time # Obtain the total seconds since midnight, Jan 1, 1970 totalSeconds = int(currentTime) # Get the current second currentSecond = totalSeconds % 60 # Obtain the total minutes totalMinutes = totalSeconds // 60 # Compute the current minute in the hour currentMinute = totalMinutes % 60 # Obtain the total hours totalHours = totalMinutes // 60 # Compute the current hour currentHour = totalHours % 24 # Display results print("Current time is", currentHour, ":", currentMinute, ":", currentSecond, "GMT")

Elementary Programming

ComputeLoan.py Enter annual interest rate as a percentage, e.g., 7.25 annualInterestRate = eval(input( "Enter annual interest rate, e.g., 7.25: ")) monthlyInterestRate = annualInterestRate / 1200 # Enter number of years numberOfYears = eval(input( "Enter number of years as an integer, e.g., 5: ")) # Enter loan amount loanAmount = eval(input("Enter loan amount, e.g., : ")) # Calculate payment monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12)) totalPayment = monthlyPayment * numberOfYears * 12 # Display results print("The monthly payment is", int(monthlyPayment * 100) / 100) print("The total payment is", int(totalPayment * 100) /100)

Case Study: Computing Distances This section presents two programs that compute and display the distance between two points.

ComputeDistance.py # Enter the first point with two float values x1, y1 = eval(input("Enter x1 and y1 for Point 1: ")) # Enter the second point with two float values x2, y2 = eval(input("Enter x2 and y2 for Point 2: ")) # Compute the distance distance = ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5 print("The distance between the two points is", distance)

ComputeDistanceGraphics.py 2

import turtle # Prompt the user for inputting two points x1, y1 = eval(input("Enter x1 and y1 for point 1: ")) x2, y2 = eval(input("Enter x2 and y2 for point 2: ")) # Compute the distance distance = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 # Display two points and the connecting line turtle.penup() turtle.goto(x1, y1) # Move to (x1, y1) turtle.pendown() turtle.write("Point 1") turtle.goto(x2, y2) # Draw a line to (x2, y2) turtle.write("Point 2") # Move to the center point of the line turtle.penup() turtle.goto((x1 + x2) / 2, (y1 + y2) / 2) turtle.write(distance) turtle.done()

Home-work All PROGRAMMING EXERCISES on page 55 to 61. (26 exam)