Python is a powerful, easy-to-learn programming language that has gained popularity due to its simplicity and versatility. This comprehensive guide will walk you through the fundamentals of Python, from installing it to using advanced features like classes, functions, and file handling.
What is Python?
Python is a high-level, general-purpose programming language that emphasizes code readability and simplicity. Created by Guido van Rossum in the late 1980s, Python is widely used for web development, data science, automation, and more. Its syntax is easy to learn, making it a great choice for beginners and professionals alike.
What Can Python Do?
Python can be used for a variety of tasks, such as:
- Web development: Using frameworks like Django or Flask.
- Data analysis and machine learning: Using libraries like pandas and scikit-learn.
- Automation: Writing scripts to automate tasks.
- Game development: Using libraries like Pygame.
- Desktop applications: Building graphical interfaces with libraries like Tkinter.
Why Python?
Python stands out because:
- Easy to read: Python's syntax is straightforward and looks similar to English.
- Versatile: Python can be used across many domains, from web development to machine learning.
- Large community: Python has a huge user base, offering plenty of tutorials, documentation, and libraries.
Python Syntax Compared to Other Programming Languages
Python syntax is simpler and more readable compared to languages like C++ or Java. It uses indentation instead of braces for defining code blocks, making the code clean and easy to follow.
Python Install
To get started with Python, you can download it from the official website python.org. Follow the installation instructions for your operating system (Windows, macOS, or Linux).
Python Version
After installation, you can check the installed Python version by running:
1python --version
The Python Command Line
You can run Python code directly in the command line or shell by typing python in your terminal or command prompt. This will open an interactive session where you can type Python commands and see immediate results.
Python Syntax
Python syntax is designed to be clean and easy to understand. For example, here’s a simple Python code to print "Hello, World!":
1print("Hello, World!")
Python Indentation
Python uses indentation to define blocks of code, rather than curly braces {} like other languages. Indentation must be consistent.
1if 5 > 2:
2 print("Five is greater than two")
Python Comments
You can add comments in Python using the # symbol. Comments are ignored by the interpreter and are used to explain code:
1# This is a comment
2print("Hello, World!") # This will print a message
Python Variables
Variables in Python are used to store data values. You don’t need to declare the type of a variable; it is inferred from the value assigned to it.
Creating Variables
To create a variable, just assign a value to it:
1x = 5
2y = "Hello"
Python Casting
You can explicitly convert (cast) variables from one type to another:
1x = int(5.5) # Casts float to integer
Get the Type
You can check the type of a variable using the type() function:
1x = 5
2print(type(x)) # Output: <class 'int'>
Single or Double Quotes?
Python allows both single (') and double (") quotes to define strings:
1x = 'Hello'
2y = "World"
Case-Sensitive
Python is case-sensitive, which means myVar and myvar are considered different variables.
Variable Names
Variable names must start with a letter or an underscore, and can contain letters, digits, and underscores.
1my_var = 5
Multi-Word Variable Names
Camel Case
Each word after the first starts with a capital letter:
1myVariableName = "Camel Case"
Pascal Case
Each word starts with a capital letter:
1MyVariableName = "Pascal Case"
Snake Case
Words are separated by underscores:
1my_variable_name = "Snake Case"
Python Variables - Assign Multiple Values
You can assign multiple values to multiple variables in one line:
1x, y, z = 1, 2, 3
Print Output Variables
You can print variables by using the print() function:
1x = 5
2print("The value of x is", x)
Global Variables
A global variable is declared outside of any function and can be accessed inside functions as well.
1x = "Global"
2
3def my_function():
4 print(x)
5
6my_function() # Output: Global
Python Data Types
Python has several built-in data types like integers, floats, strings, and more.
Built-in Data Types
Common Python data types include:
- int for integers
- float for floating-point numbers
- str for strings
- list for lists
- dict for dictionaries
Getting the Data Type
Use type() to find the data type of any variable:
1x = 10
2print(type(x)) # Output: <class 'int'>
Setting the Data Type
You can explicitly set data types using casting:
1x = str(10) # Converts integer to string
Python Numbers
Python supports three types of numbers: integers (int), floating-point numbers (float), and complex numbers (complex).
Python Casting
Casting allows you to change the type of a variable:
1x = int("10") # Converts string to integer
Python Strings
Strings in Python are sequences of characters enclosed in single or double quotes:
1x = "Hello"
Python - Slicing Strings
You can slice strings to extract parts of them:
1x = "Hello"
2print(x[1:4]) # Output: ell
Python - Modify Strings
Strings can be modified using various methods:
1x = "hello"
2print(x.upper()) # Output: HELLO
Python - String Concatenation
You can concatenate strings using the + operator:
1x = "Hello"
2y = "World"
3print(x + " " + y) # Output: Hello World
Python - Format Strings
You can format strings using the format() method:
1age = 30
2txt = "I am {} years old"
3print(txt.format(age)) # Output: I am 30 years old
Python - Escape Characters
Escape characters like \n (new line) and \\ (backslash) are used to include special characters in strings:
1txt = "Hello\nWorld"
2print(txt)
Python - String Methods
Python offers various string methods, such as strip(), replace(), and split():
1txt = " Hello "
2print(txt.strip()) # Output: "Hello"
Python Booleans
Booleans represent one of two values: True or False. They are often used in conditional statements.
1x = True
Python Operators
Operators in Python are used to perform operations on variables and values, such as arithmetic (+, -, *, /), comparison (==, >, <), and logical (and, or, not) operators.
Python Lists
Lists are used to store multiple items in a single variable. Lists are ordered, changeable, and allow duplicate values.
1my_list = [1, 2, 3]
Python - Access List Items
You can access list items using their index:
1print(my_list[0]) # Output: 1
Python - Change List Items
Lists are mutable, meaning their items can be changed:
1my_list[1] = 10
Python - Add List Items
You can add items to a list using append() or insert():
1my_list.append(4)
Python - Remove List Items
You can remove items from a list using remove() or pop():
1my_list.remove(10)
Python - Loop Lists
You can loop through a list using a for loop:
1for item in my_list:
2 print(item)
Python - List Comprehension
List comprehension is a concise way to create lists:
1squares = [x**2 for x in range(10)]
Python - Sort Lists
You can sort a list using sort():
1my_list.sort()
Python - Copy Lists
Lists can be copied using the copy() method or slicing:
1new_list = my_list.copy()
Python - Join Lists
You can join lists using the + operator:
1list1 = [1, 2]
2list2 = [3, 4]
3result = list1 + list2
Python - List Methods
Python lists have many built-in methods like append(), extend(), index(), and count().
Python Tuples
Tuples are similar to lists but are immutable (unchangeable). They are defined by placing elements inside parentheses ():
1my_tuple = (1, 2, 3)
Python - Access Tuple Items
You can access tuple items by their index:
1print(my_tuple[0])
Python - Update Tuples
Tuples are immutable, but you can update them by converting them into a list and then back to a tuple.
1my_tuple = list(my_tuple)
2my_tuple[0] = 4
3my_tuple = tuple(my_tuple)
Python - Unpack Tuples
You can unpack a tuple into variables:
1x, y, z = my_tuple
Python - Loop Tuples
You can loop through tuples using a for loop:
1for item in my_tuple:
2 print(item)
Python - Join Tuples
You can concatenate two tuples using the + operator:
1tuple1 = (1, 2)
2tuple2 = (3, 4)
3result = tuple1 + tuple2
Python - Tuple Methods
Tuples only have two built-in methods: count() and index().
Python Sets
Sets are unordered collections of unique elements. They are defined using curly braces {}:
1my_set = {1, 2, 3}
Python - Access Set Items
You cannot access set items by index because sets are unordered. Instead, you can loop through the set:
1for item in my_set:
2 print(item)
Python - Add Set Items
You can add items to a set using add():
1my_set.add(4)
Python - Remove Set Items
Items can be removed using remove() or discard():
1my_set.remove(2)
Python - Loop Sets
You can loop through sets using a for loop:
1for item in my_set:
2 print(item)
Python Dictionaries
Dictionaries store data in key-value pairs and are defined using curly braces {}:
1my_dict = {"name": "John", "age": 30}
Python - Access Dictionary Items
You can access dictionary items by referring to their key:
1print(my_dict["name"])
Python - Change Dictionary Items
Dictionary values can be updated by referencing their key:
1my_dict["age"] = 31
Python - Add Dictionary Items
You can add new key-value pairs to a dictionary:
1my_dict["address"] = "New York"
Python - Remove Dictionary Items
Remove an item from a dictionary using pop() or del:
1my_dict.pop("age")
Python - Loop Dictionaries
You can loop through dictionary keys, values, or both:
1for key, value in my_dict.items():
2 print(key, value)
Python - Copy Dictionaries
Dictionaries can be copied using the copy() method:
1new_dict = my_dict.copy()
Python - Nested Dictionaries
You can nest dictionaries inside dictionaries:
1my_family = {
2 "child1": {"name": "John", "age": 10},
3 "child2": {"name": "Jane", "age": 8}
4}
Python If...Else
Python uses if, elif, and else for conditional statements:
1if x > 10:
2 print("Greater")
3else:
4 print("Smaller")
Python While Loops
while loops execute a block of code as long as a condition is true:
1i = 1
2while i < 5:
3 print(i)
4 i += 1
Python For Loops
for loops iterate over a sequence (like a list or a range):
1for i in range(5):
2 print(i)
Python Functions
Functions are defined using the def keyword:
1def my_function():
2 print("Hello from a function!")
Python Lambda
A lambda function is a small anonymous function:
1x = lambda a: a + 10
2print(x(5))
Python Arrays
Arrays in Python can be created using the array module or with lists for simpler cases:
1import array as arr
2my_array = arr.array('i', [1, 2, 3])
Python Classes/Objects
Classes are used to create objects. A class is like a blueprint for objects:
1class MyClass:
2 def __init__(self, name):
3 self.name = name
Python Inheritance
Inheritance allows one class to inherit methods and properties from another:
1class Parent:
2 def __init__(self, name):
3 self.name = name
4
5class Child(Parent):
6 pass
Python Iterators
An iterator is an object that contains a countable number of values. Use iter() to create an iterator:
1my_iter = iter([1, 2, 3])
2print(next(my_iter))
Python Polymorphism
Polymorphism allows functions to operate on different object types, like classes sharing the same method name:
1class Cat:
2 def speak(self):
3 return "Meow"
4
5class Dog:
6 def speak(self):
7 return "Bark"
Python Scope
Variables have a scope that defines where they can be accessed. Python has local, global, and nonlocal scopes.
Python Modules
Modules allow you to break down large programs into smaller, manageable files. You can import them using import:
1import math
Python Dates
Python's datetime module allows you to work with dates and times:
1import datetime
2print(datetime.datetime.now())
Python Math
The math module offers various mathematical functions:
1import math
2print(math.sqrt(16))
Python JSON
Python provides methods for working with JSON data using the json module:
1import json
2x = json.dumps({"name": "John", "age": 30})
Python RegEx
The re module in Python allows you to work with regular expressions:
1import re
2pattern = r"\bword\b"
3text = "This is a word in a sentence."
4match = re.search(pattern, text)
Python PIP
PIP is a package manager for installing and managing Python libraries. You can install packages using pip install <package-name>.
Python Try...Except
try...except is used for error handling in Python:
1try:
2 x = 1 / 0
3except ZeroDivisionError:
4 print("Cannot divide by zero!")
Python User Input
You can get user input using the input() function:
1name = input("Enter your name: ")
2print("Hello, " + name)
Python String Formatting
Python allows string formatting to include variables in strings:
1name = "John"
2age = 30
3txt = "My name is {} and I am {} years old"
4print(txt.format(name, age))
Python File Handling
Python allows you to work with files. You can open, read, write, and delete files.
Python File Handling
You can open files using the open() function:
1file = open("filename.txt", "r")
Python Read Files
Read files using read() or readline():
1file = open("filename.txt", "r")
2print(file.read())
Python Write/Create Files
Use write() or append() to write to a file:
1file = open("filename.txt", "w")
2file.write("Hello, World!")
Python Delete Files
You can delete a file using the os.remove() method from the os module:
1import os
2os.remove("filename.txt")
Frequently Asked Questions
Related Articles
Sign-in First to Add Comment
Leave a comment 💬
All Comments
No comments yet.