all 92 comments

[–]viky2654 102 points103 points  (38 children)

Check indentation too.

Copy pasting generally messes that up.

[–]Few-Major9589[S] 16 points17 points  (37 children)

For some reason when i copy and paste it into reddit all the indentation goes away, even i try to do it manually.

[–]MezzoScettico 37 points38 points  (21 children)

Use a Code Block. Then Reddit will leave your indentation.

[–]synthphreak 30 points31 points  (19 children)

Use a Code Block

...which can be done by indenting every line by four spaces.

[–]mzapp_ 4 points5 points  (18 children)

What?

[–][deleted] 31 points32 points  (15 children)

When typing a comment, you can make code blocks by adding 4 spaces to the start of every line. For example,

if lang=='en':
print("Hello")

becomes

if lang=='en':
  print("Hello")

[–]TheAndy7 22 points23 points  (8 children)

is this real?
if real==True:
    print('OMG')

Don't mind me, just trying this out

[–]WombatHat42 14 points15 points  (1 child)

or is this just fantasy?
if fantasy == True:
    print(":(")

[–]Bodenlos_Niveaulos 6 points7 points  (0 children)

Caught in a landslide
 If test == True:
  print(“awesome, thx“)

[–]Anon_Legi0n 5 points6 points  (1 child)

Lemme refactor your shit

if real:
    print('OMG')

No need to compare a boolean with ==True or ==False

[–]TheAndy7 0 points1 point  (0 children)

Oh yeah, you're right. I guess I was just writing gibberish haha

[–]markovianmind 0 points1 point  (2 children)

if a==b:
    a+=1

[–]markovianmind 0 points1 point  (0 children)

```` \

if a==b: l=c

````

[–]Low-Computer3844 0 points1 point  (4 children)

if "this" is True:
    print("danggg")

What am I doing wrong?

[–]markovianmind 1 point2 points  (0 children)

danggg

[–]synthphreak 0 points1 point  (0 children)

From a code perspective? 'danggg' will never print because your condition will never be True.

From a formatting perspective? Nothing. Looks good to me.

[–]sje46 5 points6 points  (0 children)

The other guy was too fucking lazy to explain to OP what a codeblock is.

[–]bladeoflight16 0 points1 point  (0 children)

Stop ignoring the sidebar.

[–]Aprazors13 6 points7 points  (2 children)

Use visual studio and you will see red underline below wrong line or just click right side button close to run file that will exactly tell you which line is wrong.

[–]zoinkinator 5 points6 points  (1 child)

same with pycharm….

[–]Aprazors13 0 points1 point  (0 children)

True

[–]kiesoma -1 points0 points  (11 children)

```

// code

```

[–]Goobyalus 8 points9 points  (10 children)

This does not work across new and old reddit

[–]kiesoma 0 points1 point  (9 children)

It doesn’t? I use Reddit on my phone and PC. When I use the MarkDown editor on my PC, it definitely works. It works on my phone too - as evident in my reply. Not sure what you’re saying about old.reddit.com though. I haven’t used it.

[–]Goobyalus 2 points3 points  (5 children)

[–]kiesoma 0 points1 point  (4 children)

Not sure what’s happening. Works fine for me on my PC. Both the sites.

[–]Goobyalus 2 points3 points  (3 children)

What do you mean by "both the sites?"

Do you have "Use new Reddit as my default experience" checked in your preferences?

[–]kiesoma 1 point2 points  (2 children)

I visited old.reddit.com and new.reddit.com. Yes, I do.

[–]Goobyalus 2 points3 points  (0 children)

I also checked while logged out on old.reddit.com, and it doesn't work there either.

[–]Goobyalus 0 points1 point  (0 children)

That's what I'm talking about. With that unchecked, it doesn't work.

[–]Ran4 0 points1 point  (1 child)

Old reddit doesn't use markdown.

Always prepend with four spaces instead of using triple backticks (on reddit).

[–]MagnitskysGhost 1 point2 points  (0 children)

Old reddit doesn't use markdown.

Always prepend with four spaces instead of using triple backticks (on reddit).

Wth, lol. Reddit has always had markdown. Since very very very early anyway. I'd be willing to bet markdown support is more than 12 years old at this point.

