Free Ebook cover Python for Absolute Beginners: Variables, Loops, and Small Useful Scripts

Python for Absolute Beginners: Variables, Loops, and Small Useful Scripts

New course

14 pages

Working with Strings and User Input for Simple Programs

Capítulo 3

Estimated reading time: 11 minutes

+ Exercise

What Strings Are Used For in Small Programs

Strings are pieces of text, like names, messages, file paths, email addresses, and anything you might type on a keyboard. In beginner programs, strings are often the main way your program communicates with a user: you ask a question, the user types an answer, and your program responds.

In Python, strings are written inside quotes. You can use single quotes or double quotes. The important thing is to start and end with the same type of quote.

greeting = "Hello"
name = 'Ada'
message = "It's nice to meet you"

Strings are immutable, which means you cannot change a string “in place.” Instead, when you “modify” a string, Python creates a new string. This matters when you do operations like replacing text or changing case: you must store the result if you want to keep it.

text = "hello"
text.upper()      # returns "HELLO" but does not change text
text = text.upper()
print(text)       # "HELLO"

Getting User Input with input()

Most simple interactive programs use input(). It pauses the program, shows a prompt (a message), and waits for the user to type something and press Enter. The result of input() is always a string.

user_name = input("What is your name? ")
print("Nice to meet you, " + user_name)

Because input() always returns a string, you must convert it when you need a number. You will often combine input with int() or float() to turn text into numeric values.

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app

age_text = input("How old are you? ")
age = int(age_text)
print("Next year you will be", age + 1)

If the user types something that is not a valid integer (for example, twelve), int() will raise an error. A beginner-friendly program should validate input or handle errors. A common approach is to keep asking until the user enters something valid.

Step-by-step: Keep asking until the user enters a number

This pattern uses a loop and a try/except block. The idea is: attempt the conversion; if it fails, show a helpful message and ask again.

while True:
    age_text = input("Enter your age (whole number): ")
    try:
        age = int(age_text)
        break
    except ValueError:
        print("That wasn't a whole number. Please try again.")

print("Thanks! Your age is", age)

Even if you have not used try/except much yet, it is worth learning this one pattern early because it makes your programs feel more “real” and less fragile.

Building Strings: Concatenation, print(), and f-Strings

You often need to combine text with other text or with values. There are three common beginner-friendly ways to do it.

1) Concatenation with +

You can add strings together using +. This is called concatenation.

first = "Ada"
last = "Lovelace"
full = first + " " + last
print(full)

Concatenation only works with strings. If you try to add a number directly, you will get an error. Convert the number to a string first.

count = 3
message = "You have " + str(count) + " new messages."
print(message)

2) Letting print() join values with commas

print() can take multiple arguments separated by commas. It automatically converts non-strings to strings and inserts spaces between items.

count = 3
print("You have", count, "new messages.")

This is convenient for quick output, but you have less control over formatting.

3) f-Strings (recommended for readable formatting)

f-Strings let you embed expressions inside a string using {}. They are readable and flexible.

count = 3
user = "Ada"
print(f"Hello {user}, you have {count} new messages.")

You can also format numbers inside f-strings (for example, showing two decimal places).

price = 12.5
print(f"Total: ${price:.2f}")  # Total: $12.50

Common String Operations You Will Use Often

Python strings come with many helpful methods. Methods are functions attached to a value, written with a dot. For example: text.lower().

Changing case: lower(), upper(), title()

Case changes are useful for normalizing user input. For example, users might type YES, Yes, or yes. You can convert input to lowercase and compare once.

answer = input("Do you want to continue? (yes/no) ")
answer = answer.strip().lower()

if answer == "yes":
    print("Continuing...")
else:
    print("Stopping...")

Notice the use of strip() above. That removes extra spaces at the beginning and end, which is common in user input.

Removing extra spaces: strip(), lstrip(), rstrip()

Users sometimes accidentally type spaces before or after their input. strip() cleans that up.

