Skip to content
← Back to Community
Learn To Code In Python
Profile icon
PYer

Teaches you how to code in python. By PYer
This tutorial excpects some basic knowledge of coding in another language.

This file cannot be displayed: https://storage.googleapis.com/replit/images/1539906614890_d3ab3e7d0acf7cc1d56b6c218bd6d344.pn
This file cannot be displayed: https://storage.googleapis.com/replit/images/1539906646554_941ec29791cd36653b2612f8368ab99e.pn

What is python?

Python is a very popular coding language. Little people use it for serious projects, but it is still useful to learn. It was created in 1991 by Guido van Rossum.
Look at a few uses of python:

  • Desktop Applications
  • Web Applications
  • Complex Scientific Equations

Let's look at a few reasons why it is useful:

  • Readable/Understandable Code
  • Compatible with other systems/platforms
  • Millions of useful modules

These are just a few, you can find a bunch more by researching it.

Know This Before We Start

What we will be teaching you is specifically python 3. This is the most updated version, but the version 2 is still widely used.
Here we will be using replit, but there are multiple text editors you can find.

Python Syntax

Python syntax was made for readability, and easy editing. For example, the python language uses a : and indented code, while javascript and others generally use {} and indented code.

First Program

Lets create a python 3 repl, and call it Hello World. Now you have a blank file called main.py. Now let us write our first line of code:

helloworld.py

print('Hello world!')

Brian Kernighan actually wrote the first "Hello, World!" program as part of the documentation for the BCPL programming language developed by Martin Richards.

Now, press the run button, which obviously runs the code. If you are not using replit, this will not work. You should research how to run a file with your text editor.

Command Line

If you look to your left at the console where hello world was just printed, you can see a >, >>>, or $ depending on what you are using. After the prompt, try typing a line of code.

Python 3.6.1 (default, Jun 21 2017, 18:48:35) [GCC 4.9.2] on linux Type "help", "copyright", "credits" or "license" for more information. > print('Testing command line') Testing command line > print('Are you sure this works?') Are you sure this works? >

The command line allows you to execute single lines of code at a time. It is often used when trying out a new function or method in the language.

New: Comments!

Another cool thing that you can generally do with all languages, are comments. In python, a comment starts with a #. The computer ignores all text starting after the #.

shortcom.py

# Write some comments!

If you have a huge comment, do not comment all the 350 lines, just put ''' before it, and ''' at the end. Technically, this is not a comment but a string, but the computer still ignores it, so we will use it.

longcom.py

''' Dear PYer, I am confused about how you said you could use triple quotes to make SUPER LONG COMMENTS ! I am wondering if this is true, and if so, I am wondering if this is correct. Could you help me with this? Thanks, Random guy who used your tutorial. ''' print('Testing')

New: Variables!

Unlike many other languages, there is no var, let, or const to declare a variable in python. You simply go name = 'value'.

vars1.py

x = 5 y = 7 z = x*y # 35 print(z) # => 35

Remember, there is a difference between integers and strings. Remember: String = "". To convert between these two, you can put an int in a str() function, and a string in a int() function. There is also a less used one, called a float. Mainly, these are integers with decimals. Change them using the float() command.

vars2.py

x = 5 x = str(x) b = '5' b = int(b) print('x = ', x, '; b = ', str(b), ';') # => x = 5; b = 5;

Instead of using the , in the print function, you can put a + to combine the variables and string.

Operators

There are many operators in python:

  • +
  • -
  • /
  • *
    These operators are the same in most languages, and allow for addition, subtraction, division, and multiplicaiton.
    Now, we can look at a few more complicated ones:
  • %
  • //
  • **
  • +=
  • -=
  • /=
  • *=
    Research these if you want to find out more...

simpleops.py

x = 4 a = x + 1 a = x - 1 a = x * 2 a = x / 2

You should already know everything shown above, as it is similar to other languages. If you continue down, you will see more complicated ones.

complexop.py

a += 1 a -= 1 a *= 2 a /= 2

The ones above are to edit the current value of the variable.
Sorry to JS users, as there is no i++; or anything.

Fun Fact:
The python language was named after Monty Python.

If you really want to know about the others, view Py Operators

More Things With Strings

Like the title?
Anyways, a ' and a " both indicate a string, but do not combine them!

quotes.py

x = 'hello' # Good x = "hello" # Good x = "hello' # ERRORRR!!!

slicing.py

String Slicing

You can look at only certain parts of the string by slicing it, using [num:num].
The first number stands for how far in you go from the front, and the second stands for how far in you go from the back.

