Lecture 2 : Strings & Conditional Statements | Python Full Course
Introduction to Chapter 2: Strings and Conditional Statements
Overview of Chapter 2
- The session introduces Chapter 2, focusing on strings in Python and their functionalities, along with conditional statements which are fundamental to the language.
- All lectures in this Python series are available on the channel's playlist, and notes/slides can be downloaded from the description box.
Understanding Strings
- Strings are defined as a data type that stores a sequence of characters, which can range from single characters to entire sentences or paragraphs.
- Three methods for creating strings were previously discussed; an example is provided using VS Code where a variable named
string_oneis created using double quotes.
Creating Strings with Different Quotes
- Strings can also be created using single quotes or triple quotes. For instance,
string_twocan store a single word within single quotes.
- Triple quotes allow for multi-line strings; however, double quotes are commonly used due to their prevalence in other programming languages.
Importance of Different Quote Types
- The necessity for different types of quotes arises when including apostrophes within strings. For example, if writing "This is my college tutorial," enclosing it in single quotes would confuse Python about where the string starts and ends.
Handling Apostrophes in Strings
- To avoid confusion when needing an apostrophe inside a string enclosed by single quotes, one should use double quotes instead. This allows valid string creation without errors.
Working with Multi-Line Strings
Printing Multiple Sentences
- When attempting to print multiple sentences on separate lines within a string, simply adding new lines directly will result in an error since Python does not recognize line breaks as valid syntax.
Escape Sequence Characters
- Escape sequence characters are special characters used for formatting purposes such as inserting tabs or new lines into strings. They cannot be added directly like regular text.
Using Escape Sequences Effectively
Implementing New Lines and Tabs
- To create new lines within printed output, one can use
n, which signifies a new line. This allows control over how text appears when printed.
Example of Tab Spaces
- Similarly, tab spaces can be introduced using
t, allowing better formatting between sentences or elements within the output.
Concatenate Strings in Python
Understanding Concatenation
- The operation discussed is called "concatenate," which, despite sounding complex, is straightforward. It involves adding two strings together in Python, similar to how numbers are added in mathematics.
- In Python, the plus operator (+) is used to concatenate two strings. For example, if we create
string_oneandstring_two, we can simply writestring_one + string_twoto get their concatenated output.
- The result of concatenation can be stored in a new variable (e.g.,
final_string) for further use. This allows us to keep the combined version of the strings.
Finding String Length
- Another operation that can be performed is finding the length of a string using the built-in
len()function. Functions will be explored in detail later; for now, they are seen as magical words that perform specific operations.
- To find the length of a string, you can write
len(string_name)within a print statement or store it in a variable (e.g.,length_one).
Example Outputs
- When printing lengths of two strings (
string_oneandstring_two), we see outputs like 4 for "own" and 7 for "college."
- If additional spaces are included during concatenation (e.g., between "own" and "college"), this space counts towards the total character count when calculating length.
Important Considerations
- Spaces are counted when determining string length; thus, it's crucial not to overlook them as they contribute to the overall character count.
- Special characters and digits also count towards string length. This includes symbols like percentages or dollar signs.
Indexing Characters
- Each character in a string has an index starting from zero. This means that accessing characters follows zero-based indexing rather than one-based indexing commonly found elsewhere.
- To access specific characters by their index, you can use square brackets with the string name followed by the desired index number (e.g.,
string_name).
Practical Examples
- By creating a sample string (like "own college") and accessing its characters via indices (0 for 'o', 1 for 'w', etc.), users learn how to retrieve individual characters effectively.
- Accessing spaces through indexing demonstrates that even non-visible characters have defined positions within strings.
Understanding String Manipulation in Python
Indexing and Assignment Limitations
- Strings in Python are immutable, meaning you cannot change a specific character at a given index. Attempting to do so results in an error indicating that string objects do not support item assignment.
- You can access characters by their index but cannot modify them directly. This is crucial for understanding how strings work in Python.
Slicing: A Key Concept
- Slicing allows you to access parts of a string, which is particularly useful when dealing with data in machine learning contexts.
- The concept of slicing can be likened to cutting an apple; it involves breaking down the string into smaller segments for easier manipulation.
How to Slice Strings
- To slice a string, specify the starting and ending indices using square brackets. The syntax is
string[start:end], where the start index is included, but the end index is not.
- For example, if you have the string "college" and want to access part of it from index 1 to 4, you would get "oll".
Practical Examples of Slicing
- If you run a slice from index 1 to 5 on "college", you'll retrieve "oll".
- You can also use the length of the string as an endpoint for slicing. Using
len(string)will give you the last valid index.
Default Behavior When Indices Are Missing
- If you omit the ending index while slicing, Python assumes you want to go up to the last character of the string.
- Similarly, if you miss out on specifying a starting index, Python defaults it to zero.
Negative Indexing: A Unique Feature
- Python supports negative indexing which counts backwards from the end of a string. For instance, -1 refers to the last character.
- This feature allows for flexible slicing options that are not commonly found in other programming languages like C++ or Java.
Advanced Slicing with Negative Indices
- When using negative indices for slicing (e.g.,
string[-3:-1]), only characters between those indices are returned without including the ending character.
Understanding String Manipulation in Python
Basic String Printing Techniques
- The speaker discusses testing string printing by creating a substring from a given string, using negative indexing to print specific characters.
- By using negative indices, the speaker explains how to cover three characters while skipping the last one, demonstrating backward counting for character selection.
- Emphasizes that as beginners, practical cases may not be explored deeply; however, understanding this concept is crucial for working with strings.
Functions and Their Importance
- The discussion shifts to various functions available in string manipulation. It highlights that programmers often work with multiple languages and may not remember all functions.
- It's noted that memorizing every function isn't necessary; instead, practicing coding through tutorials can help retain knowledge effectively.
Key String Functions
Ends With Function
- Introduction of the
endswithfunction which checks if a string ends with a specified substring. This function returnsTrueorFalse.
- An example is provided where the speaker uses a sample string "I am studying Python" to demonstrate how to check if it ends with certain substrings.
Capitalize Function
- The
capitalizefunction is introduced, which capitalizes the first character of a string without altering the original string unless reassigned.
- If modifications are needed on the original string, reassigning it after applying
capitalizeensures changes are reflected.
Replace Function
String Manipulation in Python
Replacing Characters in Strings
- The process of replacing characters in a string is demonstrated, where 'o' is replaced with 'a'. This affects all occurrences of 'o' within the string.
- An example shows how to replace an entire substring, changing "Python" to "JavaScript", illustrating flexibility in string manipulation.
Finding Characters in Strings
- The
findfunction searches for a specific character or substring within a string and returns the starting index of its first occurrence.
- If the character does not exist (e.g., searching for 'q'), it returns -1, indicating no valid index was found.
Counting Occurrences of Substrings
- The
countfunction counts how many times a specified substring appears within a string. For instance, counting occurrences of "from" yields two results.
- When counting the letter 'o', it appears four times across different words, showcasing the utility of this function.
Exploring String Functions
- Various built-in functions are available for strings in Python. These can be explored further as they provide powerful tools for handling text data.
- Understanding these functions lays the groundwork for more complex programming tasks involving strings.
Practical Applications and Exercises
User Input and String Length
- A practical exercise involves writing a program that takes user input for their first name and prints its length using
len().
Counting Specific Characters
- Another exercise focuses on counting how many times the dollar sign '$' appears in a given string using the
countmethod.
Introduction to Conditional Statements
Understanding Conditions in Programming
- Conditional statements allow programmers to express various conditions that must be met before executing certain code blocks (e.g., age requirements).
Syntax of Conditional Statements
Understanding Conditional Statements in Programming
Basics of Conditional Statements
- The concept of using conditional statements, such as "if," is introduced. An example is given where a person's age must be 18 or older to apply for a license.
- A condition returns either true or false. Boolean variables can also be used within conditions to determine the execution of statements based on their truth value.
Practical Example with Age Verification
- A practical coding example is provided where an age variable is set to 21, and an if statement checks if the age is greater than or equal to 18.
- Emphasis on proper indentation after the colon in Python syntax; subsequent lines must start with a tab space or four spaces for correct execution.
Executing Multiple Statements
- If the condition evaluates to true, multiple statements can be executed. For instance, printing messages about eligibility for voting and applying for a license.
- The ability to execute two statements simultaneously under one if condition is highlighted, demonstrating flexibility in coding logic.
Understanding 'elif' and Its Usage
- Introduction of "elif" (else if), which allows checking another condition if the first one fails. This structure helps manage multiple conditions effectively.
- An analogy using traffic lights illustrates how different conditions (red, yellow, green lights) can dictate actions like stopping or going based on their states.
Execution Flow and Final Outputs
- The flow of code execution is explained: once a true statement executes, subsequent statements are ignored unless they are part of another conditional check.
- It’s noted that multiple if and elif statements can coexist in sequence; however, at least one initial if statement must always precede any elif statements.
Differences Between 'if' and 'elif'
- Clarification on the difference between "if" and "elif": while "if" checks its condition every time it appears, "elif" only checks when its preceding "if" has evaluated to false.
Conditional Statements in Programming
Understanding Conditional Execution
- Statements will execute, but when an
ifstatement is followed by anelif, only the first true condition will be executed. The second condition is not checked if the first one is true.
- An
elsestatement can only be written once and typically appears at the end of conditional statements. It signifies that no conditions were met above it.
Practical Example: Traffic Light Logic
- If none of the traffic light colors (red, green, yellow) are present, it indicates a broken light. For instance, if a blue color appears, it doesn't make sense; hence we can use an
elsestatement to print "Light is broken."
- If the traffic light shows pink or any other unexpected color, all previous conditions would fail and trigger the
elsestatement to print "Light is broken."
Voting Age Example
- In a voting scenario where age equals 24, we check if age is greater than or equal to 18 to print "Can vote." If this fails, we use an
elsestatement to print "Cannot vote."
- This demonstrates how basic conditional statements work in programming.
Indentation in Python
- Proper indentation (spacing with tabs or spaces) is crucial in Python as it defines code blocks instead of using curly braces like in C/C++ or Java.
- Indentation helps combine multiple statements logically within conditional structures.
Assigning Grades Based on Marks
- A program can be created to assign grades based on student marks:
- A for marks above 90,
- B for marks between 80 and 90,
- C for marks between 70 and 80,
- D for marks below 70.
Implementing Grade Logic
- To implement this logic:
- Check if marks are greater than or equal to 90 for grade A.
- Use logical operators (
and) to check ranges effectively.
- For example: Check if marks are greater than or equal to 80 and less than 90 for grade B.
Finalizing Grade Assignment Code
- The final code checks each condition sequentially:
- If marks >= 90 → Grade = A
- Else if (marks >= 80 and <90) → Grade = B
- Else if (marks >=70 and <80) → Grade = C
- Else → Grade = D
Understanding Programming Basics
Input, Operations, and Output in Programming
- The discussion begins with a focus on how programming works by taking input (e.g., student marks), performing operations (like grading), and producing output. For example, a student scoring 94 receives an 'A', while scores of 67 and 88 correspond to grades 'D' and 'B', respectively.
- It is emphasized that programming languages typically follow the structure of receiving input, executing operations, and generating output as results sent from the program.
Conditional Statements and Nesting
- The concept of nesting within conditional statements is introduced. Nesting refers to placing one if-statement inside another. This allows for more complex decision-making processes in code.
- An example illustrates checking if age is greater than or equal to 18; if true, it prints "can drive," otherwise "cannot drive." A hypothetical upper limit of 80 years for driving is also discussed.
Practical Application of Nested Conditions
- Further exploration into nested conditions shows how multiple checks can be performed within a single statement. If age meets certain criteria, different outputs are printed based on those conditions.
- The validity of using nested statements in Python is confirmed through examples where age values determine driving eligibility.
Introduction to Loops
- The session transitions towards loops as an important concept in programming that will be covered in future lectures. It hints at the potential for nesting within loops as well.
Practice Questions: Odd and Even Numbers
Identifying Odd and Even Numbers
- A practice question prompts writing a program to check whether a user-entered number is odd or even. Odd numbers start from one (1, 3, 5...) while even numbers include two (2, 4, 6...).
- A key property of even numbers is highlighted: they are divisible by two without leaving a remainder. This leads to the conclusion that any number yielding zero when divided by two is even.
Implementing Logic in Code
- To implement this logic programmatically, users can find the remainder using modulo operation (%). If the result equals zero after dividing by two, then it's classified as an even number; otherwise, it's odd.
Finding the Greatest Among Three Numbers
Writing Programs for Comparison
- Another practice question involves writing a program to find the greatest among three user-inputted numbers (a, b, c).
How to Find the Largest of Three Numbers
Inputting and Storing Numbers
- The process begins with inputting three numbers from the user, storing them in variables A, B, and C.
- A conditional check is performed to determine if A is greater than or equal to B and C. If true, it prints that the first number is the largest along with its value.
Determining the Largest Number
- If B is found to be greater than or equal to C, it indicates that B is the second largest number; this value is printed accordingly.
- In cases where neither A nor B are the largest, C must be the greatest number. The program concludes by printing that C is the largest.
Example Execution
- An example run shows inputs of 4 for A, 5 for B, and 7 for C resulting in "Third is largest which is 7."
- Another example with inputs of 99 for A, 201 for B, and 87 for C confirms that "Second number which is equal to 201" becomes the largest.
Homework Assignment: Finding Largest of Four Numbers
Task Description
- Students are assigned a task to write code that finds the largest among four numbers using similar logic as used in finding three numbers.
Approach Suggestion
- It’s recommended to think through the logic on paper before converting it into Python code.
Checking Multiples of Seven
Program Objective
- The next question involves writing a program to check if a given number (X) is a multiple of seven. This requires checking if X modulo seven equals zero.
Examples of Multiples
- Examples provided include numbers like 7, 14, 21, and so forth—all yielding a remainder of zero when divided by seven.
Code Implementation
- The program prompts users for an input number X. If X modulo seven equals zero, it prints "Multiple of 7"; otherwise, it states "Not a multiple."
Testing Other Multiples
Additional Checks
- Users can test other numbers as well; examples include checking if 25 or 27 are multiples of five—demonstrating flexibility in applying similar logic across different scenarios.