Classic number guess game Python ternary operator demonstration

Updated TrustyTony 0 Tallied Votes 1K Views Share

Do you know that there is clean way of doing what C-language ternary operator ? does in Python's recent versions.

It is if with special twist. The syntax is:

'The value if true' if <condition> else 'Value when false'

Values can be any type. You can put this structure to replace single value.

In this classic number guess game version we practise using the structure even in a nested way. This is not maybe so advisable general way, as it is less clear than many print statements in normal if statement.

Anyway, this came first to my mind as demonstration of this, as I learned about this statement form myself only today. I have used and and or to simulate the form before.

## This program is programmed little special way to demonstrate Python ternary if

from __future__ import print_function ## for python 2.6 Python 3 style print function
from random import randint
from sys import version
print ('Your python is:\n',version)
if version[0]=='3': raw_input = input

secret = randint(0,100)
found = False
tries=0
print('What number between 0 and 100 I am thinking')
while not found:
    try:
        tries += 1
        guess=int(raw_input('%i. try:' % tries))
        found = guess == secret
        print ('Too small' if guess < secret
               else ('You found it with %i tries! It was %i.' % (tries,secret) if found
                     else 'Too big')
               )
    except ValueError:
        print('Input must be number')

Dani AI

Generated

Nice demonstration by of Python's conditional expression. The construct is handy for very short, single-value choices, but readability drops quickly once it is nested. A clearer pattern for this classic guessing game is to keep input/validation separate and use straightforward if/elif/else for the game logic.

import random

secret = random.randint(0, 100)
tries = 0

while True:
    tries += 1
    try:
        guess = int(input(f"{tries}. try: "))
    except ValueError:
        print("Input must be a number")
        continue
    if guess < secret:
        print("Too small")
    elif guess > secret:
        print("Too big")
    else:
        print(f"You found it with {tries} tries! It was {secret}.")
        break

Notes and cautions: the older a and b or c trick that predates the conditional expression fails when b is falsy (for example 0 and "yes" or "no" yields "no"). For cross-version checks prefer sys.version_info (check the major version number) rather than slicing sys.version. Also remember randint(a, b) is inclusive of both endpoints. Use the conditional expression for short assignments only; when multiple branches or formatting are involved, an explicit if/elif/else or a small helper function improves clarity and maintainability.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.