Python Tutorial - Learn Python Basics

Learn Python basics with this comprehensive tutorial. Covers data types, keywords, operators, data structures (lists, tuples, sets, dictionaries), conditional branching, loops, and function definitions.

Python Tutorial

Introduction to Python

  • Python is an interpreted, high-level, general-purpose, dynamically typed programming language.

  • It is also object-oriented, modular, and a scripting language.

  • In Python, everything is considered an object.

  • A Python file has an extension of .py.

  • Python uses indentation to separate code blocks instead of curly brackets {}.

  • We can run a Python file using the following command in cmd (Windows) or shell (macOS/Linux):

    $ python <filename.py> or $ python3 <filename.py>

Python does not require any imports to run a basic Python file.

Creating and Executing a Python Program

  1. Open a terminal/cmd.
  2. Create the program: nano > nameProgram.py or cat > nameProgram.py
  3. Write the program and save it.
  4. Run the program: python nameProgram.py


Basic Data Types

Data Type Description
int Integer values [0, 1, -2, 3]
float Floating-point values [0.1, 4.532, -5.092]
str Strings ["abc", "AbC", "A@B", "sd!", "`asa"]
bool Boolean values [True, False]
complex Complex numbers [2+3j, 4-1j]


Python Keywords


  • As of Python 3.11, there are 36 keywords.
Keyword Description Category
True Boolean value for true (or 1) Value Keyword
False Boolean value for false (or 0) Value Keyword
None Represents the absence of a value Value Keyword
and Logical AND (returns true if both operands are true) Logical Operator
or Logical OR (returns true if at least one operand is true) Logical Operator
in Membership operator (checks if a value is present in a sequence) Membership Operator
is Identity operator (checks if two variables refer to the same object) Identity Operator
not Logical NOT (inverts a boolean value) Logical Operator
if Starts a conditional statement Conditional
elif Used for additional conditions in an if statement Conditional
else Used in conditional statements for the default case Conditional
for Starts a for loop Iteration
while Starts a while loop Iteration
break Exits a loop prematurely Iteration Control
continue Skips the current iteration of a loop Iteration Control
def Defines a function Structure
class Defines a class Structure
lambda Creates an anonymous function Structure
with Used with context managers Structure
as Creates an alias Structure
pass A null operation (does nothing) Structure
return Returns a value from a function Return
yield Used in generator functions Return
import Imports modules Import
from Imports specific names from a module Import
try Starts a try...except block Exception Handling
except Handles exceptions Exception Handling
finally Code that always executes in a try...except block Exception Handling
raise Raises an exception Exception Handling
assert Used for debugging (raises an AssertionError if a condition is false) Debugging
async Used for asynchronous functions Asynchronous Programming
await Used within asynchronous functions Asynchronous Programming
del Deletes a variable Variable Handling
global Declares a global variable Variable Handling
nonlocal Declares a variable in an enclosing scope Variable Handling

Python Operators


Operator Description
( ) Parentheses (grouping, function calls, tuple creation)
[ ] Brackets (list indexing, list slicing, list creation)
! Logical NOT (inverts a boolean value)
~ Bitwise NOT (ones' complement)
- Unary minus
+ Unary plus
* Multiplication
/ Division
% Modulo (remainder)
+ Addition
- Subtraction
<< Left bit shift
>> Right bit shift
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
and Logical AND
or Logical OR
= Assignment
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulo and assign
<<= Left bit shift and assign
>>= Right bit shift and assign
&= Bitwise AND and assign
^= Bitwise XOR and assign
|= Bitwise OR and assign
, Separator

Basic Data Structures

Lists

  • A list is an ordered, mutable (changeable) collection that allows duplicate elements.

  • Lists are created using square brackets:

thislist = ["apple", "banana", "cherry"]
  • List items are ordered, mutable, and allow duplicate values.
  • List items are indexed, starting from 0.
  • The len() function returns the number of items in a list.
  • Lists can contain different data types.
list1 = ["abc", 34, True, 40, "male"]
  • The list() constructor can also be used to create a list.
thislist = list(("apple", "banana", "cherry"))
  • The pop() method removes and returns the last item by default, or the item at a specified index.
thislist = ["apple", "banana", "cherry"]
print(thislist.pop())  # Output: cherry
print(thislist.pop(0)) # Output: apple

Tuples

  • A tuple is an ordered, immutable (unchangeable) collection that allows duplicate elements.
  • Tuples are created using parentheses.
thistuple = ("apple", "banana", "cherry")
  • Tuple items are ordered, immutable, and allow duplicate values.
  • Tuple items are indexed, starting from 0.
  • The len() function returns the number of items in a tuple.
  • To create a tuple with one item, add a comma after the item.
thistuple = ("apple",)
print(type(thistuple)) # Output: <class 'tuple'>

thistuple = ("apple")
print(type(thistuple)) # Output: <class 'str'>
  • The tuple() constructor can also be used to create a tuple.
thistuple = tuple(("apple", "banana", "cherry"))

Sets

  • A set is an unordered, mutable collection that does not allow duplicate elements.
  • Sets are created using curly braces.
thisset = {"apple", "banana", "cherry"}
  • Set items are unordered, unchangeable (but the set itself is mutable), and do not allow duplicate values.
  • The len() method returns the number of items in a set.
  • Sets can contain different data types.
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
set4 = {"abc", 34, True, 40, "male"}
  • The set() constructor can also be used to create a set.
thisset = set(("apple", "banana", "cherry"))
  • A frozenset() is an immutable version of a set.
set1 = {"apple", "banana", "cherry"}
frzset = frozenset(set1)
print(frzset)

Dictionaries

  • A dictionary is an unordered, mutable collection of key-value pairs.
  • Dictionaries are created using curly braces.
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
  • Dictionary items are accessed by key name.
print(thisdict["brand"]) # Output: Ford
  • Dictionaries are mutable.
  • Dictionaries cannot have two items with the same key.
  • The len() function returns the number of items in a dictionary.
  • Dictionary values can be of any data type.
thisdict = {
  "brand": "Ford",
  "electric": False,
  "year": 1964,
  "colors": ["red", "white", "blue"]
}
  • The pop() method removes and returns the item with the specified key.
car = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
  }
x = car.pop("model")
print(x) # Output: Mustang
print(car) # Output: {'brand': 'Ford', 'year': 1964}

Conditional Branching

if condition:
    pass
elif condition2:
    pass
else:
    pass

Loops

Python has two main loop types: while loops and for loops.

While Loops

  • A while loop executes a block of code as long as a condition is true.
i = 1
while i < 6:
  print(i)
  i += 1
  • break exits the loop.
  • continue skips the current iteration.
  • else executes if the loop completes normally (without break).

For Loops

  • A for loop iterates over a sequence (list, tuple, string, etc.).
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  • range() generates a sequence of numbers.
  • Nested loops are loops within loops.
  • else executes after the loop completes normally.
  • A for loop cannot be empty, use pass if needed.
for x in [0, 1, 2]:
  pass

Function Definition

def function_name():
    return

Function Call

function_name()
  • Return types are not explicitly specified.
  • Functions return None by default.
  • Any data type can be returned.