raw = "   hello   "
clean = raw.strip()
print(clean)  # "hello"

lstrip() removes from the left only, and rstrip() removes from the right only.

Checking what a string contains: in, startswith(), endswith()

To check whether a piece of text appears inside another, use in.

email = input("Email: ").strip()
if "@" in email:
    print("Looks like an email address.")
else:
    print("Missing '@'.")

To check prefixes and suffixes, use startswith() and endswith().

filename = input("Filename: ").strip()
if filename.endswith(".txt"):
    print("Text file detected")

Replacing text: replace()

replace() returns a new string where occurrences are replaced.

sentence = "I like cats"
new_sentence = sentence.replace("cats", "dogs")
print(new_sentence)

This is useful for cleaning input, for example converting commas to dots in a decimal number (depending on locale). Be careful: replacing characters can change meaning, so do it only when you are sure it is appropriate.

Splitting and joining: split() and join()

split() breaks a string into a list of parts. A very common case is splitting by spaces.

text = "red green blue"
parts = text.split()
print(parts)  # ['red', 'green', 'blue']

You can also split by a specific separator, like a comma.

csv_line = "apples,bananas,cherries"
items = csv_line.split(",")
print(items)

join() does the opposite: it combines a list of strings into one string with a separator.

words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence)

A practical use: you ask the user for several items separated by commas, split them, clean spaces, and then display them nicely.

Step-by-step: Parse a comma-separated list from the user

raw = input("Enter items separated by commas: ")
parts = raw.split(",")
clean_parts = []

for p in parts:
    item = p.strip()
    if item != "":
        clean_parts.append(item)

print("You entered:")
for item in clean_parts:
    print("-", item)

This script demonstrates a realistic input-cleaning workflow: split, strip, ignore empty items.

Indexing and Slicing Strings

You can access individual characters in a string using indexing. Indexes start at 0.

word = "Python"
print(word[0])  # 'P'
print(word[1])  # 'y'

You can also use negative indexes to count from the end.

print(word[-1])  # 'n'
print(word[-2])  # 'o'

Slicing lets you take a piece (substring) of a string using [start:end]. The end index is not included.

word = "Python"
print(word[0:2])  # 'Py'
print(word[2:])   # 'thon'
print(word[:3])   # 'Pyt'

Slicing is useful for tasks like extracting an area code, trimming a fixed prefix, or showing a preview of a long message.

Validating User Input as Text

Not all input should be accepted. For example, a username might need to be at least 3 characters, contain no spaces, and only use letters and numbers. Python provides methods that help you check the shape of a string.

Useful checks: isdigit(), isalpha(), isalnum()

These methods return True or False.

  • isdigit(): only digits (0–9)
  • isalpha(): only letters
  • isalnum(): only letters and digits
code = input("Enter a 4-digit PIN: ").strip()
if len(code) == 4 and code.isdigit():
    print("PIN accepted")
else:
    print("PIN must be exactly 4 digits")

Notice how validation often combines multiple checks: length plus content rules.

Step-by-step: Create a username prompt with rules

Goal: ask the user for a username that is 3 to 12 characters long, contains only letters and numbers, and has no spaces. Keep asking until it is valid.

while True:
    username = input("Choose a username (3-12 letters/numbers): ").strip()

    if len(username) < 3 or len(username) > 12:
        print("Username must be 3 to 12 characters long.")
        continue

    if not username.isalnum():
        print("Use only letters and numbers (no spaces or symbols).")
        continue

    break

print(f"Welcome, {username}!")

This is a strong pattern for beginner programs: a loop that continues until the input passes all checks.

Working with Multi-line Text

Sometimes you want to store or print text that spans multiple lines, such as instructions or a menu. You can create multi-line strings using triple quotes.

menu = """Choose an option:
1) Add item
2) Remove item
3) Quit"""
print(menu)

Even if your program is small, clear menus and instructions make it easier to use.

Mini Program 1: A Polite Greeter with Name Cleanup

