0

I'm new to programming. I searched for an answer but didn't seem to find one. Maybe I just can't Google properly.

I want to get something True, when the user inputs anything. Example:

another_number = input("Want to enter another number? ")

What I want:

if another_number = True
   float(input("Enter another number: "))

Sure I can say if another_number = ("Yes", "yes", "Y", "y") but in my program I want to get True when entering really anything.

Matt Hall
  • 7,614
  • 1
  • 23
  • 36
  • 1
    ```if another_number:``` simply will do. Any **non-empty** string in python always evaluates to True –  Jul 23 '21 at 17:03
  • Welcome to StackOverflow! Perfectly reasonable question, good for you for asking and using code formatting etc. Good luck with learning Python! – Matt Hall Jul 23 '21 at 17:06
  • By the way, you mentioned the other option of checking a list of strings. Sometimes people do this sort of thing: `if another_number.lower() in ("yes", "y", "ok")` — casting to lowercase means you only have to check once. (Strictly speaking `str.casefold()` is the proper way though.) – Matt Hall Jul 23 '21 at 17:11

2 Answers2

0

Strings that contain characters are 'truthy', so you can do something like:

if another_number:
    x = float(input("Enter another number: "))

The empty string is 'falsy', so this produces nothing:

s = ""
if s:
    print("s has characters")

This trick also works on other Python objects, like lists (empty lists are falsy), and numbers (0 is falsy). To read more about it, check out answers to this question.

Matt Hall
  • 7,614
  • 1
  • 23
  • 36
0

In python, any non-empty string is evaluated to True. So, you can simply do:

another_number = input("Want to enter another number? ")
if another_number: #==== Which means 'if True'
   float(input("Enter another number: "))

And that will allow for any input.

Alternatively, you can also fo:

another_number = input("Want to enter another number? ")
if another_number!='': #=== if string is not blank as without entering anything, '' is returned. You can also use ```if len(another_number)!=0: where the length of the string is not 0
   float(input("Enter another number: "))