---title: "Lab3"author: "Your Name"date: "2024-11-05"format: htmltoc: trueembed-resources: true---# IntroductionToday we learn Python. ```{r}reticulate::use_python("/opt/anaconda3/bin/python", required = TRUE)```The following is a Python chunk.```{python filename="Python"}#Here goes the Python Code```The following is an R chunk.```{r filename="R"}#Here goes the R Code```
Introduction
In this section, we will learn how to store information in variables.
We will explore different data types, including strings and numerical data types.
A variable holds at least one value. For example, the following are variables
Python
message ="Hello"print(message)
Hello
Python
number =3print(number)
3
Python
boolean =Trueprint(boolean)
True
Variables
Python
message ="Hello"number =3boolean =True
All these variables hold individual values: Hello, 3, TRUE
The value Hello is a string object in Python.
The value 3 is a numeric object.
The value TRUE is a Boolean object.
Variables
Python
message ="Hello"number ="3"boolean ="True"
What type of variables are number and boolean?
They are both strings because they have quotes
Variables
Naming Rules
Variables can contain letters, numbers, and underscores.
The .find() method searches for the first occurrence of a substring within a string and returns its index. If the substring is not found, it returns -1
Python
sentence ="Python is fun!"index = sentence.find("fun")print(index)
10
Here is why the index is 10
Character
P
y
t
h
o
n
i
s
f
u
n
!
Index
0
1
2
3
4
5
6
7
8
9
10
11
12
13
———–
—
—
—
—
—
—
—
—
—
—
—
—
—
—
String Operations
Strings and Numbers
We can mix strings and numbers in the following way.
Python
number =23print("My favorite number is "+str(number) +".")
My favorite number is 23.
Strings
Dealing with Whitespace
The most common white space characters are spaces, tabs, and newlines.
No Spaces
Python
print("Hello World!")
Hello World!
Spaces (Tabs)
\t is the standard way to mark tabs in Python.
Python
print("\tHello World!")
Hello World!
Python
print("Hello\t world!")
Hello world!
Strings
Dealing with Whitespace
We can split two lines using \n
Spaces (New Lines)
We can move strings on a new line.
Python
print("Hello\n world!")
Hello
world!
Strings
Exercise
Store the following quote in a variable: “Never succumb to the temptation of bitterness.”
Add another variable: “Martin Luther King once said:”
Print the two variables together. Your response should look like:
"Martin Luther King once said: 'Never succumb to the temptation of bitterness.'"
Numbers
Calculations
Dealing with numbers is straightforward in Python.
Python
#Additionprint(1+2)
3
Python
#Subtractionprint(1-2)
-1
Python
#Multiplicationprint(1*2)
2
Numbers
Calculations
Dealing with numbers is straightforward in Python.
Python
#Divisionprint(1/2)
0.5
Python
#Exponentiationprint(1**2)
1
Numbers
Floating-Point numbers
Dealing with numbers is straightforward in Python.
Python
#"floor” division (rounds down to nearest whole number)print(1//2)
0
Floating-point numbers refer to any number with a decimal point.
Python
print(0.1+0.1)
0.2
Numbers
Exercise 1
Write a program that prints the result of one calculation for each of the basic operations: addition, subtraction, multiplication, division, and exponentiation.
Start with a=10 and b=5.
Then, create new objects: addition, subtraction, multiplication, division, exponentiation.
Numbers
Exercise 1
Write a program that prints out the results of one calculation for each of the basic operations: addition, subtraction, multiplication, division, and exponents.
Python
#Defining valuesa =10b =5#Performing the calculationaddition = a + bsubtraction = a - bmultiplication = a * bdivision = a/bexponentiation = a**b
Numbers
Exercise 1
Write a program that prints out the results of one calculation for each of the basic operations: addition, subtraction, multiplication, division, and exponents.
Addition: a + b = 15
Subtraction: a - b = 5
Multiplication: a * b = 50
Division: a / b = 2.0
Exponentiation: a**b = 100000
Logical Operations
Booleans
A Boolean is a logical data type with only true or false values.
This is what they look like in Python.
Python
x =Truey =False
This is what happens when I print them.
Python
print(x)
True
print(y)
False
Logical Operations
Booleans
This is what happens after we perform the following operation.
True and True is True
Python
x and x
True
True and False is False
Python
x and y
False
Logical Operations
Booleans
This is what happens after we perform the following operation.
To check if a variable is Boolean or not, we can perform:
Python
x =Truetype(x)
<class 'bool'>
This is different from:
Python
y =1type(y)
<class 'int'>
z1 =1.0type(z1)z2 ='1'type(z2)
<class 'float'>
<class 'str'>
Logical Operations
Expressions
An expression is a code that is executed upon evaluation.
For example, x=1 is not an expression that is evaluated but instead declared.
The following, for example, is an expression:
Python
-3+5*(120/12)
47.0
We can concatenate strings:
Python
# Concatenation of strings3*'Hello!'
'Hello!Hello!Hello!'
Logical Operations
Expressions vs. Statements
It is essential to clarify the distinction between expressions and statements.
Expression - piece of code that produces a value when evaluated.
The following example produces 28
Python
# Concatenation of strings3+5* (10/2)
28.0
Statement - a piece of code that performs an action but doesn’t necessarily return a value.
Example: x = 10 assigns the value 10 to the variable x
Logical Operations
Exercises
What is the value of w?
Python
x =12y =-1z =0w = x*2- y +1**z
What is the value of the variable c?
Python
a ='Hello'b ='World'c = a[:4] +'_'+ b
Logical Operations
Exercises
What is the value of the variable c?
Python
a =1b =2.0c ='7'd =str((3*a + b/0.5) /int(c))
Conditional Statements
Introduction
Conditional statements allow us to execute specific code based on certain conditions.
They are fundamental in controlling the flow of a program.
Common types of conditional statements in Python:
if
elif
else
Conditional Statements
Syntax of Conditional Statements
This is what the syntax of conditional statements looks like:
if condition:# code to execute if condition is Trueelif another_condition:# code to execute if another_condition is Trueelse:# code to execute if all conditions are False
Example: Simple If Statement
Python
age =18if age >=18:print("You are eligible to vote.")
You are eligible to vote.
Conditional Statements
Syntax of Conditional Statements
Example: If-Else Statement
This code checks the temperature. If it’s over 25, it prints that it’s a hot day; otherwise, it prints a different message.
Python
temperature =30if temperature >25:print("It's a hot day!")else:print("It's a pleasant day!")
It's a hot day!
Conditional Statements
Syntax of Conditional Statements
Example: If-Elif-Else Statement
The following code evaluates the score and prints the corresponding grade based on the defined ranges.
We can use elif statements when we want to check multiple conditions that are dependent on each other.
In that case, only one block should be executed among multiple conditions
The elif block will be checked if the preceding if or elif conditions are false.
Example:
if condition1:# This block will execute if condition1 is trueelif condition2:# This block will execute if condition1 is false and condition2 is trueelif condition3:# This block will execute if condition1 and condition2 are false and condition3 is true
Other Operations
Difference if and elif
Other Operations
Difference if and elif
Use if:
when you want to check multiple conditions independently of each other
When multiple conditions can be true simultaneously, and you want to execute the corresponding blocks for all true conditions.
if condition1:# This block will execute if condition1 is trueif condition2:# This block will execute if condition2 is true (independently of condition1)
Other Operations
Difference if and elif
Use elif:
when you want to check multiple conditions dependent on each other
when only one block should be executed among multiple conditions
the elif block will be checked only if the preceding if and elif conditions were false
if condition1:# This block will execute if condition1 is trueelif condition2:# This block will execute if condition1 is false and condition2 is trueelif condition3:# This block will execute if condition1 and condition2 are false and condition3 is true
Other Operations
Example use if vs. elif
Using if (independent conditions)
weather ="rainy"if weather =="rainy":print("Take an umbrella.")if weather =="windy":print("Wear a windbreaker.")if weather =="sunny":print("Wear sunglasses.")
Take an umbrella.
if the weather is rainy, it will print “Take an umbrella.”
The other conditions will still be checked, but only the block for the true condition will be executed.
Other Operations
Example use if vs. elif
Using elif (dependent conditions)
weather ="rainy"if weather =="rainy":print("Take an umbrella.")elif weather =="windy":print("Wear a windbreaker.")elif weather =="sunny":print("Wear sunglasses.")
Take an umbrella.
only the block for the first condition will execute
if weather is “rainy”, it will print “Take an umbrella.” and then skip all subsequent elif blocks.
Other Operations
Example use if vs. elif
Using elif (dependent conditions)
Here is when elif gets executed
weather ="windy"if weather =="rainy":print("Take an umbrella.")elif weather =="windy":print("Wear a windbreaker.")elif weather =="sunny":print("Wear sunglasses.")
Wear a windbreaker.
Once again, the elif block will be checked only if the preceding if and elif conditions were false
Other Operations
The else statement
The else statement can define a block of code to be executed if none of the preceding if or elif conditions are true.
It is a catch-all for any cases not covered by previous conditions.
Thus, use else to specify a code block if the preceding conditions are false.
weather ="rainy"if weather =="rainy":print("Take an umbrella.")elif weather =="windy":print("Wear a windbreaker.")elif weather =="sunny":print("Wear sunglasses.")else:print("Check weather & dress well.")
Other Operations
The else statement
Python
weather ="rainy"if weather =="rainy":print("Take an umbrella.")elif weather =="windy":print("Wear a windbreaker.")elif weather =="sunny":print("Wear sunglasses.")else:print("Check weather & dress well")
Take an umbrella.
The if statement checks if the weather is “rainy”. If true, it prints “Take an umbrella.”.
The first elif checks if the weather is “windy”. If true, it prints “Wear a windbreaker.” but only if the previous if condition was false.
The second elif checks if the weather is “sunny”. If true, it prints “Wear sunglasses.” but only if all previous conditions were false.
Other Operations
The else statement
Python
weather ="rainy"if weather =="rainy":print("Take an umbrella.")elif weather =="windy":print("Wear a windbreaker.")elif weather =="sunny":print("Wear sunglasses.")else:print("Check weather & dress well")
Take an umbrella.
The else statement catches any other weather conditions not covered by the if and elif statements and prints “Check weather & dress well”.
Other Operations
Exercise:
Write a program using if, elif, and else that prints a letter grade for students.
Here are the rules:
If the score is 90 or above, the grade is ‘A’
If the score is 80 or above but less than 90, the grade is ‘B’
If the score is 70 or above but less than 80, the grade is ‘C’
If the score is 60 or above but less than 70, the grade is ‘D’