0% found this document useful (0 votes)
6 views

CS111 2020 SWPart Lect9 Python Datatpes

Uploaded by

qwer353666
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

CS111 2020 SWPart Lect9 Python Datatpes

Uploaded by

qwer353666
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

CS111 – Fundamentals of Computer Science

Data Types
Sabah Sayed
Topics
1. Data Types.
2. Values and Operators.
3. Input Function.
4. Comments.
5. Data Types Conversion.
6. Error Types.
7. Examples.
Remember

What is the o/p of this program? o/p


print ("One!")
print ("Two!", "Three!")
print ()
print ("Four!", "Five!", "Six!")

print("Seven")
Leaving empty
Notes: The print() function has two default behaviors: lines inside a
•It will always print a "line break" character at the end of program, has no
a line
•It will always print a "space" character between multiple effect in the o/p
arguments
Data types
• Data type
– describes the kind of data being stored
– allows you to perform certain operations on the value (e.g., you can add
or subtract two Integer values)
• Basic Data type In python
– Strings (set of characters)
• str (e.g., xyz, hello123, welcome)
– Numbers (set of digits)
• int (e.g., 5, -5, 100, 10032)
• float (e.g., 5.0, -5.0, 100.99, 0.232132234)
– Logical values(True/False)
• bool
Values and types
• Value: may be number or characters
• Type: category of values
examples:
• 2 is int
• 2.0 is float
• ‘hello world’ is string
– Strings can contain 0 or more printed characters. A
string with zero characters is called an "empty string".
– Specify string in python using single quotes, double
quotes, or triple quotes
– Surround a string between triple-quotes, if you want
to use double quotes inside it
• Note:
– type is a built-in function
Number Operations
• i+j , i-j, i*j
If i and j are both of type int  the result
is an int.
If either of them is a float  the result is a
float.

• i/j
The result is a float.

• The operator // provides integer division


that returns the quotient and ignores the
remainder
i//j (round down)
String Operations
• String concatenation (using +)
– i+j
• If i and j are both of type str, the
result is a str which concate both i
and j
• If one of them is str and the other is
int or float an error will appear

