Python Basics for Beginners: A Complete Guide (2023)

Python Basics for Beginners: A Complete Guide (1)

Why Python?

Python is a popular programming language that is widely used for a variety of tasks, such as web development, data analysis, machine learning, and more.

The reason for its popularity is its simplicity and ease of use. Python has a simple and easy-to-learn syntax, which makes it an ideal choice for beginners who are just starting to learn programming.

Python is also a high-level language, which means that it abstracts away many of the low-level details of programming, such as memory management and data types.

This makes it much easier for beginners to focus on the logic of their programs without getting bogged down in the details.

A great thing about Python is its vast ecosystem of libraries and frameworks. These libraries and frameworks provide pre-built functionality that you can use in your programs, which makes it much easier to accomplish complex tasks.

For example, the popular web framework Django makes it easy to build web applications in Python, and the NumPy library makes it easy to work with arrays and matrices of data.

Overall, Python is a great choice for beginners because it is simple, easy to learn, and has a vast ecosystem of libraries and frameworks that can help you accomplish complex tasks.

Python Mastery: A Guide to Going from Zero to HeroPython is a versatile, high-level programming language that has become one of the most popular choices for developers…medium.com

Download Python

Before you can start writing Python programs, you need to download and install Python on your computer. You can download the latest version of Python from the official Python website at https://www.python.org/downloads/.

Once you have downloaded the installer, simply run it and follow the prompts to install Python on your computer. Once the installation is complete, you should be able to access the Python interpreter by opening a command prompt or terminal and typing “python” (without the quotes).

Printing In Python

One of the most basic things you can do in Python is print text to the screen. To do this, you use the built-in “print” function. Here’s an example:

print("Hello, World!")

This will print the text “Hello, World!” to the screen. You can also use the print function to print the value of a variable.

name = "John"
print("Hello, " + name)

This will print “Hello, John” to the screen.

Variables

You can use variables to store data. A variable is a named container that holds a value. You can assign a value to a variable using the assignment operator (=). For example:

x = 5
y = 10

In this example, we have created two variables, x and y, and assigned the values 5 and 10 to them, respectively.

You can also use variables to store different types of data, such as strings, lists, and dictionaries.

name = "John"
age = 25
scores = [90, 80, 70]
data = {"name": "John", "age": 25}

In this example, we have created variables to store a string, an integer, a list, and a dictionary.

Getting User Input

Use the built-in “input” function to get input from the user. The input function takes a string as an argument, which is used as a prompt to the user.

name = input("What is your name? ")
print("Hello, " + name)

This will prompt the user with the question “What is your name?”, and store the user’s response in the variable “name”. Then it will print “Hello, “ followed by the user’s name.

It’s important to note that the input function always returns a string, even if the user enters a number. So if you need to use the user’s input as a number, you will need to convert it to the appropriate data type.

age = input("What is your age? ")
age = int(age) # convert the string to an integer
print("You are " + str(age) + " years old.")

In this example, we first use the input function to get the user’s age as a string, then we convert it to an integer using the int() function, and finally we use the str() function to convert it back to a string so that we can print it.

Writing Comments

Use the “#” symbol to write comments in your code. Comments are ignored by the interpreter and are only there to help you and other developers understand what your code is doing. For example:

# This is a comment

x = 5 # This is also a comment
# This is a multi-line comment
# You can use triple quotes for multi-line comments
"""
This is a multi-line comment.
You can write as much as you want in here.
"""

It’s a good practice to add comments to your code to explain what you’re doing and why, especially for more complex or tricky parts of your code.

Operators in Python

You can use various operators to perform operations on variables and values. Here are some of the most common operators:

  • Arithmetic operators: +, -, *, /, % (modulus), // (floor division), ** (exponent)
  • Comparison operators: ==, !=, >, <, >=, <=
  • Logical operators: and, or, not
  • Membership operators: in, not in
  • Identity operators: is, is not
x = 5
y = 10