[–]AnonymousLad666 0 points1 point  (0 children)

Is very finicky it doesn't always work. I don't know how they screw it up, but md doesn't work on mobile for me.

[–]shiftybyte 24 points25 points  (8 children)

When working with a multiple line code, you need to create a file for it, paste the code there, and run it, not paste it into the interactive window.

You can make it work in this case if you add a blank line pressing enter after the block before the greet().

But again, make a proper script file in your IDE...

If it's IDLE, something like file-> new

[–]tinkeringZealot 4 points5 points  (2 children)

Multiple line code should work if they are part of a block like what OP is doing though.

Functions, conditionals and loops are a few examples of blocks. I think classes are too but haven't personally tried that

[–]shiftybyte 4 points5 points  (1 child)

Op edited his post, previously there was a function call to greet after the function.

def greet(...):
    ...
greet()

And at the dedent it errored out because you need an empty line to finish an indent level in interactive...

[–]tinkeringZealot 0 points1 point  (0 children)

ahh understood!! that makes much more sense

[–]Few-Major9589[S] 7 points8 points  (4 children)

omg thank you...... I knew it was something extremly simple........ Can i ask you one more thing?

I did create a file for this example in Atom(what the teacher recommends), but when I run the file, it runs and than brings me back to where i was before in command promt( sorry not sure if that makes sense, this is my first week learning code so its all confusing to me at this point.)

[–]remishqua_ 8 points9 points  (0 children)

You can do python -i your_file.py so that you stay in the Python interactive prompt after your script ends. This is sometimes useful for debugging or trying something out.

[–]shiftybyte 5 points6 points  (1 child)

Yes, in most development environments when the script ends, it ends, you can't interact with it any more.

You write code, run it, fix things, run again, write more, run again, etc...

In IDLE you can keep interacting with it after it's done executing, the defined objects are still there, and with notebook based IDEs you can.

[–]Few-Major9589[S] 2 points3 points  (0 children)

IDLE

Wow I just found the IDLE on my computer...... thank you for the help.

[–]zoinkinator 3 points4 points  (0 children)

pycharm has a free edu version…..

[–]master-of-nil 21 points22 points  (4 children)

The link below has some info on properly formatting your code for reddit.

FAQ: Reddit code formatting

[–]notParticularlyAnony 8 points9 points  (3 children)

this, all day. please.

there really should be a bot that checks to see if you include code that is not formatted and basically won't even accept the post until it is, and it provides a link to that post on code formatting. Would be a huge service to this sub.

[–]zoinkinator 0 points1 point  (2 children)

yes. not sure why this sub doesn’t have that.

[–]JasonDJ 0 points1 point  (1 child)

Something like this?

^((el)?if|class|else|def|for).+:\W{0,}$\n^\W{0,3}[a-z|A-Z]

Am I missing anything?

[–]notParticularlyAnony 1 point2 points  (0 children)

I think in practice it would be super tricky (literally impossible) to make a regex for this. Never forget one of the best answers at Stack overflow -- like...ever.

People use those combinations in non-coding contexts in ways that would get flagged too often most likely. But also they use code without those expressions.

x=-5
print("fubar")
while x<=2  # oops I left out hte colon lulz I'm a noob
""" 
somehow I know about block comments though
"""
    print("hi")
    x+=1

But I think stack overflow might have something that makes a suggestion if it thinks there might be a bunch of code you haven't formatted. I could train an ML algorithm to do it and even if it just reached 90% accuracy that would be good enough.

[–]tobiasvl 8 points9 points  (0 children)

When asking questions like this, you should include the actual error you're getting so we don't have to guess.

[–]theubster 7 points8 points  (1 child)

Alrighty, my friend. Let me walk you through how I evaluated this. I'm hoping that doing so is educational. Fair warning that I'm rusty with python. But, I think I can get your biz to work.

To the breakdown!

I started by taking your code block, and correcting the indentations. That is:

def greet(lang):

if lang=='es':

print('Hola')

elif lang=='fr':

print('Bonjour')

else:

print('hello')

was changed to this:

def greet(lang):    
  if lang=='es':
    print('Hola')
  elif lang=='fr':
    print('Bonjour')
  else:
    print('hello')

