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
print('What number between 0 and 100 I am thinking')
while not found:
        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')
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.