# Arithmetic operators
print(x + y) # 15
print(x - y) # -5
print(x * y) # 50
print(x / y) # 0.5
print(x % y) # 5
print(x // y) # 0
print(x ** y) # 9765625

# Comparison operators
print(x == y) # False
print(x != y) # True
print(x > y) # False
print(x < y) # True
print(x >= y) # False
print(x <= y) # True

# Logical operators
print(x > 0 and y > 0) # True
print(x > 0 or y > 0) # True
print(not (x > 0)) # False

# Membership operators
numbers = [1, 2, 3, 4, 5]
print(x in numbers) # True
print(y in numbers) # False

# Identity operators
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a is b) # False
print(a is c) # True

Expressions in Python

An expression is a combination of values, variables, and operators that results in a value. Expressions can be used to perform calculations, assign values to variables, or as part of a larger statement.

x = 5
y = 10

# Expression to calculate the sum of x and y
result = x + y
print(result) # 15
# Expression to assign the result of the calculation to a variable
z = x * y
print(z) # 50
# Expression used as part of a larger statement
if x > y:
print("x is greater than y")
else:
print("x is not greater than y")

In the first example, the expression “x + y” calculates the sum of x and y and assigns it to the variable “result”.

In the second example, the expression “x * y” calculates the product of x and y and assigns it to the variable “z”.

In the third example, the expression “x > y” is used as part of a larger conditional statement.

Conditional Statements in Python

You can use conditional statements to control the flow of your program based on certain conditions. The most commonly used conditional statements are “if”, “elif” (else if), and “else”.

x = 5
y = 10

if x > y:
print("x is greater than y")
elif x < y:
print("x is less than y")
else:
print("x is equal to y")

In this example, the program checks if x is greater than y. If it is, the first block of code is executed, printing “x is greater than y”. If it is not, the program then checks if x is less than y. If it is, the second block of code is executed, printing “x is less than y”. If neither of the conditions are true, the else block is executed, printing “x is equal to y”.

You can also use the “and”, “or”, and “not” logical operators to chain multiple conditions together in a single if statement.

age = 18
is_student = True

if age >= 18 and is_student:
print("You are eligible for a student discount.")
else:
print("You are not eligible for a student discount.")

The program checks if the user is 18 or older and is a student. If both conditions are true, the first block of code is executed, printing “You are eligible for a student discount.”.

Loops in Python

You can use loops to repeat a block of code multiple times. The most commonly used loops are “for” loops and “while” loops.

For example, a “for” loop can be used to iterate over a sequence of items, such as a list or a string.

numbers = [1, 2, 3, 4, 5]

for number in numbers:
print(number)

This will print the numbers 1, 2, 3, 4, and 5 to the screen.

A “while” loop can be used to repeat a block of code as long as a certain condition is true.

x = 0

while x < 5:
print(x)
x += 1

This will print the numbers 0, 1, 2, 3, and 4 to the screen. The condition “x < 5” is checked at the start of each iteration, and as long as it is true, the code block inside the while loop will continue to execute.

You can also use the “break” and “continue” statements to control the flow of a loop. The “break” statement will exit the loop completely, while the “continue” statement will skip the current iteration and move on to the next one.

numbers = [1, 2, 3, 4, 5]

for number in numbers:
if number == 3:
break
print(number)

This will print the numbers 1, 2 and stop the loop.

Range

The “range” function in Python is used to generate a sequence of numbers. You can use it in a “for” loop to iterate over a range of numbers.

for i in range(5):
print(i)

This will print the numbers 0, 1, 2, 3, and 4 to the screen.

You can also specify the starting and ending point of the range, as well as the step size.

for i in range(2, 7, 2):
print(i)

This will print the numbers 2, 4, 6.

Functions in Python

You can use functions to group a block of code together and give it a name.

Functions can take input (parameters) and return output (return values). You can use the “def” keyword to define a function.

def add(x, y):
result = x + y
return result

result = add(5, 10)
print(result)

This will define a function called “add” that takes two parameters, x and y, and returns the result of x + y. The function is then called and the result is stored in a variable and printed to the screen.