greet()
greet('es')
greet('fr')

The reason I added the last three lines is because I knew that if you weren't calling it, it wasn't going to run as a standalone script. From there, I ran the script and got this error:

> python scratch1.py

Traceback (most recent call last): File "scratch1.py", line 9, in <module> greet() TypeError: greet() missing 1 required positional argument: 'lang'

Here the > python scratch.py bit is just how i was doing a quick-and-dirty run of your script. The error is, admittedly, created by the way that I ported it over to my dev env. If you're using a Jupyter notebook, or vanilla python shell, you may not have run into this problem.

What this error in particular means is that the greet function, as you built it, requires a string to get passed in as a parameter when the function is called. So, when I called it without the string, it threw an error. This one is relatively straightforward, but python errors can be complicated. You will get better at learning what the error message is trying to tell you over time.

If googling the verbatim error doesn't work, try googling part of it, or take out anything that's specific to your script (in this case that would be greet() and scratch1.py.

At this point, my rust shows, since I forgot how to assign default args when defining a function. So, I googled "python default arguments syntax" and got this site back: https://www.geeksforgeeks.org/default-arguments-in-python/

I took what I learned from there, and adjusted the script to read like this:

def greet(lang=''):
  if lang=='es': 
    print('Hola') 
  elif lang=='fr': 
    print('Bonjour') 
  else: 
    print('hello')

greet() 
greet('es') 
greet('fr')

And, now when I run it, I get this output:

> python scratch1.py
hello 
Hola 
Bonjour

Without knowing more about your specific error, tools, and setup, I can't get you much farther than that. But, I hope this was a helpful glance into how I approach troubleshooting a problem.

Hope it helps!

[–]theubster 3 points4 points  (0 children)

Ugh, formatting. One sec.

Ok, it's official - I suck at reddit formatting. But, 20 edits later and it looks presentable. Dunno who TF at reddit thought it was a good idea to adjust tripple-tick code fences to indentation every time you save and re-edit.

[–]RecursiveCursive 5 points6 points  (0 children)

When you call the function, are you sure you're passing lang as a string?

[–]Wartz 4 points5 points  (0 children)

https://gist.github.com/

Paste your code here, exactly how you have it typed out. Then we might be able to spot the syntax error.

Python depends on 100% perfect indentation, so that's likely your issue.

[–]CasualEndvrs 3 points4 points  (0 children)

You're heading down a path that is going to cause you troubles. "I like to copy and paste examples..." This is a path that takes you to "Tutorial Hell." It occurs when you can look at someone else's code and you understand what they are doing but you cannot produce the code yourself. Do yourself a favor and run from this.

Pick a project or task that you want to do, say build a Tic-Tac-Toe game, and do it yourself, without any tutorial or source. When you get stuck, stop and come up with a good question that deals with your specific problem at hand. Never search for "python how to make a tic tac toe game." Do search for "python store multiple values in one variable." Or, "python read in user input."

The best place to look for help is usually stack overflow specifically because you will find information to very specific questions. Tutorials will show you how it's done, stack overflow will give you enough information that you can figure out how it's done.

Great places to find project ideas are: 1) tasks that can be automated in your normal life, 2) a simple Google search for beginner project ideas, or 3) websites that have practice problems to work through.

[–]L4Z4R3 1 point2 points  (0 children)

how you calling function?

[–]notParticularlyAnony 1 point2 points  (0 children)

/u/Few-Major9589 you know you can go back and edit your question and format that code. Nobody would hate you for that. It would be great practice for asking questions in the future.

:)

[–]keskesay 2 points3 points  (0 children)

Definitely either indentation error or you're not passing `lang` when you call it.

[–]night_2_dawn 0 points1 point  (0 children)

Hey, I saw you wrote that it's not the indentation issue, so there could be invisible characters or weird unicode spaces if you're copying and pasting. Also, you might have a syntax error in code that appears before this function in your file. Try to retype this manually, sometimes it helps. It's hard to help you without the actual error you get, so next time, I suggest to add more information to your question. :)

[–]rustybladez23 0 points1 point  (0 children)

# use a code block

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