x = 'Hello everybody!' x[1] # 'e' x[-1] # '!' x[5] # ' ' x[1:] # 'ello everybody!' x[:-1] # 'Hello everybod' x[2:-3] # 'llo everyb'

Methods and Functions

Here is a list of functions/methods we will go over:

  • .strip()
  • len()
  • .lower()
  • .upper()
  • .replace()
  • .split()

I will make you try these out yourself. See if you can figure out how they work.

strings.py

x = " Testing, testing, testing, testing " print(x.strip()) print(len(x)) print(x.lower()) print(x.upper()) print(x.replace('test', 'runn')) print(x.split(','))

Good luck, see you when you come back!

New: Input()

Input is a function that gathers input entered from the user in the command line. It takes one optional parameter, which is the users prompt.

inp.py

print('Type something: ') x = input() print('Here is what you said: ', x)

If you wanted to make it smaller, and look neater to the user, you could do...

inp2.py

print('Here is what you said: ', input('Type something: '))

Running:
inp.py

Type something: Hello World Here is what you said: Hello World

inp2.py

Type something: Hello World Here is what you said: Hello World

New: Importing Modules

Python has created a lot of functions that are located in other .py files. You need to import these modules to gain access to the,, You may wonder why python did this. The purpose of separate modules is to make python faster. Instead of storing millions and millions of functions, , it only needs a few basic ones. To import a module, you must write input <modulename>. Do not add the .py extension to the file name. In this example , we will be using a python created module named random.

module.py

import random

Now, I have access to all functions in the random.py file. To access a specific function in the module, you would do <module>.<function>. For example:

module2.py

import random print(random.randint(3,5)) # Prints a random number between 3 and 5

Pro Tip:
Do from random import randint to not have to do random.randint(), just randint()
To import all functions from a module, you could do from random import *

New: Loops!

Loops allow you to repeat code over and over again. This is useful if you want to print Hi with a delay of one second 100 times.

for Loop

The for loop goes through a list of variables, making a seperate variable equal one of the list every time.
Let's say we wanted to create the example above.

loop.py

from time import sleep for i in range(100): print('Hello') sleep(.3)

This will print Hello with a .3 second delay 100 times. This is just one way to use it, but it is usually used like this:

loop2.py

import time for number in range(100): print(number) time.sleep(.1)

This file cannot be displayed: https://storage.googleapis.com/replit/images/1539649280875_37d22e6d49e8e8fbc453631def345387.pn

while Loop

The while loop runs the code while something stays true. You would put while <expression>. Every time the loop runs, it evaluates if the expression is True. It it is, it runs the code, if not it continues outside of the loop. For example:

while.py

while True: # Runs forever print('Hello World!')

Or you could do:

while2.py

import random position = '<placeholder>' while position != 1: # will run at least once position = random.randint(1, 10) print(position)

New: if Statement

The if statement allows you to check if something is True. If so, it runs the code, if not, it continues on. It is kind of like a while loop, but it executes only once. An if statement is written:

if.py

import random num = random.randint(1, 10) if num == 3: print('num is 3. Hooray!!!') if num > 5: print('Num is greater than 5') if num == 12: print('Num is 12, which means that there is a problem with the python language, see if you can figure it out. Extra credit if you can figure it out!')

Now, you may think that it would be better if you could make it print only one message. Not as many that are True. You can do that with an elif statement:

elif.py

import random num = random.randint(1, 10) if num == 3: print('Num is three, this is the only msg you will see.') elif num > 2: print('Num is not three, but is greater than 1')

Now, you may wonder how to run code if none work. Well, there is a simple statement called else:

else.py

import random num = random.randint(1, 10) if num == 3: print('Num is three, this is the only msg you will see.') elif num > 2: print('Num is not three, but is greater than 1') else: print('No category')

New: Functions (def)

So far, you have only seen how to use functions other people have made. Let use the example that you want to print the a random number between 1 and 9, and print different text every time.
It is quite tiring to type:

Characters: 389

nofunc.py

import random print(random.randint(1, 9)) print('Wow that was interesting.') print(random.randint(1, 9)) print('Look at the number above ^') print(random.randint(1, 9)) print('All of these have been interesting numbers.') print(random.randint(1, 9)) print("these random.randint's are getting annoying to type") print(random.randint(1, 9)) print('Hi') print(random.randint(1, 9)) print('j')

Now with functions, you can seriously lower the amount of characters:

Characters: 254

functions.py

import random def r(t): print(random.randint(1, 9)) print(t) r('Wow that was interesting.') r('Look at the number above ^') r('All of these have been interesting numbers.') r("these random.randint's are getting annoying to type") r('Hi') r('j')

