Why Python:
print("Hello Python 101")
#as comment
#print("Hello Python 101")
QUESTION 1
Using the Practice Lab find the result of executing print("Hello\nWorld!")
statement
print("Hello\nWorld!")
QUESTION 2
what is the output of executing the following statement: # print('Hello World!')
# print('Hello World!')
1: Integer -> Int
2.34 : Real number -> Float
"cevi": Words -> Str
TRUE/FALSE: Boolean -> Bool
QUESTION 1
What is the type of the following int(1.0)?
int(1.0)
QUESTION 2
Enter the code to convert the number 1 to a Boolean ?
bool(1)
bool(0)
Operators
40+40+100
10-50
10*8
20/5
Variables
my_variable=100
print(my_variable)
total=1+2+19
print(total)
my_variable2=total/my_variable
print(my_variable2)
By the end of this notebook, you will have learned the basics of Python, including writing some basic commands, understanding object types, and some simple operations!
A statement or expression is an instruction the computer will run or execute. Perhaps the simplest program you can write is to print a statement in Python.
How do we know that Python 3 is running? Take a look in the top-right hand corner of this notebook. You should see "Python 3"!
In addition to writing code, note that it is customary to comment your code to help describe what it does. Not only does this help other people understand your code, it can also serve as a reminder to you of what your code does. (This is especially true when you write some code and then come back to it weeks or months later.)
To write comments in your Python code, use the hash symbol (#) before writing your comment. When you run the code Python will ignore everything after the # in that line.
print('Hello Python 101')
#this my comment
#print('Hi')
Great! After executing the cell above, you should notice that "this is my comment did not appeared in the output, because it was a comment (and thus ignored by Python).
The second line was also not executed because print('Hi')
was preceded by a hash symbol (#) as well!
Before continuing, it's important to note when things go wrong in Python, and we cause errors.
There are many kinds of errors, and you do not need to memorize the various types of errors. Instead, what's most important is know what the error messages mean.
For example, if you spell print as frint, you will get an error message.
frint("Hello World!")
The error message tells you (1) where the error occurred, and (2) what kind of error it was. Here, Python attempted to run the function frint
, but could not determine what frint
-- since it is undefined.
No, Python is naive! Python will try to run the code line-by-line, and it will stop if it runs into an error.
print("This will be printed")
frint("This will cause an error")
print("This will NOT be printed")
More on errors later on in this course!
print()
function, print out the phrase: "hello world"¶print("hello world!")
print("Hello World") #print Hello World
You can have many different object types in Python, let's start with strings, integers and floats. Anytime you write words (text) in Python, you're using character strings (strings for short). Numbers, on the other hand, depend: numbers can be integers (like -1, 0, 100) or floats, which are real numbers (like 3.14, -42.0).
<a,align = "center"><img src = "https://ibm.box.com/shared/static/8zp0t4oh7kuzleudrszhkqukcup1708f.png" width = 600></a>
The following chart summarizes three data types for the last examples, the first column indicates the expression the second column indicates the data type
11 #integer
2.14 #float
"Hello Python 101" #character string
We can see the actual data type in python by using the type()
command
type(12)
type(2.14)
type("Hello Python 101")
type()
function, check the object type of 12.0
?¶type(12.0)
Here are some integers, integers can be negative or positive:
<a align = "center"><img src = "https://ibm.box.com/shared/static/19iqm3q5pvxzuwa22d5ihxcr6eftjl48.png" width = 600></a>
We can verify some of the above examples using the type command:
type(-1)
type(4)
type(0)
Floats are real numbers; they include the integers but also "numbers in-between the integers". Consider the numbers between 0 and one we can select numbers in-between them, these numbers are floats. Similarly, consider the numbers between 0.5 and 0.6. We can select numbers in-between them, these are floats as well. We can continue the process, zooming in for different numbers, of course, there is a limit, but it is quite small.
We can verify some of the above examples using the type command:
type(1.0)
type(0.5)
type(0.56)
You can change the type of the object in Python; this is called typecasting. For example, you can convert an integer into a float, as in 2 to 2.0.
type(2) #verify that this is an integer
float(2)
type(float(2))
Nothing really changes. If you cast a float to an integer, you must be careful. For example, if you cast the float 1.1 to 1 you will lose some information :
int(1.1)
If a string contains an integer value, you can convert it to an integer:
int('1')
You can also convert strings containing float values into float objects
float('1.2')
However, if we attempt to convert a string that contains a non-numerical value, we get an error:
int("A")
You can convert an int to a string:
str(1)
You can convert a float to a string
str(1.2)
Boolean is another important type in Python; a Boolean can take on two values. The first value is true, just remember we use an uppercase T:
True
Boolean values can also be false, with an uppercase F:
False
Using the type command on a Boolean value we obtain the term bool, this is short for Boolean
type(True)
type(False)
If we cast a Boolean true to an integer or float we will get a 1, if we cast a Boolean false to an integer or float. If we get a zero if you cast a 1 to a boolean, you get a true similarly, if you cast a 0 to a Boolean you get a false.
int(True)
bool(1)
bool(0)
float(True)
6 / 2
¶type(6/2)
6 // 2
? (Note the double slash //)¶type(6//2)
Expressions are operations that Python performs. For example, basic arithmetic operations like adding multiple numbers.
43 + 60 + 16 + 41
We can perform operations such as subtraction using the subtraction sign. In this case the result is a negative number.
50 - 60
We can use multiplication using an asterisk:
5 * 5
We can also perform division with the forward slash
25 / 5
25 / 6
We can use the double slash for integer division, where the result is rounded
25//5
25//6
What is 160 min in hours?
160.0/60.0
Python follows mathematical conventions when performing mathematical expressions. The following operations are in different order. In both cases Python performs multiplication, then addition to obtain the final result.
2 * 60 + 30
The expressions in the parentheses are performed first. We then multiply the result by 60, the result is 1920.
(30 + 2) * 60
We can also store our output in variables, so we can use them later on. For example:
x = 43 + 60 + 16 + 41
To return the value of x, we can simply run the variable as a command:
x
We can also perform operations on x
and save the result to a new variable:
y = x / 60
y
If we save something to an existing variable, it will overwrite the previous value:
x = x / 60
x
It's good practice to use meaningful variable names, so you don't have to keep track of what variable is what:
total_min = (43 + 42 )
total_min
total_hr = total_min / 60
total_hr
You can put this all into a single expression, but remember to use round brackets to add together the album lengths first, before dividing by 60.
total_hr = (43 + 42 + 57) / 60 # get total hours in a single expression
total_hr
x = 3 + 2 * 2
x
y = (3 + 2) * 2
y
z = x + y
z
String is a sequences of characters
QUICK PRACTICE LAB
QUESTION 1
Consider the following string:
Numbers="0123456"
how would you obtain the even elements ?
#Number[::2]
QUESTION 2 (1 point possible)
What is the result of the following line of code:
"0123456".find('1')
#1. Position
A string is contained within 2 quotes:
"Michael Jackson"
You can also use single quotes:
'Michael Jackson'
A string can be spaces and digits:
'1 2 3 4 5 6 '
A string can also be special characters :
'@#2_#]&*^%$'
We can print our string using the print statement:
print("hello!")
We can bind or assign a string to another variable:
Name= "Michael Jackson"
Name
It is helpful to think of a string as an ordered sequence. Each element in the sequence can be accessed using an index represented by the array of numbers:
<img src = "https://ibm.box.com/shared/static/esdu9w118rm1aldff7ff8c9b3kpjdazc.png" width = 600, align = "center"></a>
The first index can be accessed as follows:
print(Name[13])
We can access index 6:
print(Name[6])
Moreover, we can access the 13th index:
print(Name[13])
We can also use negative indexing with strings:
<img src = "https://ibm.box.com/shared/static/rmq8akevtt6uufox3xai7q2kqs4j9kan.png" width = 600, align = "center"></a>
The last element is given by the index -1:
print(Name[-1])
The first element can be obtained by index -15:
print(Name[-15])
We can find the number of characters in a string by using 'len', short for length:
len("Michael Jackson")
We can obtain multiple characters from a string using slicing, we can obtain the 0 to 4th and 8th to the 12th element:
</a>
Name[0:4]
Name[8:12]
We can also input a stride value as follows, with the '2' indicating that we are selecting every second variable:
</a>
Name[::2]
We can also incorporate slicing with the stride. In this case, we select the first five elements and then use the stride:
Name[0:5:2]
We can concatenate or combine strings by using the addition symbols, and the result is a new string that is a combination of both:
Statement = Name + "is the best"
Statement
To replicate values of a string we simply multiply the string by the number of times we would like to replicate it. In this case, the number is three. The result is a new string, and this new string consists of three copies of the original string:
3*"Michael Jackson "
You can create a new string by setting it to the original variable. Concatenated with a new string, the result is a new string that changes from Michael Jackson to “Michael Jackson is the best".
Name= "Michael Jackson"
Name= Name+" is the best"
Name
Back slashes represent the beginning of escape sequences. Escape sequences represent strings that may be difficult to input. For example, back slash "n" represents a new line. The output is given by a new line after the back slash "n” is encountered:
print(" Michael Jackson \n is the best" )
Similarly, back slash "t" represents a tab:
print(" Michael Jackson \t is the best" )
If you want to place a back slash in your string, use a double back slash:
print(" Michael Jackson \\ is the best" )
We can also place an "r" before the string to display the backslash:
print(r" Michael Jackson \ is the best" )
There are many string operation methods in Python that can be used to manipulate the data. We are going to use some basic string operations on the data.
Let's try with the method "upper"; this method converts upper case characters to lower case characters:
A="Thriller is the sixth studio album"
print("before upper:",A)
B=A.upper()
print("After upper:",B)
The method replaces a segment of the string, i.e. a substring with a new string. We input the part of the string we would like to change. The second argument is what we would like to exchange the segment with, and the result is a new string with the segment changed:
A="Michael Jackson is the best"
B=A.replace('Michael', 'Janet')
B
The method "find" finds a sub-string. The argument is the substring you would like to find, and the output is the first index of the sequence. We can find the sub-string "jack" or "el".
</a>
Name="Michael Jackson"
Name.find('el')
Name.find('Jack')
If the sub-string is not in the string then the output is a negative one. For example, the string 'Jasdfasdasdf' is not a substring:
Name.find('Jasdfasdasdf')
A="1"
A="1"
A
B="2"
B="2"
B
C=A+B
C=A+B
C
D="ABCDEFG"
print(D[:3])
E='clocrkr1e1c1t'
print(E[::2])
print(" \\" )
F="You are wrong"
F.upper()
G="Mary had a little lamb Little lamb, little lamb Mary had a little lamb \
Its fleece was white as snow And everywhere that Mary went Mary went, Mary went \
Everywhere that Mary went The lamb was sure to go"
G.find('snow')
G.replace("Mary","Bob")
3 + 2 * 2
name = 'Lizz'
print(name[0:2])
var = '01234567'
print(var[::2])
'1'+'2'
myvar = 'hello'
myvar.upper()
Cheers!
/itsmecevi