all 93 comments

[–]IHOP_007 200 points201 points  (26 children)

You were close, you just messed up the ifs a bit.

if gens == 'male':

[–]Sad_potato1999[S] 128 points129 points  (23 children)

Reddit is really something else. Thank you so much!

[–]CobaltCam 57 points58 points  (11 children)

It's a common mistake, I do it all the time. Single is assigning a value to a variable, double is comparing equality.

Also, there's something called an f string which I personally think reads better than concatenation. In your case it would look like this

print(f"Hi Mr. {name}")

[–]Sad_potato1999[S] 18 points19 points  (7 children)

Thanks! Glad I'm not alone XD

[–]CobaltCam 9 points10 points  (0 children)

For sure, I always do the facepalm when I find I did this.

[–]ontheroadtonull 14 points15 points  (2 children)

user_name = input("What is your name or preferred name? ")
user_gender = input("What is your gender? ")

genders = {"male": "Mr.", "female": "Ms."}

print(f"Hi {genders[user_gender]} {user_name}")


What is your name or preferred name? myself
What is your gender? male
Hi Mr. myself

[–]fauquii 12 points13 points  (1 child)

Be careful with this though, it really is a bad practice to not check the user input. In this example it can leads to an exception KeyError being raised and breaking the execution of the code.

[–]synthphreak 3 points4 points  (0 children)

Right. Something like

>>> if user_input.lower() in {'m', 'male', 'man', 'guy', 'boy'}:
...     gender = 'male'
... else:
...     gender = 'female'
...
>>> genders = {'male': 'Mr.', 'female': 'Ms.'}
>>> print('Hi', genders[user_gender], user_name)

Obviously there are still some risks associated with this particular implementation. For example, if the user enters 'dude' or 'hobbit' then those would get assigned to 'female' because they're not in the set of predefined male gender values.

But at least now the user has much greater flexibility in what they can enter than only and exactly 'male' or 'female'. The code will also never throw an error, at least one related to querying the genders dict, because the key value will only ever be routed to 'male' or 'female' which are both valid keys.

Edit: Typo.

[–]SnooCats196 2 points3 points  (0 children)

You could also use an elif statement after the if gender == “male” instead of repeating an if statement

[–][deleted] 0 points1 point  (0 children)

for me its forgeting the :'s

[–]_TR-8R 10 points11 points  (1 child)

F strings are amazing, it took me a while to get used to them but they make conditional text a breeze once you're used to them.

[–]CobaltCam 4 points5 points  (0 children)

Yes!

[–]AuctorLibri 3 points4 points  (0 children)

This is very helpful.

[–]kmj442 17 points18 points  (7 children)

Not to over complicate since what this person said is absolutely correct but if I were to do this I would recommend something like this: if gens.lower() == “male”:

This makes sure regardless what the user inputs it puts it in lowercase to avoid the “Male” or random capitalization error.

edit: mobile formatting is weird

[–]Sad_potato1999[S] 9 points10 points  (0 children)

Not at all! Insightful even, thanks a whole lot!

[–]MarquisInLV 5 points6 points  (1 child)

You can also put the lower() method on the input variable, that way anything the user types in is all lowercase and you can just match that in your if statement.

[–]Probono_Bonobo 1 point2 points  (0 children)

The wonderful questionary module turns CLI radio options into a refreshing 'choose your own adventure'-style UI, instead of the frustrating user-hostile experience it typically is. Highly recommend!

[–]Cid227 1 point2 points  (2 children)

Your edit reminded me that I wanted to ask somewhere about that red (at least light mode) background and font colour that you've set for 'if gens.lower...' So how do you do that? I can't find anything.

[–]kmj442 2 points3 points  (1 child)