This file cannot be displayed: https://storage.googleapis.com/replit/images/1539906570970_88961cdd6d7c76c15c92cd79307dbb06.pn

There you go! Try making your own functions!

The End

Now you know all of the basics of python. Congratulations!


Updated: Thanks for all the feedback and comments guys! This is the post I'm proudest of!!!! So amazed to hear that some schools have been using this to guide students, glad I'm making a difference!

Voters
Profile icon
MishMotifs
Profile icon
iamcoding123
Profile icon
ChemaLeyva
Profile icon
18rosegeo
Profile icon
TimothyBecker1
Profile icon
DanieNell
Profile icon
AhmedMagdy2
Profile icon
johnnweke1
Profile icon
Angel_DanielDan
Profile icon
SofiaMiranda2
Comments
hotnewtop
Profile icon
PYer

Now it teaches you all of the basics of python. If anybody wants me to add more, comment below please. Thank you!

Profile icon
Vagasvic

@PYer hi this is really a helpful post, especially for new comers like me :D .. Two things I didn't get yet is about: try and exception. I'll be glad if you add something about those things hehe

Profile icon
PYer

@Vagasvic I am kind of busy right now. I may in the future. In the meantime, you can read this article https://realpython.com/python-exceptions/#the-try-and-except-block-handling-exceptions that I used when learning about them.

Profile icon
Vagasvic

@PYer thank you, what a great source to learn :) I had read or watched some litle things about try and exception, I was just giving you a suggestion to improve this post

Profile icon
PYer

@Vagasvic thanks

Profile icon
jwangtcsyl

@PYer Thanks, it is helpful to me( ^ ^ )

Profile icon
PYer

@jwangtcsyl you're welcome!

Profile icon
jwangtcsyl

@PYer ( ^ ^ )

Profile icon
DerrickLukimin

@PYer like create some advanced ones like Flask

Profile icon
AarishKodnaney

@PYer can you do one on object oriented python?

Profile icon
multicoder2021

@PYer
Yes, please make a tutorial on Python Audio, or include in another one.

Profile icon
PYer

Interesting idea. Working on another project right now though. I'm sure there are some already? I'll tell you if I make one, thanks for the suggestion! @multicoder2021

Profile icon
joejox

my school is using you just so you know (thats how good this is)

Profile icon
PYer

Cool! Thanks! @joejox

Profile icon
PYer

