Download presentation
Presentation is loading. Please wait.
Published bySpencer Hunt Modified over 6 years ago
1
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, it will get you. -- Peter Farrar
2
What is a Data Type? The type of value stored by a variable
Two general categories: String: represents text For now, only use for input/output More later, if time allows Numerical Breaks down into many other types Types have different internal representations
3
Numerical Data Types int: whole numbers float: decimal point numbers
Computations are exact float: decimal point numbers Large range, but fixed precision Not exact Example: =
4
Data Types: Differences
Most arithmetic operations behave as you would expect for all data types Except integer division – result is an integer Example: result = 5//2 float division behaves as you expect: Example: result = 5.0/2.0
5
Data Types: Automatic Conversion
int to float: int op float = float Examples: 5.0/2 16-(3//2) 16-(3.0/2) What about: /4?
6
Data Types: Examples of Automatic Conversion
/2 3.0/2 5**31 5.0**31 5.0/ //5 – 2 4.0/5 – 2 4/5 – 2.0
7
Data Types: Explicit Conversion
Python provides functions to do this: float (<put number here>) int (<put number here>) #truncates! If you would rather round to the nearest whole number, use round() Also takes number as the argument
8
Data Types: Examples of Explicit Conversion
What is the output? float(3) int(3.9) int( ) IDLE: Average of 3 test scores
9
Question: Data Types What is the output of the following code?
result = //2 print result B. 8 C D. 8.0
10
Keyboard Input Read data from the user during program execution
input() function How it works: wait for the user to enter a value read what has been typed when user enters Enter or Return key
11
Keyboard Input: input()
input(<put prompt string here>) Prompts the user to enter a number Assigns entered string to a variable Example: greeting = input("Please enter your message: ")
12
Keyboard Input If you want to read an integer, use int() Example:
score = int(input("Please enter exam score: ")) IDLE: Write a program that asks the user for three integer exam scores, and prints the average.
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.