L3: Variables, Strings, Numbers, and Conditional Statements

Bogdan G. Popescu

John Cabot University

Introduction

In this section, we will learn how to store information in variables

We will learn about different data types including strings and numerical data types

A variable holds at least one value.

For example, the following are all variables

message = "Hello"
print(message)
Hello
number = 3
print(number)
3
boolean = True
print(boolean)
True

Variables

message = "Hello"
number = 3
boolean = True

All these variables have one value individually: 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

message = "Hello"
number = "3"
boolean = "True"

What type of variables are number and boolean?

They are both strings as indicated by the quotes

Variables

Naming Rules

Variables can contain letters, numbers, and underscores.

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 variable called “message” and print it.

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

Variables

Strings

Strings are sets of characters

Strings can be contained by either single or double quotes

message1 = "Hello"
message2 = 'Hello'

Let us now print the messages:

print(message1)
Hello
print(message2)
Hello

Variables

Combining Strings

We can easily combine or concatenate strings

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: 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).
message = "Hello"
first_char = message[0]
first_char
'H'
last_char = message[-1]
last_char
'o'

Variables

String Indexing

We can also extract more than one character

message = "Hello"
first_2char = message[:2]
first_2char
'He'
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 is made up of 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)
# 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 (like the first few characters, or a substring).
# Define a string
message = "Hello"
# Slice from index 0 to 3 (exclusive)
substring = message[0:3]  # Output: 'Hello'

We can also extract the first and the last character:

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

String Operations

Finding Substrings

We can see if specific strings are within out strings.

We can do that in the following way:

sentence = "John, Anna, and Emma are in this class"
john_present = 'John' in sentence
print(john_present)
True
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

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:

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 in substrings when they are separated by a repeated character.

The split function returns a set of substrings

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 punctuation is still there.

String Operations

Strings: Lower Case to Upper Case and the Opposite

We can turn lower case strings to upper case strings:

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

We can turn upper case strings to upper lower strings:

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

And we can go back to the original format:

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

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

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.

number = 23
print("My favorite number is " + str(number) + ".")
My favorite number is 23.

Strings

Dealing with Whitespace

The most common type of white space characters are: spaces, tabs, and newlines.

  • No Spaces
print("Hello World!")
Hello World!
  • Spaces (Tabs)

\t is the common way to mark tabs in python

print("\tHello World!")
    Hello World!
print("Hello\t world!")
Hello    world!

Strings

Dealing with Whitespace

We can split two line using \n

  • Spaces (New Lines)

We can move strings on a new line

print("Hello\n world!")
Hello
 world!

Strings

Exercise

Store the following quote in a variable: “Never succumb to the temptation of bitterness.”

Add the introduction: “Martin Luther King once said:”

Print the introduction and quote. Your response should look like:

"Martin Luther King once said: 'Never succumb to the temptation of bitterness.'"

Strings

Exercise Answer

Store the following quote in a variable: “Never succumb to the temptation of bitterness.”

Add the introduction: “Martin Luther King once said:”

Print the introduction and quote. Your response should look like:

introduction = "Martin Luther King once said:"
quote= "'Never succumb to the temptation of bitterness.'"

introduction + " " + quote
"Martin Luther King once said: 'Never succumb to the temptation of bitterness.'"

Numbers

Calculations

Dealing with numbers is straightforward in python.

#Addition
print(1+2)
3
#Subtraction
print(1-2)
-1
#Multiplication
print(1*2)
2
#Division
print(1/2)
0.5
#Exponentiation
print(1**2)
1

Numbers

Floating-Point numbers

Dealing with numbers is straightforward in python.

#"floor” division (rounds down to nearest whole number)
print(1//2)
0

Floating-point numbers refer to any number with a decimal point.

print(0.1+0.1)
0.2

Numbers

Exercise 1

Write a program that prints out the results one calculation for each of the basic operations: addition, subtraction, multiplication, division, and exponents.

Start off 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 one calculation for each of the basic operations: addition, subtraction, multiplication, division, and exponents.

#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 one calculation for each of the basic operations: addition, subtraction, multiplication, division, and exponents.

#Printing the result
print("Addition: a + b = " + str(addition))
print("Subtraction: a - b = " + str(subtraction))
print("Multiplication: a * b = " + str(multiplication))
print("Division: a / b = " + str(division))
print("Exponentiation: a**b = " + str(exponentiation))
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 that can have only the values true or false.

This is what they look like in python

x = True
y = False

This is what happens when I print them

print(x)
True
print(y)
False

Logical Operations

Booleans

This is what happens after I perform the following operation

True and True is True

x and x
True

True and False is False

x and y
False

False and False is False

y and y
False

Logical Operations

Booleans

We can also obtain booleans in the following way:

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

Logical Operations

Booleans

We can have even more complex Booleans

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

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

Logical Operations

Booleans

In order to check if a variable is Boolean or not, we can perform:

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

This different from:

y = 1
type(y)
<class 'int'>

or

z1 = 1.0
type(z1)
z2 = '1'
type(z2)
<class 'float'>
<class 'str'>

Logical Operations

Expressions

An expression is a code, which is executed upon evaluation.

For example x=1 is not en expression that is evaluated, but rather, something that is declared.

The following for example is an expression:

- 3 + 5*(120/12)
47.0

We can concatenate strings:

# Concatenation of strings
3 * 'Hello!'
'Hello!Hello!Hello!'

Logical Operations

Expressions vs. Statements

It is important to clarify the distinction between expressions and statements.

Expression - piece of code that produces a value when evaluated.

The following example produces 28

# Concatenation of strings
3 + 5 * (10 / 2)
28.0

Statement - 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?

x = 12
y = -1
z = 0

w = x*2 - y + 1**z

What is the value of the variable c?

a = 'Hello'
b = 'World'
c = a[:4] + '_' + b

Logical Operations

Exercises

What is the value of the variable c?

a = 1
b = 2.0
c = '7'

d = str((3*a + b/0.5) / int(c))

Other Operations

Conditionals

An if statement tests for a condition and then responds to that condition

If the condition is true, then that action gets carried out.

ph = 7.5

if ph > 7:
    print('base')
base

If the condition is false, then that action does not get carried out (nothing gets printed)

ph = 7
if ph > 7:
    print('base')

Other Operations

Conditionals

We could have multiple conditions at the same time

ph = 7.5
if ph > 7:
    print('base')
if ph < 7:
    print('acid')
base

or

ph = 7
if ph > 7:
    print('base')
if ph < 7:
    print('acid')
if ph == 7:
    print('neutral')
neutral

Other Operations

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 were 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 at the same time 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 execute.

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 be used to define a block of code to be executed if none of preceding if or elif conditions are true.

It is a catch-all for any cases not covered by previous conditions

Thus, use else when you want to specify a block fo code 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

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

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 wite this:

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 mutual exclusive nature of the elif conditions.

Other Operations

Exercise:

What if the grade was 72?

Other Operations

Exercise:

What if the grade was 72?

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 - fundamental in programming, allowing 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.