Hello
We will now get down to business and learn the basics or Python.
Create a new Quarto Document. Delete all the irrelevant information. Put your name in the preamble.
Make sure that you replace /opt/anaconda3/bin/python
with your python path:
This is how we add Python chunks and text
---
title: "Lab3"
author: "Your Name"
date: "2024-11-05"
format: html
toc: true
embed-resources: true
---
# Introduction
Today 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
```
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
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.
What type of variables are number
and boolean
?
They are both strings because they have quotes
Variables can contain letters, numbers, and underscores.
Variables cannot start with a number, e.g., “3message”.
A variable cannot have two unconnected words, e.g., “message 3”
Variables should not use Python keywords as variable names: e.g.: “False”, “None”, “True”, “and”, etc.
Store “Hello World” in a variable called “message” and print it.
Strings are sets of characters.
Either single or double quotes can contain strings
We can easily combine or concatenate strings.
Indexing allows you to access individual characters in a string.
Python strings are zero-indexed: the first character is at index 0, the second at index 1, and so on.
You can use positive or negative indices:
Indexing allows you to access individual characters in a string.
Python strings are zero-indexed: the first character is at index 0, the second at index 1, and so on.
You can use positive or negative indices:
We can also extract more than one character.
String slicing is a way to extract a portion (substring) of a string by specifying a range of indices.
string[start:end]
Important Points
0
, the second character 1
, and so on.Advanced Slicing: Omitting Start or End
text[:5]
- From the beginning to index 5 (exclusive).text[6:]
- From index 6 to the end of the stringWhy Use String Slicing?
To extract specific parts of a string (e.g. first few characters or a substring)
We can see if specific strings are within our strings.
We can do that in the following way:
We can easily replace a string by using .replace
We can count how many times a substring can be found within a bigger string in the following way:
Strings can be split into substrings when a repeated character separates them.
The split function returns a set of substrings.
Notice that the punctuation is still there.
We can turn lower case strings into upper case strings:
We can turn lower case strings into upper case strings:
The .strip()
method removes leading and trailing whitespace (spaces, tabs, or newlines).
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
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 |
———– | — | — | — | — | — | — | — | — | — | — | — | — | — | — |
We can mix strings and numbers in the following way.
The most common white space characters are spaces, tabs, and newlines.
\t
is the standard way to mark tabs in Python.
We can split two lines using \n
We can move strings on a new line.
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.'"
Dealing with numbers is straightforward in Python.
Dealing with numbers is straightforward in Python.
Dealing with numbers is straightforward in Python.
Floating-point numbers refer to any number with a decimal point.
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.
Write a program that prints out the results of one calculation for each of the basic operations: addition, subtraction, multiplication, division, and exponents.
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
A Boolean is a logical data type with only true or false values.
This is what they look like in Python.
This is what happens when I print them.
This is what happens after we perform the following operation.
True and True is True
True and False is False
This is what happens after we perform the following operation.
False and False is False
We can also obtain booleans in the following way:
We can have even more complex Booleans.
To check if a variable is Boolean or not, we can perform:
This is different from:
<class 'float'>
<class 'str'>
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:
We can concatenate strings:
It is essential to clarify the distinction between expressions and statements.
Expression - piece of code that produces a value when evaluated.
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
if
elif
else
This is what the syntax of conditional statements looks like:
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.
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.
if
and elif
if
and elif
Use if
:
if
and elif
Use elif
:
elif
block will be checked only if the preceding if
and elif
conditions were falseif
vs. elif
if
(independent conditions)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.
if
vs. elif
elif
(dependent conditions)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.
if
vs. elif
Using elif
(dependent conditions)
Here is when elif
gets executed
Wear a windbreaker.
elif
block will be checked only if the preceding if
and elif
conditions were falseelse
statementThe 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.
else
statementPython
Take an umbrella.
if
statement checks if the weather is “rainy”. If true, it prints “Take an umbrella.”.elif
checks if the weather is “windy”. If true, it prints “Wear a windbreaker.” but only if the previous if
condition was false.elif
checks if the weather is “sunny”. If true, it prints “Wear sunglasses.” but only if all previous conditions were false.else
statementPython
Take an umbrella.
else
statement catches any other weather conditions not covered by the if and elif statements and prints “Check weather & dress well”.Write a program using if
, elif
, and else
that prints a letter grade for students.
Here are the rules:
Let’s start with grade=92
This is how we can write this:
Note that you could potentially write this only with if
statements.
This, however, would require checking each condition independently.
This approach is less efficient as it does not take advantage of the mutually exclusive nature of the elif
conditions.
What if the grade was 72?
What if the grade was 72?
Understanding Logical Operations:
Key Takeaways:
if
, elif
, else
) control the flow of the program.Importance of Structure
Popescu (JCU): Lecture 3