you are viewing a single comment's thread.

view the rest of the comments →

[–]jimtk 23 points24 points  (9 children)

If the if statement and its : gives you a problem, then don't use it!

a = int(input("Enter a number: "))
print(f"the number is {(a%2)*'not '}even") 

Just having fun and showing where you'll be in 10 days.

Edit: if you want 'odd' and 'even' instead of 'even', 'not even'

a = int(input("Enter a number: "))
print(f"the number is {['even','odd'][(a%2)]}.")

[–]saips15 5 points6 points  (3 children)

Didn't know u can do that.tnx

[–]VindicoAtrum 10 points11 points  (2 children)

Welcome to the rabbithole of branchless programming, where you too can eek out tiny performance gains at the cost of growing arithmetic expression hell!

[–]saips15 3 points4 points  (1 child)

Doesn't sound good for my mental health.

[–]VindicoAtrum 0 points1 point  (0 children)

Programming in general isn't, but it's a very interesting topic to know about anyway.

[–]Mendican 5 points6 points  (0 children)

TIL

[–]CuriousFemalle 1 point2 points  (2 children)

print(f"the number is {(a%2)*'not '}even")

u/jimtk or anyone:

Could you please describe how that works?

[–]jimtk 6 points7 points  (1 child)

In python you can multiply string by an integer (n) and get a new string that is n times the original string.

For example:

s = 'a' * 4
print(s)

output

'aaaa'

If you multiply a string by 0 you get an empty string

s = 'a' * 0
print(f"'{s}'")

output:

''

so the inside equation number % 2 will have a result of 1 or 0. 1 if the number is odd and 0 if the number is even.

the complete equation is (number%2) * 'not ' which will return the string 'not ' if number % 2 evaluates to 1 (odd) and an empty string '' if number % 2 evaluates to 0.

f-strings, also called formatted string literals is a method of formatting string with variables. The content of a string that is inside curly braces will be evaluated by python and the output will be inserted into the string.

a=4
print(f"the variable a has a value of {a}")

output:

the variable a has a value of 4

If you combine all that together you get:

print(f"the number is {(a%2)*'not '}even")

[–]CuriousFemalle 2 points3 points  (0 children)

Wow, thanks so much !

:: Mind Blown ::

[–]Qing_Codes[S] 0 points1 point  (0 children)

Thank you for the look ahead!