Lesson 2 · Full-Length Courses
Python Full Tutorial for Beginners
This lesson is a complete walkthrough of core Python: variables, strings, numbers, conditionals, loops, lists, tuples, dictionaries, functions, exception…
- CourseFull-Length Courses
- Lesson2 of 7
- Video1 h 15 min
- FormatJupyter notebook · 52 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbPython Full Tutorial for Beginners#
- This lesson is a complete walkthrough of core Python: variables, strings, numbers, conditionals, loops, lists, tuples, dictionaries, functions, exception handling, classes, and modules.
- Every example runs inside a Jupyter Notebook cell in VS Code, with plenty of hands-on exercises along the way.
- No prior programming experience is required.
Installing Python#
- Go to python.org, open Downloads, and download the latest version of Python 3 for your operating system.
- On Windows, before clicking Install, check the box that says 'Add python.exe to PATH', which lets your terminal and VS Code find Python.
- On macOS, run the installer package and follow the prompts.
Setting Up VS Code and Your First Notebook#
- Install Visual Studio Code from code.visualstudio.com.
- Open the Extensions view and install the Python extension and the Jupyter extension, both published by Microsoft.
- Open the Command Palette with Control plus Shift plus P (Command plus Shift plus P on Mac), type 'Create: New Jupyter Notebook', and press Enter.
- In the top right corner of the notebook, click Select Kernel and choose your installed Python interpreter.
print('Hello there')
print('O----')
print(' | | | |')
print(' ' + '*' * 10)
price = 10
print(price)
price = 20
print(price)
age = 20
rating = 4.9
name = 'Alex'
is_published = True
print(age, rating, name, is_published)
Practice Exercise: Hospital Check-In#
- Imagine a program for a hospital checking in a patient named John Smith, who is 20 years old and is a new patient.
- Define three variables: one for his name, one for his age, and a Boolean for whether he is a new patient.
full_name = 'John Smith'
age = 20
is_new = True
print(full_name, age, is_new)
name = input('What is your name? ')
print('Hi ' + name)
name = input('What is your name? ')
color = input('What is your favorite color? ')
print(name + ' likes ' + color)
birth_year = input('Birth year: ')
age = 2024 - birth_year
birth_year = input('Birth year: ')
age = 2024 - int(birth_year)
print(type(birth_year))
print(type(age))
print(age)
Practice Exercise: Weight Converter#
- Ask the user for their weight in pounds, convert it to kilograms, and print the result.
weight_lbs = input('Weight in lbs: ')
weight_kg = int(weight_lbs) * 0.45
print(weight_kg)
course = "Python's course for beginners"
print(course)
course2 = 'Python for "beginners"'
print(course2)
message = '''
Hi John,
Here is our first email to you.
Thank you,
The Support Team
'''
print(message)
course = 'Python for Beginners'
print(course[0])
print(course[-1])
print(course[-2])
print(course[0:3])
print(course[1:])
print(course[:5])
print(course[:])
first_name = 'John'
last_name = 'Smith'
msg = f'{first_name} [{last_name}] is a coder'
print(msg)
course = 'Python for Beginners'
print(len(course))
print(course.upper())
print(course.lower())
print(course.find('Beginners'))
print(course.replace('Beginners', 'Absolute Beginners'))
print('Python' in course)
print(10 / 3)
print(10 // 3)
print(10 % 3)
print(10 ** 3)
x = 10
x += 3
print(x)
x -= 3
print(x)
x = 10 + 3 * 2
print(x)
x = 10 + 3 ** 2
print(x)
x = (10 + 3) * 2
print(x)
import math
print(round(2.9))
print(abs(-2.9))
print(math.ceil(2.2))
print(math.floor(2.9))
is_hot = True
is_cold = False
if is_hot:
print('It is a hot day')
print('Drink plenty of water')
elif is_cold:
print('It is a cold day')
print('Wear warm clothes')
else:
print('It is a lovely day')
Practice Exercise: Down Payment#
- The price of a house is 1,000,000 dollars.
- If the buyer has good credit, they need to put down 10 percent of the price; otherwise they need to put down 20 percent.
- Write a program that displays the required down payment for a buyer with good credit.
price = 1000000
has_good_credit = True
if has_good_credit:
down_payment = 0.1 * price
else:
down_payment = 0.2 * price
print(f'Down payment: ${down_payment}')
has_high_income = True
has_good_credit = True
if has_high_income and has_good_credit:
print('Eligible for loan')
has_criminal_record = False
if has_good_credit and not has_criminal_record:
print('Eligible for loan')
temperature = 35
if temperature > 30:
print('It is a hot day')
else:
print('It is not a hot day')
Practice Exercise: Name Validation#
- If a name is fewer than 3 characters, print a message that the name must be at least 3 characters.
- If it is more than 50 characters, print a message that it can be a maximum of 50 characters.
- Otherwise, print that the name looks good.
name = 'Jo'
if len(name) < 3:
print('Name must be at least 3 characters')
elif len(name) > 50:
print('Name can be a maximum of 50 characters')
else:
print('Name looks good')
Practice Exercise: Two-Way Weight Converter#
- Ask for a weight and a unit, entering 'l' for pounds or 'k' for kilograms.
- Convert to the other unit and print the result. Make the unit check case-insensitive.
weight = input('Weight: ')
unit = input('(l)bs or (k)g: ')
if unit.upper() == 'L':
converted = int(weight) * 0.45
print(f'You are {converted} kilos')
else:
converted = int(weight) / 0.45
print(f'You are {converted} pounds')
i = 1
while i <= 5:
print(i)
i = i + 1
print('Done')
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input('Guess: '))
guess_count += 1
if guess == secret_number:
print('You won!')
break
else:
print('Sorry, you failed')
Mini Project: Car Simulator#
- Build a simple command loop: 'start' starts the car, 'stop' stops it, 'help' lists commands, and 'quit' exits.
- Bonus: don't let the car start twice in a row, or stop twice in a row.
started = False
while True:
command = input('> ').lower()
if command == 'start':
if started:
print('Car is already started')
else:
started = True
print('Car started, ready to go')
elif command == 'stop':
if not started:
print('Car is already stopped')
else:
started = False
print('Car stopped')
elif command == 'help':
print('start - to start the car\nstop - to stop the car\nquit - to quit')
elif command == 'quit':
break
else:
print("Sorry, I don't understand that")
for item in 'Python':
print(item)
for name in ['Alex', 'John', 'Sarah']:
print(name)
for number in range(5, 10, 2):
print(number)
prices = [10, 20, 30]
total = 0
for price in prices:
total += price
print(f'Total: {total}')
for x in range(4):
for y in range(3):
print(f'({x}, {y})')
Challenge Exercise: Draw a Shape With Nested Loops#
- Given a list like [5, 2, 5, 2, 5], print that many x's on each corresponding line, using a nested loop to build each line's string one character at a time (rather than relying on string multiplication).
numbers = [5, 2, 5, 2, 5]
for x_count in numbers:
output = ''
for count in range(x_count):
output += 'x'
print(output)
names = ['John', 'Bob', 'Alex', 'Sarah', 'Mary']
print(names[0])
print(names[2])
print(names[-1])
print(names[2:])
names[0] = 'Jon'
print(names)
Practice Exercise: Largest Number in a List#
- Given a list of numbers, find and print the largest one, without using the built-in max function.
numbers = [3, 6, 2, 8, 4, 10]
largest = numbers[0]
for number in numbers:
if number > largest:
largest = number
print(largest)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
print(matrix[0][1])
matrix[0][1] = 20
print(matrix[0][1])
for row in matrix:
for item in row:
print(item)
numbers = [5, 2, 1, 7, 4]
numbers.append(20)
print(numbers)
numbers.insert(0, 10)
print(numbers)
numbers.remove(5)
print(numbers)
numbers.pop()
print(numbers)
print(numbers.index(2))
print(50 in numbers)
numbers.append(2)
print(numbers.count(2))
numbers.sort()
print(numbers)
numbers.reverse()
print(numbers)
numbers2 = numbers.copy()
numbers.append(99)
print(numbers2)
Practice Exercise: Remove Duplicates#
- Given a list of numbers with duplicates, build a new list containing each value only once.
numbers = [2, 2, 4, 6, 6, 3, 4, 6, 1]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques)
numbers = (1, 2, 3)
print(numbers[0])
numbers[0] = 10
coordinates = (1, 2, 3)
x, y, z = coordinates
print(x)
print(y)
print(z)
customer = {
'name': 'John Smith',
'age': 30,
'is_verified': True,
}
print(customer['name'])
print(customer.get('birthdate'))
print(customer.get('birthdate', 'Jan 1, 1980'))
customer['name'] = 'Jack Smith'
customer['birthdate'] = 'Jan 1, 1980'
print(customer)
Mini Project: Phone Number Words#
- Ask the user to enter a phone number as digits, then translate each digit to its word using a dictionary.
digits_mapping = {
'1': 'One',
'2': 'Two',
'3': 'Three',
'4': 'Four',
}
phone = input('Phone: ')
output = ''
for ch in phone:
output += digits_mapping.get(ch, '!') + ' '
print(output)
emojis = {
':)': '\U0001F600',
':(': '\U0001F61E',
}
message = input('> ')
words = message.split(' ')
output = ''
for word in words:
output += emojis.get(word, word) + ' '
print(output)
)'}
y
def greet_user():
print('Hi there')
print('Welcome aboard')
print('Start')
greet_user()
print('Finish')
def greet_user(first_name, last_name):
print(f'Hi {first_name} {last_name}')
greet_user('John', 'Smith')
greet_user(last_name='Smith', first_name='John')
def square(number):
return number * number
result = square(3)
print(result)
print(square(5))
def emoji_converter(message):
emojis = {
':)': '\U0001F600',
':(': '\U0001F61E',
}
words = message.split(' ')
output = ''
for word in words:
output += emojis.get(word, word) + ' '
return output
print(emoji_converter(input('> ')))
)'}
y
try:
age = int(input('Age: '))
income = 20000
risk = income / age
print(age)
except ValueError:
print('Invalid value')
except ZeroDivisionError:
print('Age cannot be 0')
Comments#
- A comment starts with a hash sign, #, and is completely ignored when Python runs your code.
- Use comments to explain why you made a decision, or to leave a note for yourself or other developers.
- Avoid comments that just restate the obvious, like explaining that a print statement prints something; these get outdated and add noise as the code changes.
class Point:
def move(self):
print('move')
def draw(self):
print('draw')
point1 = Point()
point1.draw()
point1.x = 10
point1.y = 20
print(point1.x)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self):
print('move')
point1 = Point(10, 20)
print(point1.x)
point1.x = 11
print(point1.x)
class Person:
def __init__(self, name):
self.name = name
def talk(self):
print(f'Hi, I am {self.name}')
john = Person('John Smith')
john.talk()
bob = Person('Bob Smith')
bob.talk()
class Mammal:
def walk(self):
print('walk')
class Dog(Mammal):
def bark(self):
print('bark')
class Cat(Mammal):
def be_annoying(self):
print('annoying')
dog1 = Dog()
dog1.walk()
dog1.bark()
cat1 = Cat()
cat1.walk()
cat1.be_annoying()
Modules and Packages#
- In a regular VS Code project, a module is a separate .py file whose functions and classes you can import into another file, keeping related code organized together, like sections of a supermarket.
- A package is a folder of related modules, containing a special init.py file that tells Python to treat the folder as importable.
- Since this entire lesson lives in one connected notebook, every function and class we define in an earlier cell is already available in later cells, without needing a separate import statement.
def find_max(numbers):
largest = numbers[0]
for number in numbers:
if number > largest:
largest = number
return largest
numbers = [3, 6, 2, 8, 4, 10]
print(find_max(numbers))
The Python Standard Library#
- Python ships with a huge standard library of built-in modules for common tasks: dates and times, sending emails, generating random values, and much more.
- Search 'Python 3 module index' online to browse the full list.
- Nobody memorizes every module; you gradually become familiar with the ones relevant to the applications you build.
import random
print(random.random())
print(random.randint(10, 20))
members = ['John', 'Mary', 'Bob', 'Alex']
print(random.choice(members))
Practice Exercise: Dice Roller#
- Define a Dice class with a roll method that returns a tuple of two random values between 1 and 6.
import random
class Dice:
def roll(self):
first = random.randint(1, 6)
second = random.randint(1, 6)
return first, second
dice = Dice()
print(dice.roll())
Recap#
- We installed Python and set up a Jupyter Notebook in VS Code as our environment for writing and running code.
- We covered variables, strings, formatted strings, numbers, type conversion, if/elif/else, and comparison and logical operators, through many hands-on exercises.
- We covered while loops, for loops, nested loops, lists, two-dimensional lists, tuples, unpacking, and dictionaries.
- We covered functions with positional and keyword arguments, return values, try/except error handling, comments, classes with constructors, and inheritance.
- We covered how modules and packages organize code across files, and used the built-in math and random modules from Python's standard library.
- Practicing each exercise yourself in a Jupyter Notebook in VS Code is the best way to make these concepts stick.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



