Hello
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.
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.
What type of variables are number and boolean?
They are both strings as indicated by the 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 variable called “message” and print it.
Strings are sets of characters
Strings can be contained by either single or double quotes
We can easily combine or concatenate strings
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:
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?
We can see if specific strings are within out 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 in substrings when they are separated by a repeated character.
The split function returns a set of substrings
Notice that punctuation is still there.
We can turn lower case strings to upper case strings:
We can turn upper case strings to upper lower 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 type of white space characters are: spaces, tabs, and newlines.
\t
is the common way to mark tabs in python
We can split two line 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 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.'"
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:
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 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
Write a program that prints out the results one calculation for each of the basic operations: addition, subtraction, multiplication, division, and exponents.
Write a program that prints out the results 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 that can have only the values true or false.
This is what they look like in python
This is what happens when I print them
This is what happens after I perform the following operation
True and True is True
True and False is False
False and False is False
We can also obtain booleans in the following way:
We can have even more complex Booleans
In order to check if a variable is Boolean or not, we can perform:
This different from:
or
<class 'float'>
<class 'str'>
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:
We can concatenate strings:
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
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
An if statement tests for a condition and then responds to that condition
If the condition is true, then that action gets carried out.
If the condition is false, then that action does not get carried out (nothing gets printed)
We could have multiple conditions at the same time
base
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
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 execute.
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 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.
else
statementweather = "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.
else
statementweather = "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.
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 wite 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 mutual 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