Learn Python for Beginners – Part 1: Variables, Strings, Lists, Dictionaries, and Sets
In this tutorial you’ll learn basics of the Python programming language. The first part covers variables, strings, lists, dictionaries, and sets.
The tutorial uses Jupyter Notebook as the Python development environment. If you have not installed Jupyter Notebook yet take a look at Getting Started With Jupyter Notebook For Python.
Let’s start with a first statement printing out the text Hello World:
print('Hello World')
As a result you’ll get the text Hello World printed out:
>> Hello World
Comments
If you’d like to include comments in your Python code you can use the #-sign. You can choose to add the the #-sign at the beginning of the line or to include the comment at the end of the line:
# One line comment starts with hash
print('Hello World') # comment at the end of the line
Variables
var1 = 2
print(var1)
>> 2
var2 = 3
var3 = var1 + var2
print('The sum of var1 and var2 is {}'.format(var3))
>> The sum of var1 and var2 is 5
Strings
# Single Quote String
'This is a string'
# Double Quote String
"This is a string"
string1 = 'This is a string'
print(string1)
>> This is a string
string1[1]
>> 'h'
string1[1:]
>> 'his is a string'
string1[5:7]
>> 'is'
Lists
list1 = [1,2,3]
print(list1)
>> [1, 2, 3]
list2 = ['a', 'b', 'c']
print(list2)
>> ['a', 'b', 'c']
list2.append('d')
print(list2)
>> ['a', 'b', 'c', 'd']
list2[0]
>> 'a'
list2[0] = 'abc'
print(list2)
>> ['abc', 'b', 'c', 'd']
# Nested Lists
list2[0] = ['a', 'b', 'c']
print(list2)
>> [['a', 'b', 'c'], 'b', 'c', 'd']
Dictionaries
d1 = {'key1': 'value1', 'key2': 'value2'}
>> {'key1': 'value1', 'key2': 'value2'}
d1['key2']
>> 'value2'
# Lists in Dictionaries
d2 = {'list1':[1,2,3]}
>> {'list1': [1, 2, 3]}
d2['list1']
>> [1, 2, 3]
list1 = d2['list1']
list1[2]
>> 3
d2['list1'][2]
# Nesting Dictionaries
d3 = {'key1': {'key2': 'value2'}}
d3['key1']
>> {'key2': 'value2'}
d3['key1']['key2']
>> 'value2'
Sets
Last but not least, let’s take a look at sets, another data structure which is part of Python. Sets are defined by using curly braces:
{1,2,3}
Sets can only contain distinct values. If you try to define a set which includes duplicates, like the following set:
{1,2,2,3,3,3}
{1, 2, 3}
Off course, sets can be stored in variables:
s1 = {1,2}
s1.add(3)
>> {1, 2, 3}
COURSE: Complete Python Masterclass
Check out the great Complete Python Masterclass Online Course by Tim Buchalka and Jean-Paul Roberts with thousands of students already enrolled:
- You’re taught step by step how to program in Python
- Understand data structures and how to access the web with Python
- The skills to get a job with Python under your belt as taught by the best
- With each step, the why you’re doing it is explained
Top 3 Python Online Courses
Getting Started With CSS Grid
Using and writing about best practices and latest technologies in web design & development is my passion.