Sequence
A sequence is an ordered collection of items, indexed by positive integers. It is a combination of mutable and non-mutable data types. Three
types of sequence data type available in Python are:
a) Strings
b) Lists
c) Tuples
Introduction to strings
String is an ordered sequence of letters/characters.
They are enclosed in single quotes (‘ ‘) or double (“ “).
The quotes are not part of string.
They only tell the computer where the string constant begins and ends.
They can have any character or sign, including space in them.
#Example 1
My_message1 = 'AI for Kids:))'
print(My_message1)
AI for Kids:))
This lets us make strings that contain quotations.
# Example 2
My_message2 = "AI for Kids:))"
print(My_message2)
AI for Kids:))
Multiline Strings
In case we need to create a multiline string, there is the triple-quote to the rescue: '''
multiline_string = '''This is a string where I
can confortably write on multiple lines
without worring about to use the escape character "\\" as in
the previsou example.
As you'll see, the original string formatting is preserved.
'''
print(multiline_string)
This is a string where I
can confortably write on multiple lines
without worring about to use the escape character "\" as in
the previsou example.
As you'll see, the original string formatting is preserved.
multiline_string = """This is a string where I
can confortably write on multiple lines
without worring about to use the escape character "\\" as in
the previsou example.
As you'll see, the original string formatting is preserved."""
print(multiline_string)
This is a string where I
can confortably write on multiple lines
without worring about to use the escape character "\" as in
the previsou example.
As you'll see, the original string formatting is preserved.
#txt = "We are the so-called "Vikings" from the north."
Number
Number data type stores Numerical Values. These are of three different types:
a) Integer & Long
b) Float / floating point
c) complex numbers
x = 1 # integer
y = 2.8 # float
z = 1j # complex
Integers
Range of an integer in Python can be from -2147483648 to +2147483647, and long integer has unlimited range subject to available memory.
Integers are the whole numbers consisting of + or – sign with decimal digits like 100000, -99, 0, 17.
While writing a large integer value, don’t use commas to separate digits.
Also, integers should not have leading zeros.
x = 1
y = 35656222554887711
z = -3255522
print(3+2)
a=-90000
print(type(a))
5
<class 'int'>
print(3-2)
print(3*2)
print(3/2)
1.5
print(3**2)
You can use parenthesis to modify the standard order of operations.
standard_order = 2+3*4
print(standard_order)
my_order = (2+3)*4
print(my_order)
Floating-Point numbers
Numbers with fractions or decimal point are called floating point numbers.
A floating-point number will consist of sign (+,-) sequence of decimals digits and a dot such as 0.0, -21.9, 0.98333328, 15.2963
x = 1.10
y = 1.0
z = -35.59
x = 35e3
y = 12E4
z = -87.7e100
print(0.1+0.1)
0.2
However, sometimes you will get an answer with an unexpectly long decimal part:
print(0.1+0.2)
0.30000000000000004
This happens because of the way computers represent numbers internally; this has nothing to do with Python itself. Basically, we are used to
working in powers of ten, where one tenth plus two tenths is just three tenths. But computers work in powers of two. So your computer has to
represent 0.1 in a power of two, and then 0.2 as a power of two, and express their sum as a power of two. There is no exact representation
for 0.3 in powers of two, and we see that in the answer to 0.1+0.2.
Python tries to hide this kind of stuff when possible. Don't worry about it much for now; just don't be surprised by it, and know that we will
learn to clean up our results a little later on.
You can also get the same kind of result with other operations.
print(3*0.1)
0.30000000000000004
# Test
3 * 0.1 == 0.3
False
#-2.0 x 105 will be represented as -2.0e5 2.0X10-5 will be 2.0E-5
a = -2.0e5
print(a)
print(type(a))
-200000.0
<class 'float'>
Complex number
Complex numbers are written with a "j" as the imaginary part
x = 3+5j
y = 5j
z = -5j
Booleans
Booleans
Booleans represent one of two values: True or False.
In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the Boolean answer
print(10 > 9)
print(10 == 9)
print(10 < 9)
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
Almost any value is evaluated to True if it has some sort of content.
Any string is True, except empty strings.
Any number is True, except 0.
Any list, tuple, set, and dictionary are True, except empty ones.
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
Type Conversion
The process of converting the value of one data type (integer, string, float, etc.) to another data type is called type conversion. Python has two
types of type conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion
Implicit Type Conversion
Python automatically converts one data type to another data type. This process doesn't need any user involvement.
# Code to calculate the Simple Interest
principle_amount = 2000
roi = 4.5
time = 10
simple_interest = (principle_amount * roi * time)/100
print("datatype of principle amount : ", type(principle_amount))
print("datatype of rate of interest : ", type(roi))
print("value of simple interest : ", simple_interest)
print("datatype of simple interest : ", type(simple_interest)) #implicit conversion
a = 10
b = "Hello"
print(a+b)
c = 'Ram'
N = 3
print(c*N)
x = True
y = 10
print(x + 10)
m = False
n = 23
print(n – m)
Try It Yourself:
1) Take a Boolean value and add a string to it
2) Take a string and float number and try adding both
3) Take a Boolean and a float number and try adding both.
Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an object to required data type. We use the predefined functions like int(), float(),
str(), etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the data type of the objects.
Birth_day = 10
Birth_month = "July"
print("data type of Birth_day before type casting :", type(Birth_day))
print("data type of Birth_month : ", type(Birth_month))
Birth_day = str(Birth_day)
print("data type of Birth_day after type casting :",type(Birth_day))
Birth_date = Birth_day + ' ' + Birth_month
print("birth date of the student : ", Birth_date)
print("data type of Birth_date : ", type(Birth_date))
data type of Birth_day before type casting : <class 'int'>
data type of Birth_month : <class 'str'>
data type of Birth_day after type casting : <class 'str'>
birth date of the student : 10 July
data type of Birth_date : <class 'str'>
a = 20
b = "Apples"
print(str(a)+ b)
x = 20.3
y = 10
print(int(x) + y)
m = False
n = 5
print(bool(n)+ m)
Try it yourself
1) Take a Boolean value “False” and a float number “15.6” and perform the AND operation on both
2) Take a string “ Zero” and a Boolean value “ True” and try adding both by using the Bool() function.
3) Take a string “Morning “ and the float value “90.4” and try and add both of them by using the float() function. Perform the above mentioned
Try it Yourself in the lab and write down the observations to be discussed later in the class.
Exercises
Arithmetic
Write a program that prints out the results of at least one calculation for each of the basic operations: addition, subtraction, multiplication,
division, and exponents.
Order of Operations
Find a calculation whose result depends on the order of operations.
Print the result of this calculation using the standard order of operations.
Use parentheses to force a nonstandard order of operations. Print the result of this calculation.
Long Decimals
On paper, 0.1+0.2=0.3. But you have seen that in Python, 0.1+0.2=0.30000000000000004.
Find at least one other calculation that results in a long decimal like this.
# Ex 2.8 : Arithmetic
a = 6
b = 5
print("a + b = ", end='')
o = a+b
print(o)
# Ex 2.9 : Order of Operations
result = (3*4)+2
print('The result of the calculation of (3*4)+2', result, sep=' = ')
# Ex 2.10 : Long Decimals
print(3.125 / 0.2)
Challenges
Neat Arithmetic
Store the results of at least 5 different calculations in separate variables. Make sure you use each operation at least once.
Print a series of informative statements, such as "The result of the calculation 5+7 is 12."
Neat Order of Operations
Take your work for "Order of Operations" above.
Instead of just printing the results, print an informative summary of the results.
Show each calculation that is being done and the result of that calculation. Explain how you modified the result using parentheses.
Long Decimals - Pattern
On paper, 0.1+0.2=0.3. But you have seen that in Python, 0.1+0.2=0.30000000000000004.
Find a number of other calculations that result in a long decimal like this. Try to find a pattern in what kinds of numbers will result in long
decimals.
# Challenge: Neat Arithmetic
# Put your code here
# Challenge: Neat Order of Operations
# Put your code here
# Challenge: Long Decimals - Pattern
# Put your code here
Comments
As you begin to write more complicated code, you will have to spend more time thinking about how to code solutions to the problems you
want to solve.
Once you come up with an idea, you will spend a fair amount of time troubleshooting your code, and revising your overall approach.
Comments allow you to write in English, within your program. In Python, any line that starts with a pound (#) symbol is ignored by the Python
interpreter.
Commenting one line at a time
# Performing addition of two variables
a = 12 # defining variable a and its value
b = 10 # defining variable b and its value
addition = a + b # Addition logic definition
print(addition) # getting output
22
Commenting Multiple lines at a time
"""
These lines are commented to perform addition task
We will define two variables
we will apply addition logic
we will print the output
"""
a = 12
b = 10
addition = a + b
print(addition)
22
What makes a good comment?
It is short and to the point, but a complete thought. Most comments should be written in complete sentences.
It explains your thinking, so that when you return to the code later you will understand how you were approaching the problem.
It explains your thinking, so that others who work with your code will understand your overall approach to a problem.
It explains particularly difficult sections of code in detail.
When should you write a comment?
When you have to think about code before writing it.
When you are likely to forget later exactly how you were approaching a problem.
When there is more than one way to solve a problem.
When others are unlikely to anticipate your way of thinking about a problem.
Writing good comments is one of the clear signs of a good programmer. If you have any real interest in taking programming seriously, start
using comments now. You will see them throughout the examples in these notebooks.
Exercises
First Comments
Choose the longest, most difficult, or most interesting program you have written so far. Write at least one comment in your program.
# Ex 2.10 : First Comments
# put your code here
Overall Challenges
We have learned quite a bit so far about programming, but we haven't learned enough yet for you to go create something. In the next
notebook, things will get much more interesting, and there will be a longer list of overall challenges.
# Overall Challenge
# Put your code here
# I learned how to strip whitespace from strings.
name = '\t\teric'
print("I can strip tabs from my name: " + name.strip())
Loading [MathJax]/jax/output/CommonHTML/fonts/TeX/fontdata.js