Python · Syntax · Beginner

Conditions 2

11 tasks

Additional practice with conditionals in Python: string checks, text lengths, characters, slices, string methods, logical and/or operators, and simple input processing scenarios.

String operations for conditions

#
Conditional statements in this topic work with strings instead of numbers. The new skill is knowing which string operations to reach for — there are four that cover almost every situation. Indexing gives you individual characters. Positive indices count from the start, negative from the end: ```python text = "Python" print(text[0]) # P — first character print(text[-1]) # n — last character print(text[-2]) # o — second to last ``` A slice with [start:end] extracts a substring from index start up to, but not including, index end: ```python text = "Hello world" print(text[:4]) # Hell — first 4 characters print(text[2:8]) # llo wo — from index 2 to 7 ``` If you omit start, Python assumes 0. If you omit end, it goes to the end of the string. So text[:4] and text[0:4] are identical. The in operator tests whether a substring or character exists anywhere in the string: ```python if "@" in text: print("Contains @") if "#" in text or "@" in text: print("Special character found") ``` Two methods handle prefix and suffix checks more cleanly than slicing: ```python text.startswith("Py") # True when text begins with "Py" text.endswith("on") # True when text ends with "on" ``` Both methods are case-sensitive. "python".startswith("Py") is False.

Patterns from the exercises

#
A pattern these exercises repeat: check the length before accessing characters. Accessing text[0] or text[-1] on an empty string raises an IndexError — the length guard prevents that. ```python text = input("Enter a string: ") if len(text) > 10: print(text[0], text[-1]) else: print("Too short") ``` For case-insensitive comparisons, convert to lowercase before comparing. The method returns a new string — it does not modify text in place: ```python text = input("Enter a phrase: ") if text.lower() == "hello": print("Hello to you too!") elif text.lower() == "goodbye": print("Goodbye!") else: print("I don't understand") ``` Combining a length check with a content check — and short-circuits from left to right, so if the length check fails Python skips the rest: ```python text = input("Enter a message: ") if len(text) > 6 and text[-1] == "!": print("Emotional message") else: print("Normal message") ``` Checking a range of lengths uses two comparisons joined with and: ```python if len(text) >= 5 and len(text) <= 10: print("Suitable length") ``` This is equivalent to the chained form: if 5 <= len(text) <= 10.

String conditions quick reference

#
**String operations for conditions** | Operation | Syntax | Returns | |---|---|---| | Character by index | `s[0]`, `s[-1]` | single character | | Substring slice | `s[1:4]` | substring | | Membership test | `'x' in s` | `True` / `False` | | Starts with | `s.startswith('ab')` | `True` / `False` | | Ends with | `s.endswith('ab')` | `True` / `False` | | Length | `len(s)` | integer | **Useful string methods in conditions** | Method | What it does | |---|---| | `s.lower()` | lowercase copy — use before comparing | | `s.upper()` | uppercase copy | | `s.strip()` | copy without leading/trailing spaces | | `s.isdigit()` | `True` if every character is a digit | | `s.isalpha()` | `True` if every character is a letter | | `s.isspace()` | `True` if only whitespace | **Key patterns** ```python # Always check length before indexing if len(s) > 0: # or: if s: print(s[0], s[-1]) # Case-insensitive comparison if s.lower() == 'yes': print('Confirmed') # Check both ends if s.startswith('(') and s.endswith(')'): print('Wrapped in parentheses') # Length in a range if 5 <= len(s) <= 20: print('Valid length') # Short-circuit: length guard before content check if len(s) >= 2 and s[-1] == '!': print('Ends with exclamation') ```
01

First and last character.

#

The user enters a string. If the string length is greater than 10 characters — display the first and last character, otherwise — display "The string is too short".

text = input("Enter a string: ")

Solution
text = input("Enter a string: ")

if len(text) > 10:
    print(text[0], text[-1])
else:
    print("The string is too short")

# or you can do this: store the characters in variables
text = input("Enter a string: ")

if len(text) > 10:
    first = text[0]
    last = text[-1]
    print(first, last)
else:
    print("The string is too short")
02

String starts with A.

#

The user enters a string. If the string starts with the letter "A" or "a" — display "Starts with A", otherwise — "Starts with another letter". You can use string methods.

text = input("Enter a string: ")

Solution
text = input("Enter a string: ")

if text.startswith("A") or text.startswith("a"):
    print("Starts with A")
else:
    print("Starts with another letter")


# OR
if text[0] == "A" or text[0] == "a":
    print("Starts with A")
else:
    print("Starts with another letter")


# OR
if text[0].lower() == "a":
    print("Starts with A")
else:
    print("Starts with another letter")

As a result of this expression text[0], we get a new string object that
consists of 1 character, which means we can apply methods to it.
03

First four characters.

#