This small program demonstrates a realistic combination of input, cleanup, and formatted output. It also shows how to handle users typing extra spaces or unusual capitalization.

Step-by-step

  • Ask for the user’s first name and last name.
  • Remove extra spaces with strip().
  • Apply title() to make names look nice (for many names, though not all).
  • Print a greeting using an f-string.
first = input("First name: ").strip()
last = input("Last name: ").strip()

first = first.title()
last = last.title()

print(f"Hello, {first} {last}!")

Try inputs like aDa and lovelace to see how cleanup changes the output.

Mini Program 2: Yes/No Questions That Accept Many Variations

Users rarely type exactly what you expect. If you ask for yes or no, you might get y, Y, YES, or even yep . You can normalize input and accept a small set of valid answers.

Step-by-step: Normalize and validate

while True:
    answer = input("Do you want to save changes? (y/n) ")
    answer = answer.strip().lower()

    if answer in ["y", "yes"]:
        print("Saving...")
        break
    elif answer in ["n", "no"]:
        print("Not saving.")
        break
    else:
        print("Please type y or n.")

This approach makes your program friendlier without becoming complicated.

Mini Program 3: A Simple Password Strength Checker

This example is not about real security (real password rules can be complex), but it is a great practice project for string checks. You will examine a password string and report whether it meets basic requirements.

Requirements

  • At least 8 characters
  • Contains at least one digit
  • Contains at least one letter

To check “contains at least one digit,” you can loop through characters and test each one. The same idea works for letters.

password = input("Create a password: ")

has_digit = False
has_letter = False

for ch in password:
    if ch.isdigit():
        has_digit = True
    if ch.isalpha():
        has_letter = True

if len(password) >= 8 and has_digit and has_letter:
    print("Password looks okay for this simple checker.")
else:
    print("Password must be 8+ chars and include letters and digits.")

Notice how this uses string methods on individual characters. This is a common technique when you need to inspect text carefully.

Common Beginner Mistakes with Strings and Input

Forgetting that input() returns a string

If you do math with input directly, you will get errors or unexpected results. For example, adding strings concatenates them instead of adding numbers.

x = input("Enter a number: ")
y = input("Enter another number: ")
print(x + y)  # if you type 2 and 3, this prints "23"

Convert to integers (or floats) when you need numeric behavior.

x = int(input("Enter a number: "))
y = int(input("Enter another number: "))
print(x + y)  # 5

Not storing the result of a string method

Because strings are immutable, methods like lower() and replace() return a new string. If you do not assign it, your original variable stays the same.

name = " Ada "
name.strip()
print(name)  # still " Ada "

Fix it by assigning:

name = name.strip()

Comparing text without normalizing it

If you compare raw input directly, small differences in capitalization or spaces can cause your checks to fail.

answer = input("Type YES to continue: ")
if answer == "YES":
    print("OK")
else:
    print("Not recognized")

Make it more robust:

answer = input("Type YES to continue: ").strip().lower()
if answer == "yes":
    print("OK")

Practice Tasks (Try These in Your Editor)

Use these tasks to build confidence. Each one is small but teaches a useful real-world habit.

  • Create a program that asks for a sentence and prints how many characters it has (use len()).
  • Ask for a word and print the first and last character (use indexing).
  • Ask for a list of hobbies separated by commas, then print them one per line after stripping spaces.
  • Ask for an email address and check that it contains exactly one @ and at least one dot after the @ (hint: use split("@") and in).
  • Ask the user to type a command: start, stop, or status. Normalize input with strip().lower() and respond appropriately.

Now answer the exercise about the content:

When asking the user for their age and using it in math, which approach is most beginner-friendly and least fragile?

You are right! Congratulations, now go to the next page

You missed! Try again.

input() always returns a string, and int() can fail on non-numeric text. A loop with try/except lets you validate and retry, making the program more robust.

Next chapter

Controlling Program Flow with Conditions and Comparisons

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.