DEV Community

Cover image for Introduction to Python
Kelvin
Kelvin

Posted on • Edited on

Introduction to Python

Python is a powerful and flexible programming language created by Guido van Rossum and first released in 1991.Over the years, Python has become one of the most loved and used languages in the world.

Python installation.

python installation from the web.
python.

checking the version of python installed in your pc

Open your command line and type python --version

This confirms the version of python installed in your computer.

example of a python code.

What Can You Use Python For

  • Web Development, and software development.
  • Data analysis, machine learning, data engineering, AI, and math.
  • System scripting.

Why Use Python?

  • Platform-independent - Python works everywhere: Windows, Mac, Linux, Raspberry Pi, or any other platform.
  • Simple & Readable Syntax - python is simple to read and understand.
  • Fewer Lines of Code - Python lets you do more with less typing.
  • Fast Prototyping - Python runs your code line by line, immediately showing results or errors.
  • Multiple Programming Styles - Python lets you write code in different ways i.e. procedural, object oriented and functional (using functions like math operations)

Python Syntax.

Python has rules about how code should be written so it can be understood and executed properly. It relies on indentation and clean line-by-line execution and throws errors if the rules are not followed. Python emphasizes readability and simplicity, making it easier for beginners to learn and professionals to maintain.

Key Syntax Rules in Python.

Python uses indentation to define blocks of code.
Indentation means adding spaces at the beginning of a line to show that this line belongs to a group or block of code.
You can technically use any number of spaces - at least one. But the convention is to use four spaces for each indentation level.

if 5 > 2: 
    print("Five is greater than two!") 
Enter fullscreen mode Exit fullscreen mode

Mixing indentation levels is not allowed Python needs consistency. Once you choose a number of spaces, stick with it throughout the block.

Python Variables.

A variable is a named memory location.

name = "lee"
    print("name")
Enter fullscreen mode Exit fullscreen mode

here name is a variable for storing the string "lee"

In Python, you don’t have to declare the data type of a variable like you do in many other languages. Python understands it based on the value you assign.

Rules of naming variables.

  • A variable name must start with a letter (a–z, A–Z) or an underscore _.
  • It can only contain alphanumeric characters and underscores (A–Z, a–z, 0–9, and _)
  • Variable names are case-sensitive.
  • It cannot start with a number.
  • You cannot use reserved words i.e. (int, True ETC)

Best Practices.

  • Use descriptive names
  • Use snake_case for variables
  • Avoid short, vague names like x, y, unless in quick examples or math

Assigning Multiple Variables

Python lets you assign values to multiple variables at once: a, b, c = 1, 2, 3
All at once! Or assign the same value to multiple variables: x = y = z = "Python"

Checking the Type of a Variable - You can use the type() function to find out what kind of value a variable holds.

name = "Alice" 
print(type(name)) 
Enter fullscreen mode Exit fullscreen mode

the output will be str (string)

Python Constants.

  • Values that don’t change during normal program execution
  • In real life, think of your birthdate. You store it once and it never changes - that's a constant.
  • In Python, we use uppercase letters to indicate that a variable is meant to be a constant e.g.
PI = 3.14159
Enter fullscreen mode Exit fullscreen mode
  • Python does not have built-in constants, but we use uppercase variable names to show they are constants.

Python Data Types.

A data type is the classification of data that tells the computer what kind of data you are working with and what operations can be performed on it.

Python’s Built-in Data Types.

1. Numeric Types

  • int – Integer (whole numbers)
age = 25
Enter fullscreen mode Exit fullscreen mode
  • float – Floating point (decimal numbers)
height = 5.9
Enter fullscreen mode Exit fullscreen mode
  • complex – Complex numbers (used in scientific computing)
complex_num = 3 + 2j 
Enter fullscreen mode Exit fullscreen mode

2. Text Type

  • str – String (a sequence of characters)
"Python is amazing!"
Enter fullscreen mode Exit fullscreen mode

3. Boolean Type

  • bool - Can only be True or False.
is_logged_in = True
Enter fullscreen mode Exit fullscreen mode

Arithmetic Operators in Python

  • Addition (+) -- Adds two numbers
  • Subtraction (-) -- Subtract right from left
  • Multiplication (*) -- Multiply numbers
  • Division (/) -- Divide and get float
  • Modulus (%) -- Get the remainder

