reading input from the console n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Reading Input from the Console PowerPoint Presentation
Download Presentation
Reading Input from the Console

Loading in 2 Seconds...

play fullscreen
1 / 31

Reading Input from the Console - PowerPoint PPT Presentation


  • 155 Views
  • Uploaded on

Reading Input from the Console. eval function. 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 ,

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Reading Input from the Console' - argus


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
eval function
evalfunction
  • variable = input("Enter a value: ")
  • The value entered is a string. You can use the function evalto 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
ComputeAreaWithConsoleInput.py

# Prompt the user to enter a radius

radius =eval(input("Enter a value for radius: "))

# Computearea

area = radius * radius * 3.14159

# Displayresults

print("The area for the circle of radius", radius, "is", area)

eval function1
evalfunction
  • s = input("Enter a value for radius: ") # Read input as a string
  • radius = eval(s) # Convert the string to a number
computeaverage py
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: "))

# Computeaverage

average = (number1 + number2 + number3) / 3

# Displayresult

print("The average of", number1, number2, number3,

"is", average)

variables assignment statements and expressions
Variables, Assignment Statements, and Expressions

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

variables assignment statements and expressions 2
Variables, Assignment Statements, and Expressions 2

# Compute the first area

radius = 1.0 radius 1.0

area = radius * radius * 3.14159 area 3.14159

print("The area is", area, "for radius", radius)

# Compute the second area

radius = 2.0 radius 2.0

area = radius * radius * 3.14159 area 12.56636

print("The area is", area, "for radius", radius)

multiple variables
multiple variables

i = j = k = 1

which is equivalent to

k = 1

j = k

i = j

simultaneous assignments
SimultaneousAssignments
  • 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
computeaveragewithsimultaneousassignment py
ComputeAverageWithSimultaneousAssignment.py

# Prompt the user to enter three numbers

number1, number2, number3 = eval(input(

"Enter three numbers separated by commas: "))

# Computeaverage

average = (number1 + number2 + number3) / 3

# Displayresult

print("The average of", number1, number2, number3

"is",average)

named constants
NamedConstants

# Assign a radius

radius = 20 # radius is now 20

# Computearea

PI = 3.14159

area = radius * radius * PI

# Displayresults

print("The area for the circle of radius", radius, "is", area)

There are three benefits of using constants:

  • You don’t have to repeatedly type the same value if it is used multiple times.
  • If you have to change the constant’s value (e.g., from 3.14 to 3.14159 for PI), you
  • 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
Numeric Data Types and Operators

Python has two numeric types—integers and floating-pointnumbers

for workingwiththeoperators+, -, *, /, //, **, and%.

displaytime py
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 # Secondsremaining

print(seconds, "seconds is", minutes,

"minutes and", remainingSeconds, "seconds")

augmented assignment operators
AugmentedAssignmentOperators

count = count + 1

count += 1

The += operator is called the addition assignment operator.

type conversions and rounding
TypeConversionsandRounding

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

int(value)

salestax py
SalesTax.py

# Prompt the user for input

purchaseAmount= eval(input("Enter purchase amount: "))

# Computesalestax

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
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 withmillisecond precision elapsed since the time 00:00:00 on January 1, 1970 GMT, as shownin Figure 2.1. This time is known as the UNIX epoch. The epoch is the point when timestarts. 1970 was the year when the UNIX operating system was formally introduced. Forexample, time.time() returns 1285543663.205, which means 1285543663 seconds and 205 milliseconds.

slide22
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 (1203183068

seconds // 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 (20053051

minutes // 60 334217 hours).

7. Compute the current hour from totalHours % 24 (334217 hours % 24 17, which

is the current hour).

Listing 2.7 gives the complete program.

showcurrenttime py
ShowCurrentTime.py

importtime

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

# Displayresults

print("Current time is", currentHour, ":",

currentMinute, ":", currentSecond, "GMT")

computeloan py
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 loanamount

loanAmount= eval(input("Enter loan amount, e.g., 120000.95: "))

# Calculatepayment

monthlyPayment= loanAmount * monthlyInterestRate / (1

- 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))

totalPayment= monthlyPayment * numberOfYears * 12

# Displayresults

print("The monthly payment is", int(monthlyPayment * 100) / 100)

print("The total payment is", int(totalPayment * 100) /100)

case study computing distances
CaseStudy: ComputingDistances
  • This section presents two programs that compute and display the distance between twopoints.
computedistance py
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: "))

# Computethe distance

distance = ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5

print("The distance between the two points is", distance)

slide30

importturtle

# 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: "))

# Computethedistance

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
Home-work
  • AllPROGRAMMING EXERCISES on page 55 to 61. (26 exam)