The user enters a string. If the string length is greater than 8 characters — display the first 4 characters, otherwise — display the whole string.

text = input("Enter a string: ")

Solution
text = input("Enter a string: ")

if len(text) > 8:
    print(text[:4])
else:
    print(text)

# or you can do this: prepare the fragment first
text = input("Enter a string: ")

if len(text) > 8:
    part = text[:4]
else:
    part = text

print(part)
04

Emotional message.

#

The user enters a string. If the string length is greater than 6 characters and the last character is "!" — display "Emotional message", otherwise — "Regular message".

text = input("Enter a message: ")

Solution
text = input("Enter a message: ")

if len(text) > 6 and text[-1] == "!":
    print("Emotional message")
else:
    print("Regular message")

# or you can do this using the endswith method
text = input("Enter a message: ")

if len(text) > 6 and text.endswith("!"):
    print("Emotional message")
else:
    print("Regular message")
05

Searching for special characters.

#

The user enters a string. If the string contains the "@" symbol or the "#" symbol — display "Special character found", otherwise — "No special characters".

text = input("Enter a string: ")

Solution
text = input("Enter a string: ")

if "@" in text or "#" in text:
    print("Special character found")
else:
    print("No special characters")

# or you can do this: check the characters one by one
text = input("Enter a string: ")

if "@" in text:
    print("Special character found")
elif "#" in text:
    print("Special character found")
else:
    print("No special characters")
06

Greeting by first and last name.

#

The user enters a first name and last name. If both the first name and the last name are not empty — display a greeting in the format: "Hello, First Name Last Name!" (use an f-string), otherwise — "Enter valid data".

name = input("Enter first name: ")
surname = input("Enter last name: ")

Solution
name = input("Enter first name: ")
surname = input("Enter last name: ")

if name and surname:
    print(f"Hello, {name} {surname}!")
else:
    print("Enter valid data")

# or without an f-string, using string concatenation
name = input("Enter first name: ")
surname = input("Enter last name: ")

if name and surname:
    print("Hello, " + name + " " + surname + "!")
else:
    print("Enter valid data")
07

Slice from the 3rd to the 8th character.

#

The user enters a string. If the string length is greater than 10 characters — display a slice of the string from the 3rd character (inclusive) to the 8th character (inclusive), otherwise — display "Not enough characters".

text = input("Enter a string: ")

Solution
text = input("Enter a string: ")

if len(text) > 10:
    print(text[2:8])
else:
    print("Not enough characters")
08

First and last in a message.

#

The user enters a string. If the string is not empty — display the message: "First character: X, last character: Y" (use an f-string), otherwise — "Empty string".

text = input("Enter a string: ")

Solution
text = input("Enter a string: ")

if text:
    print(f"First character: {text[0]}, last character: {text[-1]}")
else:
    print("Empty string")

# or you can do this: save the first and last character beforehand
text = input("Enter a string: ")

if text:
    first = text[0]
    last = text[-1]
    print(f"First character: {first}, last character: {last}")
else:
    print("Empty string")
09

Suitable string length.

#

The user enters a string. If the string length is from 5 to 10 characters inclusive — display "Suitable length", otherwise — "Unsuitable length".

text = input("Enter a string: ")

Solution
text = input("Enter a string: ")

if 5 <= len(text) <= 10:
    print("Suitable length")
else:
    print("Unsuitable length")

# second option: the same thing without chained comparisons
text = input("Enter a string: ")

length = len(text)
if length >= 5 and length <= 10:
    print("Suitable length")
else:
    print("Unsuitable length")
10

Looks like Python.

#

The user enters a string. If the string starts with "Py" or ends with "on" — display "Looks like Python", otherwise — "Does not look like Python".

text = input("Enter a string: ")

Solution
text = input("Enter a string: ")

if text.startswith("Py") or text.endswith("on"):
    print("Looks like Python")
else:
    print("Does not look like Python")

# or you can do this if the case of the first letter does not matter
text = input("Enter a string: ")

if text.lower().startswith("py") or text.endswith("on"):
    print("Looks like Python")
else:
    print("Does not look like Python")
11

Hello or goodbye.

#

"Hello - Goodbye program" If the user enters: Hello, hello, HeLLo or HELLO - reply with "Hello to you too!" If the user enters: Bye, bYe, and so on - reply with "Adios!".

text = input("Enter a phrase: ")
Solution
text = input("Enter a phrase: ")

if text.lower() == "hello":
    print("Hello to you too!")
elif text.lower() == "bye":
    print("Adios!")
else:
    print("Nah, I don't talk to strangers! Adios!")


# OR more carefully, to account for containment instead of exact equality:
if "hello" in text.lower():
    print("Hello to you too!")
elif "bye" in text.lower():
    print("Adios!")
else:
    print("Nah, I don't talk to strangers! Adios!")