Hello @joejox! I was thinking about your comment, and just had a few questions I wanted to ask you! Don't feel obligated to answer them, I'm just curious.

  • Where is your school located? (Just a general area, such as the US or UK)
  • What type of school is it? Public or private?
  • Exactly what class is using it? (A computer science elective, a STEM class, etc)
  • What grade level? This is just to understand what age audience it works for.
  • What is the coding experience most of the students have? (None, minimal, proficient, etc). Do they already know a little python, or any other languages?
  • Do you feel like it was successful? Did it actually help? And if you answer this one, please be honest (I won't be offended :) )

Thanks! And like I said, don't feel obligated to answer any or all of these questions. This will just help me research and plan ways to write tutorials aimed for certain people.
Thanks again, and thanks for telling me!

Profile icon
python88

@PYer it's really helpful!

Profile icon
PYer

Glad to hear it! @python88

Profile icon
SovereignKoi

Wow. This is an insanely helpful guide. Thanks for taking the time to make this!

Profile icon
PYer

Thanks! I'm glad to hear you learned from it! @SovereignKoi

Profile icon
betman123

a iot of thanks!!good service!! i love it!

Profile icon
PYer

thank you! @betman123

Profile icon
Golub132

Thanks!That was usefull!

Profile icon
PYer

Thank you! Any specific parts, or any suggestions? @Golub132

Profile icon
Golub132

@PYer i do not understand def quite properly

Profile icon
PYer

all right, I'll add some more information later. @Golub132

Profile icon
Golub132

Ok,thanks a [email protected]

Profile icon
khalilsajjad786

You have written a nice and thoughtful article.
please check my article:https://www.plusfeeds.com/best-ide-for-python/

Profile icon
PYer
Profile icon
jonnnn

very helpfull

Profile icon
PYer

Glad you liked it! @jonnnn

Profile icon
LexiEmir

I read your article in Turkey and liked it to be explanatory, thank you <3
(I'm not sure if I wrote correctly lol)

Profile icon
PYer

You're good! Glad to hear you like it! And the english is good. some incorrect usage, but I got exactly what you meant! Thanks! @LexiEmir

Profile icon
Greenero1

Not sure will be going any were with this, as have memory problems, but thank you all the same.

Profile icon
PYer

Oooh. No problem. What languages do you prefer? @Greenero1

Profile icon
TPACK

Thank you for an aspiring coder. This was nice!

Profile icon
firedragondnd

@PYer why do you have to always make the most helpful tutorials 😝😁

Profile icon
PYer

I guess I'm just amazing like that. Lol, the tutorial was made in about 1 hour. You can see my time started running out at the end lollllllll And thanks! @firedragondnd

Profile icon
NZHacker808

@studentAlfredAl @PYer Thankyou,that was helpful :D

Profile icon
NZHacker808

What do I need to add in if I want the world viewers to type in an answer into my repl? @PYer

Profile icon
PYer

I'm sorry, but I don't understand your questionn. @Miner36number2

Profile icon
studentAlfredAl

I think he means the user input @PYer

Profile icon
PYer

oh sure. @studentAlfredAl
@Miner36number2
Use the input function and store it in a variable. For example:

text = input("Type something here") print(text)
Profile icon
studentAlfredAl
Profile icon
rodrick123

Students often face academic writing problems in College. So, Assignment Desk is here to provide you Best Essay Writing Service UK . As, Writing an project is a tough task. Students search to complete their academic projects before the deadline. Writing an essay takes a lot of research work plus time.  Students have dreams to get high grades in academic projects. Getting help from expert writer is a right way of completing essay projects before the deadline.
Visit our website for more information-
https://www.assignmentdesk.co.uk/essay-writing-service

Profile icon
Cheshta11

print("Sum of 2 and 3 is",2+3)

Profile icon
Chillicoder

Thank you so much! This is very useful!

Profile icon
PYer

Thanks, glad to hear it! @Chillicoder

Profile icon
BhaskarRana

This is really helpful, especially for beginners. If you are looking for some more beginners level artices do checkout Python tutorials for beginners.

Profile icon
pygrammer123

make a youtube channel !!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Profile icon
PYer

I've thought about it, but I post a tutorial only once in a while. I just don't have the motivation/time to upload regularly. @pygrammer123

Profile icon
Chewyblockguy

cool! I might use this. I mostly do css and html.

Profile icon
PYer

Cool! CSS and HTML are styling and markup languages respectivly. Using a programming language is a different experience and has many different capabilities. I definitely recommend it! @Chewyblockguy

Profile icon
[deleted]

This file cannot be displayed:

Profile icon
DJhyperdust

thank you

Profile icon
ArwenPotter

🎖️🎖️🎖️👍🏻👍🏻👍🏻So helpful! Thanks a lot!😁😁😁🏆🏆🏆

Profile icon
PYer

Glad to hear it! @ArwenPotter

Profile icon
hablahblahha

love it

Profile icon
PYer
Profile icon
ZiadAlbitar

Hello, I am curious to why you could get 12 with the "num = random.randint(1, 10)" command

Profile icon
PYer

You can't it was just an example of something that isn't true. Sorry if that caused confusion. @ZiadAlbitar

Profile icon
pyashika

THANK U
I WAS LEARNING IN MY SCHOOL SO THIS WAS VERY HELPFUL
@PYer
FIGHTING!!!!!!!!!!!!

Profile icon
PYer

Thank you! @pyashika

Profile icon
BluntMachete

Great article! Can we work on a project together? If so, please email me at [email protected]! Thanks a lot! I have medium experience with python and have a big project in mind!

Profile icon
IgorKusov

Good tutorial!
You have a typo in slicing.py
x[1] # is not 'H' but 'e'

Profile icon
PYer

Thanks! Can't believe nobody's caught that before. I wonder how many new coders I've already confused. @IgorKusov

Profile icon
MrCryptomicNeo

this really helped
(:=

Profile icon
PYer

Glad to hear it! @MrCryptomicNeo

Profile icon
hollimu

Can anyone suggest the best way to start learning to code, total begineer.

Profile icon
PYer

It depends, are you looking for resources for a specific language? @hollimu

Profile icon
NicholasWhite6

@PYer hello im trying to create a game through python how do i change color of text on the console

Profile icon
PYer

Try ASCII color codes. That's a pretty common way. You could also try some modules. @NicholasWhite6

Profile icon
PotatooooooMan

@PYer I don't understand the if statement, I want to check if someone wrote something, but I don't understand how, nothing I try works.

Profile icon
Alice688

@PotatooooooMan An if statement basically means, if this is true then do this, else do that. You also can write it with an input function. Here, copy this and paste it on your repl:

answer = input("Flower or not flower:") if answer == 'flower': print("Yay") else: print("Aw")

Got it?

Profile icon
PYer

thanks for responding to that question. great, simple explanation. @Alice688 I've been busy, I must have missed the comment.

Profile icon
Alice688

@PYer np :)