Concepts / Conditional Statements and Logic

Conditional Statements and Logic

A conditional decision uses processed input to choose a result.

  • Programming
Interactive lab

Try it: if / elif / else

How Python tests if / elif conditions from the top, runs only the first true branch, and how and / or stop evaluating as soon as the answer is known (short-circuiting).

How it works

  1. Python evaluates the if condition first.
  2. If it is False, it tries each elif in order; the first True one runs and the rest are skipped without being tested.
  3. If none is True, the else branch runs.
  4. and stops at the first False, or stops at the first True — the right side may never be evaluated.

Default run (5 steps): score = 84; A = 90, B = 80, C = 70. Python tests the conditions from the top. … print(grade) shows B.

Educational simulation

Loading the simulation…

From Keyboard to Variable

An input-driven program begins outside the program: a user types at the keyboard. The raw_input() function connects that action to your code. It displays a prompt, waits for the user to type and press Enter, captures the typed text, and returns that text as a string. When the returned value is assigned to a variable, the program can process the response and use it in a decision.

Keyboardtyped textraw_input()captures textresponsestringProgram logicuses the responseuser types and presses Enterreturns textstored and processed
How does text typed by the user move from the keyboard through raw_input() and become a string stored in a variable?
python

The assignment happens after raw_input() returns. First, the prompt is displayed. Next, the program waits. The user types and presses Enter. The text is captured and returned, and then it is stored in something. At that point, something contains the user's response as a string.

A Decision from Text

A conditional decision uses processed input to choose a result. In the palindrome example, the program compares the original text with a reversed version. If the two strings match, the text is identified as a palindrome. If they do not match, it is not identified as a palindrome. The important flow is that the comparison uses the string returned by raw_input(), rather than an abstract value disconnected from the user's response.

User responsestringReversed textprocessed stringString comparisonoriginal equals reversed?Palindromematching resultNot palindromenon-matching resultsend text to processingcompare with originalmatchno match
What path does the program take when the reversed response matches the original, and what path does it take when it does not?
Worked example

Tracing a palindrome response

Follow the response through a palindrome checker when the user enters a word that reads the same forwards and backwards.

  1. 1
    Prompt

    The program displays a request for text and waits for the user to type and press Enter.

  2. 2
    Capture

    raw_input() returns the typed text as a string, and the main program stores it in a variable.

  3. 3
    Process

    The response is passed to palindrome-checking logic. The text is reversed and compared with the original.

  4. 4
    Decision

    Because the original and reversed strings match, the program selects the palindrome result.

  5. 5
    Output

    The program displays the result of the comparison.

Result

The response travels through input capture, palindrome checking, and output. The comparison determines which result is displayed.

The Complete Palindrome Program

The source example organizes the task into two helper functions and a main input-and-output stage. reverse() flips a string with the slice notation [::-1]. is_palindrome() compares the original text with its reversed version. The main program calls raw_input(), sends the captured string to is_palindrome(), and prints the result.

Code walkthrough
def reverse(text):
    return text[::-1]

def is_palindrome(text):
    return text == reverse(text)

text = raw_input("Enter text: ")
if is_palindrome(text):
    print "The text is a palindrome."
else:
    print "The text is not a palindrome."
  1. 1
    The reverse() function uses [::-1] to flip the supplied string backwards.
  2. 2
    The is_palindrome() function returns the result of comparing text with reverse(text).
  3. 3
    The main program asks the user for text and stores the returned string in text.
  4. 4
    The conditional checks the Boolean result from is_palindrome(text).
  5. 5
    The program prints one result when the strings match and another when they do not.
  • reverse() receives text and returns the text in reverse order.
  • is_palindrome() compares the original text with the reversed text.
  • raw_input() captures the user's response as a string.
  • The conditional selects an output based on the comparison.

Tracing Unexpected Results

When the output is unexpected, do not inspect only the final message. Trace the program step by step and inspect the state of the data at each stage. For an input-driven palindrome checker, the main stages are input capture, palindrome checking, and output. The divergence from expectation occurred in one of those stages.

Usertypes responseInput capturereturned stringPalindrome checkingcomparison resultOutputdisplayed resulttyped textcaptured stringdecision result
At which step does the actual input or condition result diverge from what the programmer expected?
  • First verify what text the user actually entered and confirm that raw_input() captured it.
  • Next verify the value passed into the palindrome-checking function.
  • Then verify the reversed text and the comparison result.
  • Finally verify that the output stage displays the result produced by the comparison.
Captured stringraw_input() resultReverse text[::-1]Compare stringsoriginal and reversedDisplayed resultpalindrome statussend stringprovide reversed stringselect output
After raw_input() returns a string, what transformations, comparisons, and decisions occur before the result is displayed?

Mistakes Beginners Make

  • Common mistake

    Treating the value returned by raw_input() as a number automatically.

    What it looks like

    A response captured with raw_input() is used directly in numeric operations.

    Why it fails

    raw_input() returns text as a string.

    Do this instead

    Convert the string to int or float when numeric operations are required.

  • Common mistake

    Skipping the input-capture stage during debugging.

    What it looks like

    The programmer checks only the final palindrome message.

    Why it fails

    The unexpected result may have begun when input was captured, during processing, or during output.

    Do this instead

    Trace the response through input capture, palindrome checking, and output.

  • Common mistake

    Assuming the conditional result without checking the comparison.

    What it looks like

    The program is expected to identify a palindrome, but the original and reversed strings do not match.

    Why it fails

    The decision depends on whether the two strings match.

    Do this instead

    Inspect the original text, its reversed form, and the comparison result.

  • Common mistake

    Ignoring whitespace or case sensitivity when handling text.

    Why it fails

    The source specifically identifies whitespace and case sensitivity as details to handle carefully when working with captured text.

    Do this instead

    Account for whitespace and case sensitivity when testing and processing real user input.

Practice the Flow

MEDIUM

Write down the value at each stage of an input-driven palindrome checker: the text returned by raw_input(), the reversed text, the comparison result, and the displayed result. Then test the program with one response that reads the same forwards and backwards and one response that does not.

Hints
  • Begin with the fact that raw_input() returns a string.
  • Use [::-1] to identify the reversed text.
  • The conditional result depends on whether the original and reversed strings match.
Promptrequest textCaptureraw_input()Evaluatecompare textDisplay resultprint outcomewait for responsepass captured stringchoose result
How are prompting, capturing input, evaluating conditions, and displaying the result connected in one program?

Key Takeaways

  1. 1
    raw_input() displays a prompt, waits for keyboard input, and returns the typed text as a string.
  2. 2
    The returned string is stored in a variable so that program logic can process it.
  3. 3
    A palindrome checker reverses the captured text and compares the reversed version with the original.
  4. 4
    Conditional output depends on whether those two strings match.
  5. 5
    When output is unexpected, trace input capture, processing, and output in order.

At a glance

  • raw_input() moves text from the keyboard into a program variable as a string.
  • Conditional logic can use the captured response to select between results.
  • The palindrome example reverses a string and compares it with the original.
  • Debugging is a step-by-step trace through input capture, processing, and output.
  • Numeric responses require conversion to int or float before numeric operations.

Related concepts

More concepts starting with C