Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to CS Nov 2, 2015.

Similar presentations


Presentation on theme: "Intro to CS Nov 2, 2015."— Presentation transcript:

1 Intro to CS Nov 2, 2015

2 Today Python data types and operations Casting data types
Built-in functions for keyboard input

3 Four Python data types int: age = 20 float: pi = 3.14159 String:
name = ‘Alice’ Boolean: isCold = True

4 Doing arithmetic + Addition - Subtraction * Multiplication / Division
>>> 5/2 = 2.5 % Modulus How to determine an integer is even or odd? // Floor division >>> 5//2 = 2 ** Exponent >>> 5**3 = 125

5 Data types and operators
Numeric types can use all arithmetic operators If mixing string and numeric, be careful !!! print(3+5.5) # ok. Output: 8.5 print(3+’5.5’) # error: unsupported type print(‘3’+’5.5’) # ok. String operation # output: 35.5 print( ‘Hi’*5) #ok. Output: HiHiHiHiHi print(‘Hi’+5) # error.

6 Built-in functions for type conversion
Type conversion is also called type casting int(x): convert x to a integer example: int(‘5’) float(x): convert x to a decimal example: float(‘2.8’) str(x): convert x to a string example: str(5)

7 Type conversion example
print(3+’5’) #error print(3+int(‘5’)) #ok print(‘Hi’ + 5) #error print(‘Hi’ + str(5)) #ok. Output: Hi5

8 Built-in function for keyboard input
Program stops, waits for the user to type something. After user types something and presses Enter, the program resumes and returns what the user typed as a string. Example print(“Please enter your username: “) x=raw_input() print(“You just entered: “, x)

9 Built-in function for keyboard input (cont’)
The Zen of Python: simple is better than complex print(“Please enter your username: “) x=raw_input() print(“You just entered: “, x) Can be rewritten as: x=raw_input(“Please enter your username: “)

10 Built-in function for keyboard input (cont’)
Question: What is the total price to buy 5 books if each costs $10? print("One book costs $10") num_books=input(“How many books you will buy: “) price = num_books*10 print(“Your total price = “, price, “dollars”)

11 Built-in function for keyboard input (cont’)
Question: input() always returns a string. What if I need a number? x=raw_input(“How many books you will buy: “) num_books = int(x) #use int() to convert # string to int price = num_books*10 print(“Your total price = “, price)

12 Summary Python data types: int, float, string, boolean
Arithmetic operations Casting data types: int(), float(), str() keyboard input()


Download ppt "Intro to CS Nov 2, 2015."

Similar presentations


Ads by Google