Learn to Code via Tutorials on Repl.it!

← Back to all posts
A simple Python tutorial for |beginners| - ~[Don't look at this if you are NOT a beginner]~
multicoder2021 (3)

A simple Python tutorial for beginners

Hello everyone and this is my first tutorial on repl.it!

[Not my first tutorial ever because I have my own website about HTML!]

Contents:

  • Data types
    • Strings
    • Integers
    • Floats
    • Booleans
  • Variables
  • The print() function
    • Single-line
    • Multi-line
    • The 4 types of inserting variables
      • The format method
      • F-strings
      • ,
      • +
  • Escape characters
    • \n
    • \t
    • \r
    • \\
    • \'
  • Comments
    • Single-line comments
    • Multi-line comments
  • The input() function
  • Break, Continue and Pass
    • Break
    • Continue
    • Pass
  • The if else and elif loop
  • The for loop
  • The while loop
    • 😈😈Infinite loops😈😈
    • 😇😇Finite loops😇😇
  • Python operators
    • 🤔?Bitwise Operators?🤔
    • Augmented Assignments
  • A calculator

Data types

There are 4 MAIN data types:

  • Strings
  • Integers
  • Booleans
  • Floats
    They are mostly different.

Strings

Strings are sentences of text, like 'Hello World' or 'Bye Universe', or words, like 'Hello' and 'Universe'.
They are always inside quotes ['' or ""].
Normally they are referred to as str in code.

Integers

Integers are whole numbers, like '1' or '2' or '312' or '4' or...you get the idea, right?
They are never inside quotes.
They are referred to as int.
But what about decimals?
NO, they are NOT integers.
Well, that brings us to...

Floats

Yes.
Floats are decimals, like '1.1' or '2.2' or '3.141592653589793238462643383279502884197169399371'.
They are never in quotes too.
So, 1 is an integer, and 1.000000000000000000001 is a float.
They aren't referred to normally, but use float when referring to them.

Booleans

Booleans.
What do you think it is?
A fraction?
Nope.
A percentage?
NO, that's mostly a string.
A random string?
Nah, that's a different thing.
I give up.
Well, it's a boolean! A boolean is a boolean! Simple! HAHAHAHA ha ha ha.
....
Ok, lame joke.
Anyway, a boolean is either True or False.
Only two booleans.
Isn't. It. Lonely...and BORING.
Anyway, booleans determine loads of things, so stick around to find out WHAT.

The print() function

Single-line

The print() function is used to output text to the console.
Here is a very simple example:
Input:

print("Hello World!")

Output:
Hello World!
You can see it outputs 'Hello World!'
You can put double quotes [" "] or single quotes [' '].
Either way, they will show the same thing.
Input:
print("Hello World!")
print('Hello World!')
Output:
Hello World!
Hello World!
You can also print Integers, Floats and Booleans, simply excluding quotes:]
[>>> = output]

print(1)
>>> 1
print(1.1)
>>> 1.1
print(False)

Multi-line

