L3: Variables, Strings, Numbers, and Conditional Statements

Bogdan G. Popescu

John Cabot University

Introduction

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:

  • see the address of your Python interpreter in R (also see lecture 1)
---
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)
```

Introduction

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
```

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 = 3
print(number)
3
Python
boolean = True
print(boolean)
True

Variables

Python
message = "Hello"
number = 3
boolean = 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.

Python
message = "Hello"

message3 = "Hello"

message_3 = "Hello"

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.

Variables

Exercise

Store “Hello World” in a variable called “message” and print it.

Python
message = "Hello World"
print(message)
Hello World

Variables

Strings

Strings are sets of characters.

Either single or double quotes can contain strings

Python
message1 = "Hello"
message2 = 'Hello'

Let us now print the messages:

Python
print(message1)
Hello
Python
print(message2)
Hello

Variables

Combining Strings

We can easily combine or concatenate strings.

Python
message1 = "Hello,"
message2 = "world!"
combined_message = message1 + " " + message2
print(combined_message)
Hello, world!

Variables

String Indexing

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:

  • Positive Indexing: Starts from the beginning (left to right).
  • Negative Indexing: Starts from the end (right to left).
Python
message = "Hello"
first_char = message[0]
first_char
'H'

Variables

String Indexing

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:

  • Positive Indexing: Starts from the beginning (left to right).
  • Negative Indexing: Starts from the end (right to left).
Python
last_char = message[-1]
last_char
'o'

Variables

String Indexing

We can also extract more than one character.

Python
message = "Hello"
first_2char = message[:2]
first_2char
'He'
Python
last_2char = message[-2:]
last_2char
'lo'

Variables

String Slicing

String slicing is a way to extract a portion (substring) of a string by specifying a range of indices.

  • A string comprises individual characters, each with its own index.
  • Syntax: string[start:end]
    • start: The index where slicing begins (inclusive)
    • end: The index where slicing ends (exclusive)
Python
# Define a string
message = "Hello"

# Slice from index 0 to 3 (exclusive)
substring = message[0:3]
substring
'Hel'

Variables

String Slicing

Important Points

  • Indexing starts at 0: The first character has an index of 0, the second character 1, and so on.
  • End is exclusive: the slicing stops just before the end index.

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 string

Variables

String Slicing

Why Use String Slicing?

To extract specific parts of a string (e.g. first few characters or a substring)

Python
# Define a string
message = "Hello"
# Slice from index 0 to 3 (exclusive)
substring = message[0:3]
print(substring)
Hel

We can also extract the first and the last character:

Python
message[0]
'H'
message[-1]
'o'

String Operations

Finding Substrings

We can see if specific strings are within our strings.

We can do that in the following way:

Python
sentence = "John, Anna, and Emma are in this class"
john_present = 'John' in sentence
print(john_present)
True
Python
sentence = "John, Anna, and Emma are in this class"
john_present = 'Marc' in sentence
print(john_present)
False

String Operations

Replacing Substrings

We can easily replace a string by using .replace

Python
sentence = "John, Anna, and Emma are in this class"
new_sentence = sentence.replace('John', 'Marc')
print(new_sentence)
Marc, Anna, and Emma are in this class

String Operations

Counting Substrings

We can count how many times a substring can be found within a bigger string in the following way:

Python
sentence = "John, Anna, and Emma are in this class. John enjoys this class"
no_john = sentence.count('John')
print(no_john)
2

String Operations

Splitting strings

Strings can be split into substrings when a repeated character separates them.

The split function returns a set of substrings.

Python
sentence = "John, Anna, and Emma are in this class"
new_sentence = sentence.split(' ')
print(new_sentence)
['John,', 'Anna,', 'and', 'Emma', 'are', 'in', 'this', 'class']

Notice that the punctuation is still there.

String Operations

Strings: Lower Case to Upper Case and the Opposite

We can turn lower case strings into upper case strings:

Python
group = "John, Anna, Emma, Mark"
uppercase_group = group.upper()
print(uppercase_group)
JOHN, ANNA, EMMA, MARK

We can turn upper-case strings into lower strings:

Python
lowercase_group = uppercase_group.lower()
print(lowercase_group)
john, anna, emma, mark

String Operations

Strings: Lower Case to Upper Case and the Opposite

We can turn lower case strings into upper case strings:

We can also have every word start with an uppercase.

Python
cap_group = uppercase_group.title()
print(cap_group)
John, Anna, Emma, Mark

String Operations

Removing Whitespace

The .strip() method removes leading and trailing whitespace (spaces, tabs, or newlines).

Python
message = "   Hello"
stripped_message = message.strip()
print(stripped_message)
Hello

String Operations

Finding Substrings

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 = 23
print("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
#Addition
print(1+2)
3
Python
#Subtraction
print(1-2)
-1
Python
#Multiplication
print(1*2)
2

Numbers

Calculations

Dealing with numbers is straightforward in Python.

Python
#Division
print(1/2)
0.5
Python
#Exponentiation
print(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 values
a = 10
b = 5
#Performing the calculation
addition = a + b
subtraction = a - b
multiplication = a * b
division = a/b
exponentiation = 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 = True
y = 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.

False and False is False

Python
y and y
False

Logical Operations

Booleans

We can also obtain booleans in the following way:

Python
3 > 1
True
Python
3 >= 1
True
Python
3 < 1
False
Python
z = 1
z == 1
True

Logical Operations

Booleans

We can have even more complex Booleans.

Python
grade = 68
grade_desired = 80
type_student = "exchange student"

(type_student == 'exchange student') and (grade < grade_desired)
True

Logical Operations

Booleans

To check if a variable is Boolean or not, we can perform:

Python
x = True
type(x)
<class 'bool'>

This is different from:

Python
y = 1
type(y)
<class 'int'>
z1 = 1.0
type(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 strings
3 * '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 strings
3 + 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 = 12
y = -1
z = 0

w = 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 = 1
b = 2.0
c = '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 True
elif another_condition:
    # code to execute if another_condition is True
else:
    # code to execute if all conditions are False

Example: Simple If Statement

Python
age = 18

if 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 = 30

if 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.

Python
score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: D")
Grade: B

Conditional Statements

elif statements

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 true
elif condition2:
    # This block will execute if condition1 is false and condition2 is true
elif 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 true
if 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 true
elif condition2:
    # This block will execute if condition1 is false and condition2 is true
elif 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’
  • If the score is less than 60, the grade is ‘F’

Let’s start with grade=92

Other Operations

Exercise:

This is how we can write this:

Python
grade = 92

if grade >= 90:
  print("A")
elif grade >= 80:
  print("B")
elif grade >= 70:
  print("C")
elif grade >= 60:
  print("D")
else:
  print("F")
A

Other Operations

Exercise:

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.

Other Operations

Exercise:

What if the grade was 72?

Other Operations

Exercise:

What if the grade was 72?

Python
grade = 72

if grade >= 90:
  print("A")
elif grade >= 80:
  print("B")
elif grade >= 70:
  print("C")
elif grade >= 60:
  print("D")
else:
  print("F")
C

Conclusion

Understanding Logical Operations:

  • Logical operations are fundamental in programming and allow for decision-making based on conditions.

Key Takeaways:

  • Expressions are evaluated to produce values.
  • Variables store data and reference objects.
  • Conditional statements (if, elif, else) control the flow of the program.

Importance of Structure

  • Using conditions optimizes code by ensuring only relevant conditions are evaluated.