Note:
print('h'+'w')
print('h','w')
String Operations
• * : Repeat the original string 'n' times >>> ’atg’ * 3
– i*j  If i is of type str and j is of type int, the ’atgatgatg’
result is a str which repeats the string i (‘j’ times) >>> ’tg’ in ’atgatgatg’
– if j is a str or float then an error will appear True
• In : Checks if first string IS in second string >>> ’tc’ in ’atgatgatg’
• not in : Checks if first string IS NOT in second False
string.
Priority of Operators
(i.e., order of execution)
Comments
• Comments: are lines that are not interpreted by the interpreter
• Use # symbol to add Single line comment
• Use of the triple quote delimiter """ for multi line comments

Example Commenting
""" These set of lines makes it easier
will be ignored, which represents multi-line comment for someone to
"""
# the following line will NOT be ignored, this is a single line comment
quickly
print ('hi there') understand how a
program is
designed to
operate.
o/p:
input function
• input is a built-in function:
– accepts a single string as an argument/parameter (i.e., input variables),
then it prompts the user with that string and waits for them to type in a
series of characters
– returns a string
• e.g., user_age = input("How old are you?")
• This is a problem. How can we solve it??
e.g.,

animal1 = input("Enter an animal name: ")


animal2 = input("Enter another animal name: ")
print ("At the zoo we saw a", animal1)
print ("It was next to the", animal2, "enclosure ")
Data Type Conversion
• Convert from a data type into
another one # define our variables
a = "1"
– e.g., if you have a string variable
b = 5.75
and you need to execute a math
c=3
operation on it, then you must
convert it to float or int
# convert data types
• Functions in python: d = int(a)
– str: convert a given variable to e = str(b)
string f = float(c)
– int: convert a given variable to int print (d+f) # 4.0
– float: convert a given variable to print(d) #1
float print(e) # 5.75 (note: it is a
string)
print(f) # 3.0
Data Type Conversion
monthly_salary = input('how much do you make in a month?')
monthly_salary_float = float(monthly_salary)

# you can write the previous two lines as one line  this is called “Nested calls”
monthly_salary_float = float(input('how much do you make in a month?'))

# calculate the yearly salary


yearly_salary = monthly_salary_float * 12
print ('that means you make', yearly_salary, 'in a year')

• sometimes you can't convert from one data type to another

a = "hello world!"
b = float(a)
Types of Errors
• Syntax errors:
– The code that you wrote does not follow the rules of the language.
– e.g., a single quote is used where a double quote is needed; a keyword is used as a
variable name.
– With a Syntax error your program will not run at all
• Runtime errors:
– your code is fine but the program does not run as expected (it "crashes" at some
point as it is running).
– e.g., if your program is meant to divide two numbers, a run-time error would occur
when the program attempts to divide by zero.
• Logical(semantic) errors:
– the program is correct from a syntax perspective; and it runs; but the result is
wrong.
– For example, if your program prints "2 + 2 = 5" the answer is clearly wrong and your
algorithm for computing the sum of two numbers is incorrect.
What’s type of this error? Syntax Errors
• In a print statement, what happens if you
leave out one of the parentheses?

• In a print statement, what happens if you


leave out both of the parentheses?

• What if you spell print wrong?


• Note: keywords are displayed in a different
color
What’s type of this error? Logical Error

• The program run. However, the o/p is wrong

• Solution:
Examples
1 fruit_one = "Apple"
fruit_two = "Pear"
fruit_three = "Peach"

print ("Your fruits:", fruit_one, fruit_two, fruit_three)


print ("That's all folks!")

2 department1 = "Computer Science"


department2 = "Mathematics"
department3 = "History" In this program it really doesn't
make sense for us to define the
print (department1, department2) third variable since it isn't used, but
it's not an error and Python will
have no problem running this code
Comments: Examples
• write a program that creates three variables. These variables should store the
names of three US Cities. Name your variables appropriately (i.e. don't call your
variables x, y and z - use more descriptive names).
• Next, print out your cities so that they display as follows

solution
city1 = "NYC" # assign first variable to "NYC"
city2 = "Chicago" # assign second variable to "Chicago"
city3 = "San Francisco" # assign third variable to "San Francisco"

# print out the variables one at a time


print("City #1:", city1)
print("City #2:", city2)
print("City #3:", city3)
Comments
Add comment to the following program to clarify what this algorithm did
item="Pizza Slices“
unit_price = 1.99 # define item name
quantity = 10 item = "Pizza Slices"
total = unit_price * quantity # define a unit price
print (quantity, item, "will cost you", total) unit_price = 1.99
# define how many items we are buying
quantity = 10
# compute total cost of items and store it
total = unit_price * quantity
# output result to the user
print (quantity, item, "will cost you", total)
Comments
Write a program that do the following:
# ask the user for the order amount
order =int ( input(“Enter the order amount? "))
# ask the user for the order amount
# compute a 50% discount on the order
# compute a 50% discount on the order discount = order * 0.50

# display the cost of the order before the discount


# display the cost of the order before the print ("Cost before discount:", order)
discount
# display the discount rate and discount amount
print ("Discount rate:", 0.5, "; Discount amount:",
# display the discount rate and discount discount)
amount
# display the final cost of the order with the discount
print ("Final cost with discount:", order - discount)
# display the final cost of the order with the
discount
Example
Write a python program to calculate the
area of a circle. Given pi=3, radius =11.
memory
Example
• You have three tests:
– Test1_mark= 100
– Test2_mark=90
– Test3_mark=85

• Write a python program to calculate the total scores and


average
Test1_mark = 100
Test2_mark = 90
Test3_mark = 85
total = test1_mark + test2_mark + test3_mark
average = total / 3
print ("Total points:", total)
print ("Average score:", average)
Example
• Write a python program to generate the following o/p?
• Note: use only the print function

You might also like