You can also print multiple lines.
You use three quotes (''') to start it and three to end it.
See this:

print('''
M
U
L
T
I
''')

And it outputs:

M
U
L
T
I

The 4 types of inserting variables

There are 4 ways of inserting variables in strings.

The format method

In the format method, you use .format().

x = 1
print('X is {}'.format(x))

OR

x = 1
y = 1
z = 1
xyz = 3
yz = 2
xy = 2
xz = 2
print('X is {}, Y is {} and Z is {}. X+Y+Z = {}. Y+Z= {}, X+Y = {},X+Z is {}'.format(x,y,z,xyz,yz,xy,xz))

Any place you need to insert a variable, just type {}, and put the corresponding variable in the .format().
Easy.
You can also do this:

x = 1
y = 2
z = 3
print('One is {one}, Two is {two}, and Z is {three}!'.format(one = x, two = y, three = z))

Again, siMple

F-strings

F-strings are sorta similar.
Here:

var1 = 'var1'
var2 = 'var2'
print(f'{var1} & {var2}')

But what if there are loads of variables, like:

a = 'a'
b = 'b'
c = 'c'
d = 'd'
a2 = 'a'
b2 = 'b'
c2 = 'c'
d2 = 'd'
c3 = 'c'
d3 = 'd'
a4 = 'a'
b4 = 'b'
c4= 'c'
d4 = 'd'
#...

It just has no MEANING! Makes no sense! All jumbled up!
#Escape characters
Escape characters are special characters.

\n

\n makes a new line.
If you want to print multiline output, but without having to format it with the '''''', then use \n.
Like here:
Input:

print('These are both odd:\n1\n3')

Output:

These are both odd:
1
3

\t

\t makes 4 spaces forward.
If you need to format something...

print('''
Name        Age        Favourite Food
''')

...just use \t to make it quicker

print('''
Name\t\tAge\t\tFavourite Food
''')

Both output:

Name        Age        Favourite Food

\r

The \r escape character carriage returns a string.
For example:

print('abc\rdef')

What do you think this does?
Go on GUESS!
I'm going to wait till you do...
C'mon I don't have ALL the time in the world!
Guessed?
Ok.
It prints 'def'.
\r goes to the start of the line and is used for overwriting.

\\

If you want to type '\n' or \t or \r as a string, and not an escape character, then just type '\\n' or '\\t' or '\\r'.
S I M P L E.

\'

If you want to type a ' inside a print like this:

print('Don't type ['] ! Don't do that! I won't do it and maybe another person wasn't doing it! Keep this in mind:' DDDDDOOONNNTTT TYYYPPEE ['] !!'')

It will give an error.
Right?
So, you type \'!

print('Don't type [\'] ! Don\'t do that! I won\'t do it and maybe another person wasn\'t doing it! Keep this in mind:\' DDDDDOOONNNTTT TYYYPPEE [\'] !!\'')

[A way to avoid these \'s is by using single quotes inside DOUBLE quotes

print("Don't type ['] ! Don't do that! I won't do it and maybe another person wasn't doing it! Keep this in mind:' DDDDDOOONNNTTT TYYYPPEE [\] !!\'")

There.]
UNDER🆂TOOD?

Comments

Single-line comments

Single-line comments are represented with a hash symbol #.
Here is an example:

# Here is a comment!

Multi-line comments

Multi-line comments are represented with 3 double or single quotes ''' or """

'''
A MULTILINE COMMENT!
Line 2
Line 3

'''

OR

"""
A MULTILINE COMMENT!
Line 2 
Line 3

"""

They both output the same thing:

A MULTILINE COMMENT!
Line 2
Line 3

The input() function

The input() function takes input from the console and saves it in the browser. You can also 'name' the input, which is actually what you HAVE to do. You can also specify if it is a integer (a number) [int] or string (a letter, word or paragraph) [str].
Here is an example of a variable username, and username being outputted with a string:
Input:

username = input("What is your username?_")
print("Hello" , username , "!")

Output:

What is your username?_multicoder2021
Hello multicoder2021 !

Notice any new stuff in these two lines of code?
Yes! The ','!
The comma basically adds a variable onto the end of the string, but with a space .

Break, Continue and Pass

Break

The break keyword literally BREAKS out of the loop.

x = 1
CODE
...
while x == 1:
> break

This piece of PSEUDOCODE, if you remove the ... and CODE part, will still do absolutely NOTHING at all, because all it does, is break out of an empty loop.
Useful keyword, this is.

Continue

The continue keyword repeats the loop.
Example:

x = 1
while x == 1:
  q = input('Exit loop?')
  if q == 'y':
    break
  else:
   continue

Copy and paste this into your Python editor, its a good example.

Pass

And, this brings us to one of THE utmost important (or not depends how you look at it) keywords.
Pass.

This keyword is used as a placeholder.
I cannot tell you more than that.
Here:

x = 1
while x == 1:
 pass
for i in range(100):
 pass

I assure you, this code works.
If you are typing some code, and you dont know what to type next, but you want to run your code to see the output of your code, just use pass.

...I don't even know who this guy is...

The if , else and elif loop

The if, else and elif loop specifies some conditions, and the code under them will be run if those specific conditions are met.
Here is an example:

x = 1
if x == 1:
> print("Ok")
elif x == 2:
> print("Fine")
else:
> print("Really?!?!")

Output:
Ok
You see, it prints 'ok because we CLEARLY state that x has the exact same value and is equal to 1.
But if we took input, then it would print the other things maybe:...

x = int(input("Enter 1, 2 or anything larger:__"))
#Maximum: Infinite instances
if x == 1:
> print("Ok")
elif x == 2:
> print("Fine")
else:
> print("Really?!?!")

Output[Instance1]:
Enter 1,2 or anything larger:__1
Ok
Output[Instance2]:
Enter 1,2 or anything larger:__2
Fine
Output[Instance3]:
Enter 1,2 or anything larger:__3
Really?!?!
__Output[Instance4(and above)]:

Enter 1,2 or anything larger:__31415926535897932384626433832795028841971693993705028944974```

Really?!?!
Yes, yes there are ∞ [infinite] instances.
If you enter a string, it will give this error:
ValueError: invalid literal for int() with base 10: '[stringname]'

The for loop

The for loop can do something many times, without you having to type so many lines of code.
For example, if you wanted to print all the numbers from 1 to 10, you would have to print("1"), print("2"), print("3") and etc.
The amazing, incredible for loop can shorten these 10 priceless, precious lines, into 3 outSTANDing lines!
Here is how:
Input[10 boring lines]:

print("1")
print("2")
print("3")
print("4")
print("5")
print("6")
print("7")
print("8")
print("9")
print("10")

Input[3 outSTANDing lines]:

for i in range(10):
> i = i + 1
> print(i)

Output[The same for both of them]:
1
2
3
4
5
6
7
8
9
10
See?

Augmented Assignment

This may sound boring.
Basically, if you are using a FoR loop like this:

for i in range(100)
 i = i + 1
 print(i)

Then this specific line:

i = i + 1

can be changed.
You don't have to do that, you can simply do:

i += 1

You can also do:

i -= 1
i *= 1
i %= 1

and much more.

See the 'Operators' part of this tutorial.

The while loop

The while loop is just a simple loop.
Or maybe... you can call it an 😈infinite😈 loop.
So basically, you state a variable and its integer OR string value...
and then you just say while this variable's value is this, you should do this.
So that wasn't really that basic so here's an even more basic EXAMPLE:
Input:

x = 1
while x == 1:
 print("X is 1?")

Output:
X is 1?
X is 1?
X is 1?
X is 1?
X is 1?
X is 1?
X is 1?
Sorry but this is an 😈😈infinite😈😈 loop so it just KEEPS printing it until something else happens.
So I can't show it all.
So that was a extremely easy part to explain.

😇😇Finite Loops😇😇

So, while loops don't HAVE to be infinite.
Actually, they HAVE to be finite, otherwise it is just a WASTE of code.
So, to make it finite, you have to add some bits of code.
Did I say bits? I mean loads!
Here, for example:

y = 0
x = input('Continue? Yes or No? >>>')
if x == 'Yes':
 y = 1
else:
 pass
while y == 1:
 print('Hi!')
 break

So I will explain this, line by line.
Line 1: You define y as 0
Line 2: You ask if the user wants to continue and store that info as 'x'
Line 3: If x is 'Yes'...
Line 4: Then y, which we defined on Line 1, becomes 1.
Line 5: Else...[If x is NOT 'Yes']
Line 6: Pass [Go up to the 'Break, Continue and Pass' section
Line 7: While y is 1...
Line 8: print 'Hi!'
Line 9: Break [Go up to the 'Break, Continue and Pass' section, as always.]

Python operators

Source: https://www.w3schools.com/python/python_operators.asp


The operators COMMON operators are * , - , + , / , //,**
and %.
'+' adds
'-' subtracts
'*' multiplies
'/' divides
'**' exponentiates [multiplies the first number by itself the second number times]
'//' rounds the answer to the nearest whole number if it is a decimal.
'%' divides the first number by the second number and returns the remainder.
Ok, so now those are done, lets move on to these...

🤔?Bitwise Operators?🤔

Source: https://realpython.com/python-bitwise-operators/
I was just searching on Google, when I found out about these.
These are apparently called...well...BITWISE operators.
They are operators which act like LOGIC GATES.

You use them for BINARY calculations.

The & operator checks if both integers are positive, and if they both are, then it returns 1. [AND]

The | operator checks if at least one integer is positive, and if there is one, it returns 1.[OR]

The ^ operator checks if at least one integer is positive, and if there is one, then it returns 1. This may seem the same as '^', but no, there is a catch. If both the integers are positive, it returns 0.[XOR]

The ~ operator is a complex one. I didn't understand it really well.( I worked out all of these out myself ). Basically, it adds 1 and makes it negative if it is positive, and subtracts 1 and makes it positive if it is negative.[NOT]

There are 2 more, >> and << , but I don't know what they do.

A calculator

This part might look hard, but there are actually three EZ ways to do it!
I'll start with the hardest and longest one first:


Way[1]

All of these ways have the SAME output:
In the first way, we use functions!
Input:

def add(x , y):
> sum = x + y
> print(sum)

def subtract(x , y):
> difference = x - y
> print(difference)

def multiply(x , y):
> product = x * y
> print(product)

def divide(x , y)
> quotient = x / y
> print(quotient)

x = int(input("Enter first number"))
y = int(input("Enter second number"))
operator = input("Enter the operator:")
if operator == "*":
> multiply(x , y)

elif operator == "+":
> add(x , y)

elif operator == "/":
> subtract(x , y)

elif operator == "-":
> subtract(x , y)

else:
> print("Invalid input.")

Way[2]:

In this way, we use lambda():
Input:

add = lambda(x + y)
subtract = lambda(x - y)
divide = lambda(x / y)
multiply = lambda(x * y)
x = int(input("Enter first number"))
y = int(input("Enter second number"))
operator = input("Enter the operator:")
if operator == "*":
> multiply(x , y)

elif operator == "+":
> add(x , y)

elif operator == "/":
> subtract(x , y)

elif operator == "-":
> subtract(x , y)

else:
> print("Invalid input.")
Way[3]

In this way, we just print it:
Input:

a = int(input("Enter first number:"))
b = int(input("Enter second number:"))
operator = input("Enter the operator:")
if operator == "*":
> print(x * y)

elif operator == "+":
> print(x + y)

elif operator == "/":
> print(x / y)

elif operator == "-":
> print(x - y)

else:
> print("Invalid input.")
Output[same for all of them]:

Enter first number13
Enter second number13
Enter the operator:*
169
[Put whatever number you want for the first number, the second number and put whatever operator you want!]
So that was the [Unfinished]tutorial!
I hope you liked it!
Please put any suggestions about things that I should include in this please!
Bye!

*Note: I am still editing this, and it is not finished yet, so you can give me any idea you want