Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
68 views
in Technique[技术] by (71.8m points)

python - Is there a way to make a variable equal to two if statements?

I am making some code that tells you if a message is a number or a word(s).

def find_type(message):
    isneither == (if message.isdigit() == False and message.isalpha() == False)

    if message.isdigit() == False and message.isalpha() == False:
        print('Your message is neither a word nor a number.')

    if message.isalpha() == True:
        print('Your message is a word!')
        if message.isdigit() == False:
            return
    else:
        if message.isdigit() == False:
            return
        print('Your message is not a word.')    

    if message.isdigit() == True:
        print('Your message is a number!')
    else:
        if message.isalpha() == False:
            return
        print('Your message is not a number.')

message = '1239'

find_type(message)

and there is some code at the top (that doesn't work) that is trying to make a variable be two if-statements.

How would I be able to do this?

question from:https://stackoverflow.com/questions/65617558/is-there-a-way-to-make-a-variable-equal-to-two-if-statements

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

it's great seeing you (starting?) to code. Getting better has a lot to do about giving yourself tasks and find ways to translate them into code. Great! I'd like to share the way I would solve this task. It works with the same string methods but a little shorter :) and is returning for each case rather than printing. Go with what suits you most.

def find_type(message):
    #
    # case message is numeric
    if message.isdigit():
        return 'Your message is a number!'

    # case message is alphanumeric
    elif message.isalpha():
        return 'Your message is a word!'

    # case message is neither a number nor a word
    else:
        return 'Your message is neither a number nor a word'

# Examples
msg1 = '123'
find_type(msg1)
>>> 'Your message is a number!'

msg2 = 'abc'
find_type(msg2)
>>> 'Your message is a word!'

msg3 = '!?*'
find_type(msg3)
>>> 'Your message is neither a number nor a word'

Moving a step forward, what if the message isn't so clean like having mixed types (numbers, words, special characters) within?

mixed_msg = '123abc?!*69+-HelloWORLD!~{}bye'
find_type(mixed_msg)
>>> 'Your message is neither a number nor a word'

But I would rather prefer, it would give me back for example all words like 'abc', 'HelloWORLD', 'bye' and likewise for the other types.
This is where you might want to start working with regex patterns. It can be overwhelming at the beginning with what is going on but once one figures out how to use regex patterns, it can be a great deal of help! It might be off what you have been looking as an answer for, nonetheless the direction is still somewhat appropriate I think ;) (and doing my best explaining what is going on...)

Part I

# Using regex for a mixed message
# regex is a built-in module in python. To be able to work with it, it needs to be imported 
import re

# In general modules have methods and attributes which one can work with
# Besides good documentation available online for a lot of modules, to get a general overview 
# (although without any explanation on how to use them) is using dir()

dir(re)
>>>['A',
 'ASCII',
 'DEBUG',
 'DOTALL',
 'I',
 'IGNORECASE',
 'L',
 'LOCALE',
 'M',
 'MULTILINE',
 'Match',
 'Pattern',
 'RegexFlag',
 'S',
 'Scanner',
 'T',
 'TEMPLATE',
 'U',
 'UNICODE',
 'VERBOSE',
 'X',
 '_MAXCACHE',
 '__all__',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '__version__',
 '_cache',
 '_compile',
 '_compile_repl',
 '_expand',
 '_locale',
 '_pickle',
 '_special_chars_map',
 '_subx',
 'compile',
 'copyreg',
 'enum',
 'error',
 'escape',
 'findall',
 'finditer',
 'fullmatch',
 'functools',
 'match',
 'purge',
 'search',
 'split',
 'sre_compile',
 'sre_parse',
 'sub',
 'subn',
 'template']

# Let's start working with some of them...

# So we have our mixed message
mixed_msg = '123abc?!*69+-HelloWORLD!~{}bye'

# Can we define now a pattern that gives us back all words together, 
# all numbers together and all special characters together? 
# Obviously, YES! with regex and here is how it goes:

# Patterns: 
#  – looking for digits:              d
#  – looking for words:               [a-zA-Z]
#  – looking for special characters : W

# For an in-depth explanation on these patterns, have a look at:
# https://www.w3schools.com/python/python_regex.asp

# Combined to one pattern looks like this:
pattern = '(d+)|([a-zA-Z]+)|(W+)'

# What is going on here?!
# given mixed_msg to this pattern will tell regex to first look for 
# one or more digits:
#  – pattern d+ (the plus is telling to look for one or more digits)
# gives back '123'. 
# Now the parenthesis around d+ tell regex to group the findings. 
# Since (d+) is at the beginning of our pattern, we get a 
# tuple back where the first entry is '123': ('123',...,...)

# What are the other entries? Since we have a '|' between each group,       
# this tells regex to look for alternatives like the operator 'or'
# So besides '123' are there words (pattern [a-zA-Z]) for the same first three positions?
# Obviously not, since it has found already the digits (likewise for special characters)
# So we get: ('123','','') nothing for position 2 and 3

# The important part is, that we always get digits as first entries, 
# words as second and special characters as third with the above pattern

# Since we have a working regex pattern, we'd like to find now all 
# occurrences of either numbers, words or special characters. There we 
# can use the handy method 'findall' of re (remember the overview with dir(re))

# Find all occurrences
matches = re.findall(pattern, mixed_msg)
matches
>>> [('123', '', ''),
     ('', 'abc', ''),
     ('', '', '?!*'),
     ('87', '', ''),
     ('', '', '+-'),
     ('', 'HelloWORLD', ''),
     ('', '', '!~{}'),
     ('', 'hello', '')]

# From here on is a little step onwards to get all numbers, all words 
# and all special characters together. Basically, they are the columns of 
# matches, right? A practical way to read them out columnwise, 
# is with an numpy array. 

Part II

# Hold on, what's going on here again?! Glad you ask :D
# numpy is another module, that is great for working with more 
# dimensional arrays also known as matrices as an example

import numpy as np

# create numpy array
array_np = np.array(matches)
array_np
>>> array([['123', '', ''],
           ['', 'abc', ''],
           ['', '', '?!*'],
           ['87', '', ''],
           ['', '', '{}\'],
           ['', 'hello', '']], dtype='<U5')

# It is similarly structured as above matches with the main difference that columns can be retrieved easily

# Retrieve all numbers (or first column)
numbers = array_np[:,0]    # ':,0' in the brackets means from every row (':')
                           # get the first (index 0) entry

numbers
>>> array(['123', '', '', '87', '', ''], dtype='<U5')

# Now to just get the values without the empty strings '', we can use
# a list comprehension
numbers = [int(n) for n in numbers if n]    # for tells to iterate over every entry (n) in numbers
                                            # and to grab n if it has value (if n)
                                            # if '' returns false and gets rejected
                                            # in contrary to if '123' returns true and is kept

# Likewise for words and special characters
words = [word for word in array_np[:,1] if word]    # [:,1] is second column (indexing starts at 0, that's why 1 gets the second column)
specials = [spec for spec in array_np[:,2] if spec] # [:,2] for third column

# Finally, that's what we've retrieved from the regex search pattern
numbers
>>> [123, 87]

words
>>> ['abc', 'HelloWORLD', 'hello']

special
>>> ['?!*', '+-', '!~{}']

I somewhat think, I got way off with my answer with what you've initially asked for. Wasn't the question how to make a variable to be two if-statements? Heck, what is going on here?! :D
This might be off, nonetheless I hope the more or less detailed explanation can enhance your programming understanding and keeps you motivated further exploring. Enjoy!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...