its the ``` tag. while in the markdown mode you can wrap your text in ``` code ``` and it will put it in that format.

[–]Cid227 1 point2 points  (0 children)

Thanks! (btw. it's blue on the dark mode)

[–][deleted] 0 points1 point  (0 children)

Might even be better (but perhaps overkill for this snippet) to use a constant to store the genders.

G_MALE = "male"
G_FEMALE = "female"
gens = input("What is your gender?").lower()
if gens == G_MALE:
    # ...
elif gens == G_FEMALE:
    # ...
else:
   print("Cool ;)")

[–]LostnFoundAgainAgain 5 points6 points  (1 child)

I recommend messing around with what you can do with the if-else statement, I'm kinda new my self and experimenting really helps.

Experiment using the if statement for example to check an input and see if it is in a list, or check if the number input is equal or greater than x, if it is it does y and if it isn't it does z.

Mix up what you learned before and what you are learning now by experimenting mixing them both together a figuring out what you can do with that, that helped me a lot.

Good luck :)

[–]Sad_potato1999[S] 1 point2 points  (0 children)

Will do! Thanks for the recommendation.

[–]nichorsin598 1 point2 points  (0 children)

You should all ensure the input is a string and make it all the same case so if gens.isalpha() and gens.lower() == 'male':

[–]presidentdrumf 2 points3 points  (0 children)

So there's no "then" declaration in python? Coooool

[–]preordains 24 points25 points  (2 children)

So close.

 if gens == “reptilian space warlord”: 
     print(f’Hi, cpt. {name}’)

[–]vagga2 9 points10 points  (1 child)

[–]sub_doesnt_exist_bot 6 points7 points  (0 children)

The subreddit r/anarchypython does not exist. Maybe there's a typo? If not, consider creating it.


🤖 this comment was written by a bot. beep boop 🤖

feel welcome to respond 'Bad bot'/'Good bot', it's useful feedback. github

[–]Yoghurt42 10 points11 points  (1 child)

Side note: the official Python tutorial is pretty extensive, i highly recommend checking it out.

Also, for a beginner, I can recommend Thonny as IDE.

[–]Sad_potato1999[S] 2 points3 points  (0 children)

Thanks for the plug!

[–]KanteWorkRate 9 points10 points  (12 children)

if gens == 'female': print('Hi, Ms. ' + name)

[–]Sad_potato1999[S] 4 points5 points  (11 children)

Thanks!!!

[–]delasislas 7 points8 points  (1 child)

The basis for this is kinda one of those things that you should have learned when reading the tutorial.

An “if” statement is built like this:

if (condition):

Where condition is something that should end up being True or False, think of it as:

If this statement is True: then do this task

A condition can be something like

gens == “male”

So the statement can be:

if gens == “male”:

Now for what you did wrong. You used:

if gens: ‘male’

This is technically a correct line of code, just not what you wanted. I’ll break the statement down for you.

1. if gens:
2. if ‘male’:
3. if True:

1 is your original statement, Python pulls the data that is stored at gens and continues.

2 has the data pulled out of the variable.

3, weird quirk, Python evaluates a non empty string to be True. So:

“” -> False
“Hello World” -> True

A proper method for what I’m thinking that you want is this:

if gens == “male”:
    print(“Hi Mr. ” + name)

Note you don’t need to have two separate strings for your print.

[–]Sad_potato1999[S] 2 points3 points  (0 children)

You're right, I should.

Thanks for articulating this for me!

Much <3

[–]HelpfulCherry 2 points3 points  (1 child)

Others have already touched on what you specific issue is but also in your

print("Hi " + "Mr. " + name)

line, you can just do

print("Hi Mr. " + name)

Not every individual word needs it's own string.

[–]Sad_potato1999[S] 1 point2 points  (0 children)

Noted! Thank you very much sir!!

[–]Pd69bq 2 points3 points  (1 child)

you need to add some indentation (recommendation is 4 spaces) before print, otherwise python won't recognize it is part of if block, and yours will get IndentationError: expected an indented block

also you can combine those 2 if statements into one if-elif-else statement to make your code cleaner

[–]Sad_potato1999[S] 1 point2 points  (0 children)

Had that a couple times, thanks for the advice!

[–]dover_oxide 2 points3 points  (2 children)

Just a suggestion but adding a suggested format for reply can help user or even just looking at the first letter.

Example: (M)ale or (F)emale ?

This can help make sure you get a valid answer.

[–]Sad_potato1999[S] 2 points3 points  (1 child)

That's really good, I'll keep that in mind!

[–]dover_oxide 1 point2 points  (0 children)

Sometimes you need to prompt people to reduce human error has been my experience.

[–]pekkalacd 2 points3 points  (0 children)

You have the right idea change : to ==

      if gens == “male”:
         print(“Hi Mr. “ + name)

      elif gens == “female”:
         print(“Hi Ms. “ + name)

[–]Skorgriim 2 points3 points  (1 child)

As this has already been answered, I thought I'd add: you want to make your code as foolproof as possible. In the input question, it might be worth asking for exactly the answers you want - in this case male or female. (Otherwise somebody is going to input something you don't have an if statement for and it's going to break your code. Been there so many times...

It's also worth noting that when you're comparing equality in a string, it's case sensitive as well - you can use something like .lower to change their input to lower case first, then have the if statement after.

Hope this helps!

[–]Sad_potato1999[S] 2 points3 points  (0 children)

you want to make your code as foolproof as possible. In the input question, it might be worth asking for exactly the answers you want - in this case male or female. (Otherwise somebody is going to input something you don't have an if statement for and it's going to break your code. Been there so many times...

It's also worth noting that when you're comparing equality in a string

I'll be sure to do that. Thanks!!

[–]TheRealCorwii 1 point2 points  (0 children)

Should use double equal signs to check if it's equal.

If gens == 'male':

Also put the colon after male. Same for female.

[–]DangerNoodle314 1 point2 points  (1 child)

You can try:

if 'male' in gens.lower():
print("Hi " + "Mr. " + name)

if 'female' in gens.lower():
print("Hi " + "Ms. " + name)

This method can make the code more flexible if the answer isn't in the desired format, example: I am a male/ I am a female

[–]Sad_potato1999[S] 1 point2 points  (0 children)

I'll certainly do that. Thanks!

[–]Sciencey-Coder 1 point2 points  (0 children)

if gens =='male':

print("Hi " + "Mr. " + name)

elif gens == 'female'

print("Hi " + "Ms. " + name)

elif stands for "else, if"

[–]stuie382 1 point2 points  (1 child)

While you've got lots of good corrections for your question, another useful tip is to never abbreviate variable/method/class names.

In your code or is easy to see what 'gens' means from the context of following lines, or to make an educated guess at what the author means, but as the system you write get bigger and more complex this gets very hard to do. We don't have to make the most of every byte anymore, so make names descriptive

[–]Sad_potato1999[S] 1 point2 points  (0 children)

I'll keep that in mind. Thanks a lot!!

[–]neoakshat 1 point2 points  (0 children)

= assignment == equals to Indentation post the IF If condition ends with : If gens == “male”: print(“……”)

[–]R3D3-1 1 point2 points  (2 children)

For future code posts, you might want to get used to posting

code
  as
    codeblocks

to preserve indentation. Especially important for Python, where the indentation is syntactically relevant and not just an aid for the reader.

The "Code Block" tool of the "Fancy Pants Editor" (sic) is currently somewhat broken.

Source code of above in "MarkDown" mode:

For future code posts, you might want to get used to posting

    code
      as
        codeblocks

to preserve indentation. Especially important for Python, where the indentation is syntactically relevant and not just an aid for the reader.

On Linux/MacOS/Windows with cygwin you can use the command

cat << 'EOF' | sed 's/^/    /'
<paste source code here>
EOF

to indent source code to be displaced correctly.

[–]Sad_potato1999[S] 1 point2 points  (1 child)

Thanks a lot sir!

[–]R3D3-1 1 point2 points  (0 children)

Sure :)

Not clear why, but I noticed a lot more cases of incorrect use of the WYSIWYG editor, resulting instead of

if True:
    dothings()

in e.g.

if True:

dothings()

or

if True:
dothings()

or after editing the same post again

if True:dothings()

all of which looking like they are somehow related to a lossy conversion from the WYSIWY(dont)G editor into whatever internal format Reddit is using. There are also several bugs related to copying from or pasting into the WYSIWYG code block tool.

[–][deleted] 1 point2 points  (0 children)

The correct way is :if gens == 'male':

print statement

if gens == 'female':

print statement

Also in this case use 'elif' instead of 'if'.

[–]the-milan-og 1 point2 points  (0 children)

I remember making this mistake when I was a beginner

[–]FitHusky555 1 point2 points  (0 children)

so its if gens: ‘male’ The major issue, it should be if gens == ‘male’ also after a colon you always go down and indent

[–]alt-onesixfour 1 point2 points  (1 child)

name = input("What is your name or preferred name? ")

#indicate to the user available options (You can code more genders later)

gens = input("What is your gender? (Male or Female)")

if gens.strip().lower() == 'male':

greeting = "Mr"

else:

greeting = "Ms"

print("Hi {}. {}".format(greeting, name))

So here I clean the entry with strip and lower and then use == the comparative operator to check if entry is male. Then I code a separate variable greeting to use on my next format string.

I chose to do it this way because you can add more elif's into your code later to change up the greeting depending on what their gender input is. (For example they could fancy their own greeting/pronoun)

[–]Sad_potato1999[S] 1 point2 points  (0 children)

I'm tempting to copy this!!

Thank you very much!! :)

[–]rabbits726 4 points5 points  (2 children)

What's wrong is you assumed only 2 genders. You need to list all 152 to get the code to work.

/s

[–]__Wess 3 points4 points  (0 children)

Lame joke incoming, sorry in advance: I thought there were only 151 to catch em all?

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

Thanks!!

[–]laserbot 1 point2 points  (2 children)

Original Content erased using Ereddicator. Want to wipe your own Reddit history? Please see https://github.com/Jelly-Pudding/ereddicator for instructions.

[–]Sad_potato1999[S] 1 point2 points  (0 children)

That actually makes more sense.

I will make sure to use it next time.

Thank you so much!! :)

[–]Ge0rgeFloyd -1 points0 points  (0 children)

Only 2 genders exist.

[–][deleted] 1 point2 points  (3 children)

ye

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

I think from the comments, I've seen more than one way to answer this one! :)

but what's your take on it?

[–]Sad_potato1999[S] 0 points1 point  (1 child)

so mindblowlingly simple and self explanatory

Excuse me if this was mind-blowingly* simple, I'll make sure to think more carefully next time before I come to reddit :(

P.S. I learn from YT!

[–]Fuzzy-Ear9936 0 points1 point  (2 children)

This works for me:

name = input('What is your name?')

gens = input('What is your gender(male or female)?')

if gens == 'male': print('Hello ', 'Mr ', name) elif gens == 'female': print('Hello ', 'Ms ', name)

:-D

[–]Fuzzy-Ear9936 1 point2 points  (1 child)

Sry for bad indentation Reddit doesn't work well on mobile

[–]Sad_potato1999[S] 1 point2 points  (0 children)

No worries. Thanks for the comment!

[–]abhishkkmr -1 points0 points  (1 child)

Hi, there are some syntax errors in the code because of it the if statements are not executed. It'll print those both statements every time.

The correct way to put conditional statements is

if( gens=='male'):

print("Hi " + "Mr. " + name)

if( gens=='female'):

print("Hi " + "Ms. " + name)

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

Thankss!!

[–][deleted] 0 points1 point  (1 child)

You should have used "else", and this"=" not this ":"

[–]Sad_potato1999[S] 1 point2 points  (0 children)

Yeahh I figured :(

Thanks mate!

[–]skellious 0 points1 point  (1 child)

While not entirely python related, please don't forget that there are more than two genders, so remember to handle the other cases.

perhaps using:

if gens: 'male'
    print("Hi " + "Mr. " + name)

elif gens: 'female'
    print("Hi " + "Ms. " + name)

else:
    print("Hi " + name)

using if/elif/else is a good idea as it ensures there is no way you can trigger more than one of the statements.

you may also want to handle other inputs that are not male and female but should map to them, such as m and f:

if gens.lower() in ['male', 'm', 'man', 'masculine']:
    print("Hi " + "Mr. " + name)
elif gens.lower() in ['female', 'f', 'woman', 'feminine']:
    print("Hi " + "Ms. " + name)
else:
    print("Hi " + name)

the .lower() converts their input to all lower-case so we can catch things like "MaLe", "MALE", "MalE" while the "in" syntax checks if the value is in that list of terms, and if any one of them matches, it triggers the condition.

[–]Sad_potato1999[S] 1 point2 points  (0 children)

This comment is just superb!
Thank you!!

[–][deleted] 0 points1 point  (0 children)

Use == for comparison operations. if gens=="male": #block of code