One of the comments on the Python video made me laugh out loud

Joined
Jul 4, 2023
Messages
507
Reaction score
63
Like in title ...
One of the comments on the Python video made me laugh out loud. ๐Ÿ˜

CLEVER Python One Liner!!

1722432253027.png
๐Ÿ˜‚๐Ÿ˜œ

Here is code from movie
Python:
user_input = input('Name: ')

if user_input:
    name = user_input
else:
    name = 'N/A'

print(name)

another version of the code shown above, proposed by the author of the video
Python:
user_input = input('Name: ')

name = user_input or 'N/A'

print(name)

other proposed code version
Python:
name = input('Name: ') or 'N/A'
print(name)

user_input = input('Name: ')
name = user_input if user_input else 'N/A'
print(name)

print(input('Name: ') or 'N/A')

# remove white space
name = input('Name: ').strip() or 'N/A'
print(name)

print(name:=input('Name: ') or 'N/A')
# and now you can use the "name" variable too

# My code suggestion
import re

# remove white space and the name must be longer than 2 characters
name = re.sub(r'^.{1,2}$', '', input('Name: ').strip()).strip() or 'N/A'
print(name)
 
Last edited:
Joined
Sep 21, 2022
Messages
189
Reaction score
26
Personally, I wouldn't code like that. IMO it breaks one of the "structured programming" rules, cohesion.

By cohesion, I'm refering to the idea that a subroutine must do ONE thing, a variable must have ONE meaning.

When a single line of code does many things, it is not cohesive. Program maintenance will be hard.

For anyone who has not heard about structured programming, they're guidelines that allow programmers to make VERY large programs.
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,056
Messages
2,570,443
Members
47,089
Latest member
Bobby2025b

Latest Threads

Top