You can also define a function that does not take any parameters or return any values.

def print_hello():
print("Hello, World!")

print_hello()

This will define a function called “print_hello” that simply prints “Hello, World!” to the screen when called.

Strings in Python

In Python, strings are sequences of characters. You can use single or double quotes to define a string.

name = "John"
message = 'Welcome to Python!'

You can use various string methods and operators to manipulate strings.

name = "John"

# String concatenation
greeting = "Hello, " + name
print(greeting)

# String length
length = len(name)
print(length)

# String indexing
first_letter = name[0]
print(first_letter)

# String slicing
last_letters = name[1:]
print(last_letters)

# String formatting
age = 25
print("My name is {} and I am {} years old.".format(name, age))

Lists in Python

In Python, lists are used to store a collection of items. You can define a list using square brackets [] and separate items with commas.

numbers = [1, 2, 3, 4, 5]
names = ["John", "Mary", "Bob"]

You can also use various list methods and operators to manipulate lists.

numbers = [1, 2, 3, 4, 5]

# List length
length = len(numbers)
print(length)

# List indexing
first_item = numbers[0]
print(first_item)

# List slicing
last_items = numbers[1:]
print(last_items)

# List append
numbers.append(6)
print(numbers)

# List insert
numbers.insert(2, 0)
print(numbers)

# List remove
numbers.remove(3)
print(numbers)

# List pop
last_item = numbers.pop()
print(last_item)
print(numbers)

List functions

Python has several built-in functions that can be used to work with lists, such as:

  • min() and max() to find the minimum and maximum value in a list
  • sum() to calculate the sum of all values in a list
  • sorted() to sort a list
  • len() to find the length of a list
numbers = [4, 2, 8, 1, 5]

# Find the minimum value
minimum = min(numbers)
print(minimum)

# Find the maximum value
maximum = max(numbers)
print(maximum)

# Calculate the sum
total = sum(numbers)
print(total)

# Sort the list
sorted_numbers = sorted(numbers)
print(sorted_numbers)

# Find the length of the list
length = len(numbers)
print(length)

Modules in Python

You can use modules to group related functions and data together. A module is simply a Python file with a .py extension. You can use the “import” statement to import a module and use its functions and data in your code.

import math

x = math.sqrt(16)
print(x)

This will import the math module and use its sqrt function to calculate the square root of 16 and print the result.

You can also use the “from” keyword to import specific functions or data from a module.

from math import sqrt

x = sqrt(16)
print(x)

This will import only the sqrt function from the math module and use it to calculate the square root of 16 and print the result.

Dictionaries in Python

Dictionaries are used to store a collection of key-value pairs. You can define a dictionary using curly braces {} and separate keys and values with colons :

person = {"name": "John", "age": 25}

You can also use various dictionary methods and operators to manipulate dictionaries.

person = {"name": "John", "age": 25}

# Access a value by its key
name = person["name"]
print(name)

#Add a new key-value pair
person["city"] = "New York"
print(person)

#Update a value
person["age"] = 30
print(person)

#Delete a key-value pair
del person["city"]
print(person)

#Check if a key exists in a dictionary
if "city" in person:
print("City is in the dictionary.")
else:
print("City is not in the dictionary.")

Tuples in Python

Tuples are similar to lists, but they are immutable, meaning their values cannot be changed once they are created. You can define a tuple using parentheses () and separate items with commas.

numbers = (1, 2, 3, 4, 5)

You can still use indexing and slicing to access the values of a tuple, but you cannot add, remove, or update values.

Mutable vs Immutable Data Types

There are two types of data types: mutable and immutable. Mutable data types can be modified after they are created, such as lists and dictionaries.

Immutable data types cannot be modified after they are created, such as tuples and strings.

It’s important to keep in mind the difference between mutable and immutable data types when working with them in your code.

For example, if you want to sort a list, you can use the “sort” method and the list will be sorted in place. However, if you want to sort a tuple, you need to create a new tuple with the sorted values.

Sets in Python

