A quick introduction to Python

Hello!

Have you noticed that most tutorials online take you from a complete beginner to actually writing some code? That’s great! It introduces new people to programming.

And that’s exactly the problem for people coming from different languages, who already have a programming background. Now, you could just watch the whole twelve-hour tutorial and learn the language like that, but it would most likely just be a recap of stuff you know, in a different language. That’s why I hardly ever learn new languages because I want to quickly consume the language’s features without listening to a fifteen-minute talk about what each feature does.

So, I am making this guide as a way for programmers that already know other languages, to quickly get a rundown of Python’s features so they can get to writing more advanced code faster.

Because of the sheer amount of instruction on this topic, it will likely contain many errors. Feel free to contribute and add any information I missed or correct some redundancy.

Let’s begin!


Python is an object-oriented language, and it does not require semicolons, it does not use static types and is more geared toward beginner programmers and data science. It can be used for back-end, front-end, and even game development to some extent.

I am not going to go over installing Python, but if you want to learn on your local machine instead of Replit, you can download it from python.org.


Printing to the console is very simple compared to languages like C++, and can be done like so:

print("Hello, world!")

Escape sequences like \n and \t can be used within strings, and strings can be shown in multiple ways. If your coming from a language like Java, the char type no longer exists, and Python allows you to use either " " or ' ' when creating strings. Multiline screens can be created like so, and are pretty useful in certain scenarios.

print("""I
am
multiline!
""")

Multiline screens can also be created using single quotes.


Commenting is much easier in Python compared to other languages IMO.

# Single Line Comment

"""
Multi-
Line
Comment
"""

Now it's time to get into some more important stuff. Variables are easily declared, and as I said, types are not declared in Python.
my_str = "Hello, world!"
my_int = 1
my_float = 3.14
my_bool = True
my_list = [1, 2, 3] # We'll talk more about these later
my_tuple = (1,) # Same thing here
my_dict = {"Hello!":"Hi!"} # And here

And you use them exactly how you would expect:

print(my_str) # Outputs "Hello, World!"

Almost forgot to mention, variables in Python that use multiple words should be separated with underscores, and not camelCase. Though, this is completely up to you, try to stay consistent about whatever style you’re doing. Same thing applies for almost all topics discussed today.


Concatenation is very simple too, and there are three ways you can do it:

