31
Reading Input from the Console eval function

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

Embed Size (px)

Citation preview

Page 1: 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

Reading Input from the Console

eval function

Page 2: 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

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.

Page 3: 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

ComputeAreaWithConsoleInput.py

# Prompt the user to enter a radiusradius =eval(input("Enter a value for radius: "))

# Compute areaarea = radius * radius * 3.14159

# Display resultsprint("The area for the circle of radius", radius, "is", area)

Page 4: 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

eval function

• s = input("Enter a value for radius: ") # Read input as a string

• radius = eval(s) # Convert the string to a number

Page 5: 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

ComputeAverage.py

# Prompt the user to enter three numbersnumber1 = eval(input("Enter the first number: "))number2 = eval(input("Enter the second number: "))number3 = eval(input("Enter the third number: "))

# Compute averageaverage = (number1 + number2 + number3) / 3

# Display resultprint("The average of", number1, number2, number3,"is", average)

Page 6: 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

Variables, Assignment Statements, and Expressions

Variables are used to reference values that may be changed in the program

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

Variables, Assignment Statements, and Expressions 2

# Compute the first arearadius = 1.0 radius 1.0area = radius * radius * 3.14159 area 3.14159print("The area is", area, "for radius", radius)

# Compute the second arearadius = 2.0 radius 2.0area = radius * radius * 3.14159 area 12.56636print("The area is", area, "for radius", radius)

Page 8: 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

multiple variables

i = j = k = 1which is equivalent tok = 1j = ki = j

Page 9: 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
Page 10: 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

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

Page 11: 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

ComputeAverageWithSimultaneousAssignment.py

# Prompt the user to enter three numbersnumber1, number2, number3 = eval(input("Enter three numbers separated by commas: "))

# Compute averageaverage = (number1 + number2 + number3) / 3

# Display resultprint("The average of", number1, number2, number3"is",average)

Page 12: 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

Named Constants# Assign a radiusradius = 20 # radius is now 20# Compute areaPI = 3.14159area = radius * radius * PI# Display resultsprint("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 3.14159 for

PI), you3. need to change it only in a single location in the source code. Descriptive

names make the program easy to read.

Page 13: 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

Numeric Data Types and Operators

Python has two numeric types—integers and floating-point numbersfor working with the operators +, -, *, /, //, **, and %.

Page 14: 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
Page 15: 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

DisplayTime.py

# Prompt the user for inputseconds = eval(input("Enter an integer for seconds: "))# Get minutes and remaining secondsminutes = seconds // 60 # Find minutes in secondsremainingSeconds = seconds % 60 # Seconds remainingprint(seconds, "seconds is", minutes,"minutes and", remainingSeconds, "seconds")

Page 16: 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

Scientific Notation

Page 17: 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

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

Page 18: 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

Type Conversions and Rounding

If one of the operands for the numeric operators is a float value, the result will be a float valueint(value)

Page 19: 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
Page 20: 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

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

Page 21: 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

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. 1970 was the year when the UNIX operating system was formally introduced. For example, time.time() returns 1285543663.205, which means 1285543663 seconds and 205 milliseconds.

Page 22: 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

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, 1203183068.328).2. Obtain the total seconds totalSeconds using the int function (int(1203183068.328)1203183068).3. Compute the current second from totalSeconds % 60 (1203183068 seconds %60 8, which is the current second).4. Obtain the total minutes totalMinutes by dividing totalSeconds by 60 (1203183068seconds // 60 20053051 minutes).5. Compute the current minute from totalMinutes % 60 (20053051 minutes % 60 31,which is the current minute).6. Obtain the total hours totalHours by dividing totalMinutes by 60 (20053051minutes // 60 334217 hours).7. Compute the current hour from totalHours % 24 (334217 hours % 24 17, whichis the current hour).Listing 2.7 gives the complete program.

Page 23: 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

ShowCurrentTime.pyimport timecurrentTime = time.time() # Get current time# Obtain the total seconds since midnight, Jan 1, 1970totalSeconds = int(currentTime)# Get the current secondcurrentSecond = totalSeconds % 60# Obtain the total minutestotalMinutes = totalSeconds // 60# Compute the current minute in the hourcurrentMinute = totalMinutes % 60# Obtain the total hourstotalHours = totalMinutes // 60# Compute the current hourcurrentHour = totalHours % 24# Display resultsprint("Current time is", currentHour, ":",currentMinute, ":", currentSecond, "GMT")

Page 24: 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

Elementary Programming

Page 25: 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
Page 26: 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

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

Page 27: 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

Case Study: Computing Distances

• This section presents two programs that compute and display the distance between two points.

Page 28: 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

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

Page 29: 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

ComputeDistanceGraphics.py 2

Page 30: 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

import turtle# Prompt the user for inputting two pointsx1, y1 = eval(input("Enter x1 and y1 for point 1: "))x2, y2 = eval(input("Enter x2 and y2 for point 2: "))# Compute the distancedistance = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5# Display two points and the connecting lineturtle.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 lineturtle.penup()turtle.goto((x1 + x2) / 2, (y1 + y2) / 2)turtle.write(distance)turtle.done()

Page 31: 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

Home-work

• All PROGRAMMING EXERCISES on page 55 to 61. (26 exam)