Sets are used to store a collection of unique items. You can define a set using curly braces {} and separate items with commas.

numbers = {1, 2, 3, 4, 5}

Sets automatically eliminate any duplicates and only store unique values. You can use various set methods and operators to manipulate sets, such as:

numbers = {1, 2, 3, 4, 5}

# Add an item to a set
numbers.add(6)
print(numbers)

# Remove an item from a set
numbers.remove(5)
print(numbers)

# Check if an item is in a set
if 6 in numbers:
print("6 is in the set.")
else:
print("6 is not in the set.")

String Formatting in Python

Use string formatting to insert values into a string. You can use the “format” method or the “f” string literal to format strings.

name = "John"
age = 25

# Using the format method
greeting = "My name is {} and I am {} years old.".format(name, age)
print(greeting)

# Using the f string literal
greeting = f"My name is {name} and I am {age} years old."
print(greeting)

File Handling in Python

You can use the “open” function to open a file and read or write its contents. You can use the “with” statement to automatically close the file when you’re done.

# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, World!")

# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)

In the first example, the "open" function is used to open the "example.txt" file in "w" (write) mode. The "with" statement is used to automatically close the file when the block of code inside it is finished executing. The "write" method is used to write the string "Hello, World!" to the file.

In the second example, the "open" function is used to open the "example.txt" file in "r" (read) mode. The "with" statement is used to automatically close the file when the block of code inside it is finished executing. The "read" method is used to read the contents of the file and store it in the "content" variable.

Exception Handling in Python

In Python, you can use exception handling to handle errors that may occur in your code. You can use the "try" and "except" keywords to catch and handle specific errors.

x = 5
y = 0

try:
result = x / y
except ZeroDivisionError:
print("Cannot divide by zero.")

In this example, the "try" block contains the code that may cause an error, in this case dividing x by y. The "except" block contains the code that will be executed if the error occurs, in this case the ZeroDivisionError. This will print "Cannot divide by zero." to the screen if y is equal to zero and the code in the try block would cause a ZeroDivisionError.

You can also use the "finally" block to execute code no matter if an error occurred or not.

x = 5
y = 2

try:
result = x / y
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Code finished executing.")

In this example, the "finally" block will always execute and print "Code finished executing." to the screen, whether the code in the try block caused an error or not.

We've covered the basics of Python programming, including how to download and install Python, how to print to the screen, how to use variables, how to get user input, how to write comments, how to use operators and expressions, how to use conditional statements and loops, how to use functions, how to work with strings, lists, modules, dictionaries, tuples, sets, file handling, and exception handling.

With this knowledge, you should be able to start writing your own Python programs and continue learning more advanced concepts.

It’s important to practice and experiment with the concepts you’ve learned in this tutorial by writing your own code and experimenting with different examples. As you continue to practice and learn more about Python, you’ll be able to create more complex and useful programs.

You can also refer to the official Python documentation (https://docs.python.org/) for more information on the different topics covered in this tutorial and for information on additional concepts and features not covered here.

Additionally, there are many resources available online such as tutorials, forums, and online courses that can help you continue learning and improving your Python skills.

I hope this article has been helpful in introducing you to the basics of Python programming. I wish you the best of luck in your journey as a Python programmer!

Happy coding!

Mlearning.ai Submission SuggestionsHow to become a writer on Mlearning.aimedium.com
Top Articles
Latest Posts
Article information

Author: Amb. Frankie Simonis

Last Updated: 03/02/2023

Views: 6702

Rating: 4.6 / 5 (76 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Amb. Frankie Simonis

Birthday: 1998-02-19

Address: 64841 Delmar Isle, North Wiley, OR 74073

Phone: +17844167847676

Job: Forward IT Agent

Hobby: LARPing, Kitesurfing, Sewing, Digital arts, Sand art, Gardening, Dance

Introduction: My name is Amb. Frankie Simonis, I am a hilarious, enchanting, energetic, cooperative, innocent, cute, joyous person who loves writing and wants to share my knowledge and understanding with you.