print("How are you today " + my_str + "?") # Addition/Plus
print(How are you today", my_str, "?") # Commas, we'll talk more about why this works the way it does later
print(f"How are you today {my_str}?") # F-String; See below

F-Strings are similar to JavaScripts: console.log(`Hello, ${world}!`) You should immediately start using those, they are the most readable and probably the easiest to set up anyway.

There are some limitations, however. Different types cannot be used in the same string when concatenating unless you’re using F-Strings. You will need to convert types, doing something like so:

my_int = str(my_int)
print("Score: " + my_int)
# or just
print("Score: " + str(my_int))

You can also do the reverse with integers if you need to by using int().


Getting a users input is super simple as well, just assign the value of input() to a variable, which also somewhat acts as a print statement within itself:

name = input("What is your name?\n>> ")
print(f"Hello, {name}!")

Input always returns a string, even if the user were to enter some number.

There is a flaw with input, as doing something like CTRL+C while waiting for input just throws an error, which can be fixed in a topic I’ll explain later.


Python has some different arithmetic operators. You can find the whole list here, but I’ll quickly go over some of them.

my_int = 2 + 3
my_int = my_int + 2
# or even better:
my_int += 2

# Subtraction, multiplication, and division follow the same principles as addition, and are identical to most other languages

remainder = 9 % 2
exponent = 9**2

And as shown above, += and other assignment operations do exist in Python, and there are a lot of different kinds. You can find them here.


if statements are another pretty straightforward thing in Python. They do not require some like if ("a" === "a") {}, and their syntax is pretty different.

Python uses colons and indents, so curly braces aren’t a thing anymore.

Here’s an example of an if-statement in action:

password  = "password123"
password2 = "admin" 
user_input = input("Password: ")

if   password  == user_input:
    print("Correct password!")
elif password2 == user_input
else:
    print("Incorrect password!")

elif’s are just if-statements that only activate no other statements above it have already, and they have the same syntax as normal if statements. elif some_condition:.

If you’re kinda confused about how these work, an if statement only runs if a statement is True. So for example, if you had some boolean that was True, you could do something like this:

if my_bool:
    # Do something
else:
    # Do something else

That’s why the operations work the way they do, password == user_input simply returns True or False, and you could do this if you wanted: print(password == user_input.

There are also some logical operators, which are and, or, and not. You use them how you would expect:

if 1 + 1 == 2 and 3 + 4 == 7:
    # do something
if 1 + 1 == 2 or 1 + 1 == 3:
    # do something
if not my_bool:
    # do something

For a full list of comparison operators and whatnot, they are usually pretty similar to JavaScript with a few exceptions. Find them here.


The while loop is pretty simple, but to be honest, the for loop is a bit weird.

A while loop runs while a condition is True. (This is a funky example, but it works)

password = "password123"
user_input = ""

while password != user_input:
    user_input = input("Password: ") # Asks for input until the user gets the password

print("Access Granted!")

Most languages are the same deal, but if the condition is updated while the loop is running to be False, it will only stop running once the code within the loop has ended.


for loops are very unique compared to other languages.

Here’s one in action:

for x in range(100): # x starts at zero, and you may not even want to use x in some scenarios
    print(x) # Increases x per iteration

If you just need the loop to run a certain amount of times, but you don’t need x, just replace it with _. Also, if you try to replace x with a counter variable that already exists, it will not work as expected.

Loops have two keywords associated with them, break, and continue. Lets say in your for loop, you didn’t want 0 to be printed, then do something like this:

for x in range(100):
    if x == 0:
         continue
    print(x)

This immediately skips to the next iteration of the loop. break allows you to skip out of a loop immediately. The code with the while loop above could be refactored like so:

password = "password123"

while True:
    user_input = input("Password: ")
    if password == user_input:
        break
    print("Incorrect password!")
print("Access Granted!")

With these skills, I would practice and make some sort of project, such as a calculator. These are absolutely fundamental to know, and you would be able to understand some Python code in the real world with these skills.


Next, my favorite feature of Python… lists!

Python lists are a very used feature of Python and are usually called arrays in other languages. You can append to a list, delete a value or index from a list, and some other features I’ll mention later.

list_of_cars = ["Honda", "Toyota", "Volkswagen", "Tesla"]
# Indexes of lists go 0, 1, 2, 3, and so on

list_of_cars.append(input("Enter a Car: ")))
list_of_cars.remove("Volkswagen") # This removes the first occurrence of "Volkswagen" from the list
list_of_cars.pop(0) # Remove the first index of the list

Accessing a value from a list is pretty easy too:

print(list_of_cars[0]) # Prints the first value of the list
print(list_of_cars[-1]) # This prints the last value from the list like you're going reverse
print(list_of_cars[-2]) # Prints the second to last value, you get the point

Now, let’s compare lists to strings. I’ll be explaining some nice features of string manipulation later, but for now, remember that when calling a method on a list, you don’t have to reassign it to the list, but you do for strings, because lists are mutable and strings are not. More on the side effects of that later.

Tuples are basically immutable lists. After assigning them, none of their contents can be changed, they can only be accessed as shown for lists. They are pretty scenario-based, and you see them less often than lists.

Here’s an example of a tuple:

my_tuple = (255,255,255) # Some RGB value we will want to use for later
change_color(my_tuple) # This function does not exist but is good for this example

In my example of the variable types, I showed a tuple like so: my_tuple = (0,). Wouldn’t that result in a syntax error or such? Well, if we were to assign a variable like this:

my_tuple = (0)
print(my_tuple)
# Outputs "0"

That’s not what we want! This isn’t a tuple, and I can prove it by telling you about the type() function. It takes a variable and outputs its type. <class 'int'>. This function can be used to check types and such, but let’s not get too off-topic. So, if you want to declare a tuple with just a single value:

my_tuple = (0,)
print(type(my_tuple))
# Outputs "<class 'tuple'>"

Dictionaries: a very important Python feature, and you probably already have some ideas including their use. Here’s a simple dictionary:

my_dict = {"Player1":1, "Player2":3, "Player3":9}

print(f"Player 1 Score: {my_dict['Player1']}") # F-Strings are pretty funky when doing stuff like this, if you run into any errors you should google them

A dictionary is a key-value pair. Doing something like the above, storing a player and their score.

Adding a pair to a dictionary is pretty simple, simply name the key and assign it a value like so:

my_dict["Player4"] = 18

And if you want to change the value of a key that exists, just do the same thing as above.

Here’s another example:

print(my_dict.keys()) # Prints all of the dictionaries keys in a list
print(my_dict.values()) # Prints all of the dictionaries values in a list

On the topic of for loops again, 90% of the time, you will want to iterate through the contents of a list or dictionary. This is a lot easier compared to JavaScript’s built-in forEach() method.

for value in my_list:
    print(value) # Prints every value within the list on separate lines

If you need to get both the index and value in a list, use the enumerate() function.

for i, v in enumerate(my_list):
    print(f"Index {i} of my_list = {v}")

Loop through a dictionary’s keys or values:

for key in my_dict.keys():
    print(key)

for value in my_dict.values():
    print(value)

# Or even better, combine the two!
for k, v in my_dict.items():
    print(f"{k} = {v}")

Sorry this isn’t complete yet, I’m editing it in segments, and hope to finish it soon.

I hope this gives programmers a good rundown of some of the basic features of the language.

4 Likes

You should probably include one of these resources I made for a python library. This can help other users to take a deeper dive into the module and learn something. Instead of just

import time
time.sleep(5)

when you can do so much more

from time import sleep
from time import time
time = time()
sleep(5)

Here is my tutorial 4 this:

1 Like

I’m not going to get into specific modules, this is supposed to be a quick rundown of the language. But I’ll link some of your topics in case others want to learn more.

2 Likes

bravo! This would be very useful to the broad group of people who want to learn python.

1 Like

@QwertyQwerty88, could you please make this a wiki? I would love for people to contribute, possibly adding important features I missed, editing my grammar and examples (which are currently very lazy and bad), or removing redundant ones.

2 Likes

Tries to edit
There are edit conflicts, unable to save your changes

I know some cool tricks :slight_smile:

1 Like