comparison operators

Greater than (>)
Less than (<)
Equal to (==) note that (=) is an assignment operator
Not equal to (=!)
Greater than or equal to (>=)
Less than or equal to (>=)

Logical operators (and,or,not)

AND - Returns true only if both conditions are true
OR - Returns true if at least one condition is true
NOT - Reverses the value (true becomes false, false becomes true)

Data types and data structures

Datatypes
A datatype define the type of a value a variable can store

  1. Boolean - returns true or false when a certain condition is met.

  2. String - Sequence of characters or text enclosed in quotation marks.
    on command line python dir(str)

f-string - An f-string (formatted string literal) is a way to insert variables or expressions directly inside a string.
user = 'admin'
password = 12345
database = 'postgres'

database_url = f"PostgreSQL:// {user:}{password:}@localhost:5432{testdb}"

  1. Int - whole numbers without decimals

  2. floats - represents decimals

Data structures.

Is a way of organizing and storing data so that it can be modified and accessed efficiently.

on command line python dir(list)

list [] - is a collection of items in a specified order
students =["Sam", "Gloria", "Stacy", "Kevin", "Ornella"]

characteristics

(i) They are ordered
(ii) They are mutable - can be changed
(iii) Indexed
(iv) Allows duplicates

common list methods

.append() - students.append("kevin") - adds an item at the end of a list
.remove() - students.remove("kevin") - removes a specific item
.pop() - students.pop(1) - removes an item based on index and last one if no index is provided.
.sort() - students.sort() - sorts items in the list based on a particular order
.reverse() - students.reverse() - reverses the order of items in a list.

Tuple () - is a collection of items that is ordered but cannot be changed.

characteristics

(i) They are immutable - cannot be changed.

common tuple methods

.count() - my_tuple.count(35)
.index() - my_tuple.index(35)

Dictionary {}- it is a collection of key value pairs >> each key maps to a value

characteristics

(i)Key value pairs
(ii)They are mutable
(iii)The keys must be unique

common Dictionary methods

.items() - student.items() Returns key-value pairs
.keys() - student.keys() Returns all keys
.values() - student.values() Returns all values
.get() - student.get()Safely gets a value
.update() - student.update() Updates/adds items

Sets {}- is a collection of Unique items stored in an unordered structure.

Characteristics
(i) They are unordered - no indexing
(ii) No duplicates
(iii) They are mutable - can add or remove elements

common set methods

.add() fruits.add("mango") - adds mango to the set.
.pop() fruits.pop() removes items
.union() print(fruits.union(veggies)) - joins fruits and veggies
Control Flow, Loops and Functions.

Control Flow
-if else and elif

Operators and Expressions
Arithmetic operators (+,-,*,/,^,%)
comparison operators (<,>,=,=!...)
Logical operators (and,or,not)

Conditional statements.

score = int(input("enter score"))

if score < 0 or score > 100:
    print("Invalid score")
elif score >= 80:
    print("A")
elif score >= 70:
    print("B")
elif score >= 50:
    print("C")
elif score >= 35:
    print("D")
elif score >= 15:
    print("E")
else:
    print("Repeat")
Enter fullscreen mode Exit fullscreen mode

loops
for loop -- used to iterate over a sequence (list, tuple or a string)

while loop -- iterates a block of code until a certain condition is met.

Break and continue

break stops/ends the loop immediately
continue - skips the current iteration -- continue skips to next.

Functions
A function is a block of named reusable block of code that perform a specific task when called.

List comprehension
list comprehension provides a concise and efficient way to create a new list by applying an expression to each item in an existing iterable, optionally filtering the items

Object Oriented Programming (OOP)
is a way of programming that organizes code into classes and objects instead of just functions.

classes - blueprint of an object
object - instance of a class

It provides a clear structure to write programs

  1. It allows you to build reusable applications with less code
  2. Dry principle - Do Not Repeat Yourself - it keeps your code dry

CORE CONCEPTS:
1 class
2 Objects

pillars of oop

Inheritance -- this allows you to reuse code from another class

  1. Encapsulation-- this means bundling data and methods together inside a class and controlling access to them

  2. polymorphism - this means the same method name behaves differently

  3. Abstraction -- means hiding unnecessary implementation details and showing only the essential features of an object.

Top comments (0)