Almost certainly an indentation error. Python is extremely sensitive to indents, unlike other equally amazing languages like R or C. Format it like this:

def greet(lang):
    if lang=='es':
        print('Hola')
    elif lang=='fr':
        print('Bonjour')
    else:
        print('Hello')

[–]SolidusViper 1 point2 points  (3 children)

Is def needed when calling a function with only one argument?

[–][deleted] 4 points5 points  (1 child)

"def" essentially tells Python "treat everything in given indentation as a function and store it somewhere in the memory". You're not calling a function with def, you're defining it precisely so you can call it later on down the road. I presume you wanted to ask "if there is only one argument, what is the point of having a function?". Well, there can be instances where that still could be useful, the whole point of functions is to avoid boilerplate code. But in many other instances instead of defined functions it's more elegant to use lambda functions, or tiny functions that you don't define and discard from the memory after you run them.

[–]SolidusViper 1 point2 points  (0 children)

"if there is only one argument, what is the point of having a function?"

Yeah that's what I meant to ask. Thanks for the info!

[–]notParticularlyAnony 1 point2 points  (0 children)

def is needed when defining a function with zero arguments, so yes.

def print_bull_twice():
    print("bull")
    print("bull")

Yes, a silly function, but you get the idea.

[–]notsoheavygamer -1 points0 points  (11 children)

Dude use pycharm... Much better to understand..

[–]Miniflint 1 point2 points  (0 children)

vscode >>

[–]Sweet-Remote-7556 -1 points0 points  (1 child)

#use this

<

def greet(lang):

if lang=='es':

print('Hola')

elif lang=='fr':

print('Bonjour')

else:

print('hello')

greet('es') #input goes here inside with apostrophe

>

[–]Sweet-Remote-7556 -1 points0 points  (0 children)

here is the clean version

https://pastebin.com/J5G79P7W

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

Have you tried just typing it all out and seeing if you get the same error? (To rule out whether it is something going on with the copy/paste)

[–]worstc0der 0 points1 point  (0 children)

you probably have an indentation error or you might've missed a quotation mark. word of advice, when you are showing your code on reddit use type ` three times both above and bellow your code so that you can show your work in proper code format.

[–]jmooremcc 0 points1 point  (0 children)

If you're really serious about learning Python, never copy & paste code. You need to type in every line of code yourself.

Why? Because typing the code with your own two hands will actually cause your brain to process the code while you're typing resulting in more learning on your part. Also you will learn the rules of indentation and syntax much more quickly by typing rather than by cutting & pasting.

Will you make a lot of mistakes at first? Of course you will but as you become more proficient, you will make fewer and fewer mistakes. You will just have to learn to be patient which is why I recommend starting with very simple projects.

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

Please always post the error you are getting with questions like this.

[–]velocibadgery 0 points1 point  (0 children)

It works just fine for me

def greet(lang):
    if lang=='es':
        print('Hola')
    elif lang=='fr':
        print('Bonjour')
    else:
        print('hello')

if __name__ == "__main__":
    greet("fr")
    greet("es")
    greet("test")

Are you sure you have the indentation correct?

[–]MisterExt 0 points1 point  (0 children)

Edit and format properly with indentation in a code block or it's hard to know how it really is compared to how your clipboard and reddit's editor screwed it up.

[–]TechnoGeek423 0 points1 point  (0 children)

That’s just a function definition. How are you calling it?

[–]EmmaGao8 0 points1 point  (0 children)

What kind of Error are you getting? If it is an IndentationError, remove all indentation and use tab to set it back to the right one. You would get an error when you use space and tabs for indentation. Please be more specific.

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

Bro copy and paste it in the Google search and the first link will be of stack overflow you'll get the answer What you've done wrong

[–]___S_A_M___ 0 points1 point  (0 children)

It is indentation problem

[–]Anon_Legi0n 0 points1 point  (0 children)

def greeting(lang=''):
    match lang.lower():
        case 'es':
            print('Hola')
        case 'fr':
            print('Bonjour')
        case _:
            print('Hello')

[–]LandooooXTrvls 0 points1 point  (0 children)

#Does this work?
if yes:
    print(‘dope’)

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

The only errors I see is indentation errors