Python is a widely used high level general purpose programming language created by Guido van Rossum in 1991.
It is used for web development,software development,data analytics and Artificial Intelligence & Machine Learning.
Why Python
Python is widely preferred due to it's high capabilities below
- It has a simple syntax similar to English language hence simple to use and understand.
- Python runs on intepreter system meaning code can be executed as soon as it's written.You do not need to compile your program before executing it.
- Python supports 3 programming paradigms - its procedural,object-oriented and functional.
- Python has extensive library which includes almost every function imaginable
Python Basics
Variables in Python
A variable is a named location used to store data in memory and can hold different data types ie strings, integers, floats.
Python has no command for declaring a variable but rather created the moment it's assigned a value.
name = 'Maryam'
age = 62
Data Types
Variables can store data of different types, and different types can do different things. In Python, the data type is set when you assign a value to a variable.
Python has the following data types built-in by default:
Type | Example | Description |
---|---|---|
int |
29 |
Whole numbers |
float |
1.25 |
Decimal numbers |
str |
"stylo" |
Text data |
bool |
True , False
|
Boolean values |
list |
[40, 52, 13] |
Ordered, mutable collection |
tuple |
(11, 23, 63) |
Ordered, immutable collection |
set |
{1, 2, 3} |
Unordered, unique values |
dict |
{"a": 1, "b": 2} |
Key-value pairs |
1.Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
a = "Hello"
print(a)
# slicing strings.
name = 'Aubameyang'
print(name[3:7]) # returns characters from position 3 to position 7(not included)
# amey
print(name[:5]) # _returns characters from the start to position 5(not inclusive)_
#Aubam
print(name[2:]) # returns characters from position 2 all the way to the end.
#bameyang
Python has built in methods used to modify strings
a = "Hello, World!"
print(a.upper()) #returns string in upper case
# HELLO, WORLD!
print(a.lower()) # returns the string in lower case
# Concatenating strings
d = "Hello"
b = "World"
c = d + " " + b
print(c) # Hello World
2.Lists
A list is an ordered mutable collection that allows duplicate values.
List items can be of any data type
Lists are created using square brackets
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
# Identifying the data type
fruits = ["apple", "banana", "cherry"]
print(type(mylist)) # <class 'list'>
# Accessing items in lists
mylist = ['apple', 'banana', 'cherry']
print(mylist[1]) # banana
#Changing list items
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist) # ['apple', 'blackcurrant', 'cherry']
#Inserting an item at specified index
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist) # ['apple', 'banana', 'watermelon', 'cherry']
# Adding an item at the end of the list
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist) # ['apple', 'banana', 'cherry', 'orange']
# Removing specified item from the list
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist) # ['apple', 'cherry']
# Removing an item on specified index
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist) # ['apple', 'cherry']
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)
3.Tuples
A tuple is an ordered, immutable collection of items that allows duplicates.
Tuples are created using double brackets ()
# Creating a tuple
my_tuple = (1, 2, 3)
``# Tuple with mixed data types
person = ("Lenny", 25, True)``
# Accessing elements
print(person[0]) # Output: Lenny
# Slicing
print(my_tuple[1:]) # Output: (2, 3)
# Nested tuple
nested = (1, (2, 3), 4)
# Tuple with one item
single = (5,)
4.Dictionary
A dictionary is an unordered, mutable collection of key-value pairs. It uses {}
curly braces.
#Creating a dictionary
person = {
"name": "Warner",
"age": 25,
"is_student": False
}
# Access value
print(person["name"]) # Output: Warner
# Modify value
person["age"] = 25
# Add new key-value pair
person["city"] = "Kisumu"
# Delete a key
del person["is_student"]
# A dictionary of people and their ages
people = {
"Juliette": 28,
"Kenji": 34,
"Warner": 41
}
# Updating a value
people["Warner"] = 42
# Removing a person
people.pop("Juliette")
# Showing all keys and values
print("Keys(people.keys()) # dict_keys(['Kenji', 'Warner', 'Ella'])
print("Values:", people.values()) #dict_values([34, 42, 25])
print("Items:", people.items()) # dict_items([('Kenji', 34), ('Warner', 42), ('Ella', 25)])
Conditional Statements
Conditional statements in Python are used to execute certain blocks of code based on specific conditions. The conditional statement checks to see if a statement is True or False .
- The if statement
This is the simplest form of a conditional statement. It executes a block of code if the given condition is true.
age = 30
if age > 25:
print("You're still a child")
This checks if the age is greater than 25. Since 30 > 25, the condition is True, so the message gets printed.
- If else statement
The if-else statement is used to execute both the true part and the false part of a given condition. If the condition is true, the if block code is executed and if the condition is false, the else block code is executed.
number = 51
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Since 51 is not divisible by two, the else statement is executed.
- Elif statement
elif statement in Python stands for "else if." It allows us to check multiple conditions , providing a way to execute different blocks of code based on which condition is true.
score = 73
if score >= 70:
print("Grade: A")
elif score >= 60:
print("Grade: B")
elif score >= 50:
print("Grade: C")
else:
print("Grade: D")
The statement checks each condition in order, and once it finds a condition that's true—like score >= 70 for a score of 73,it runs that block and skips the rest. Hence the output will be Grade :A
Conclusion
Understanding core concepts like variables, data types, and conditional statements is just the beginning.
Keep learning and experimenting ,Python’s capabilities are vast and the journey has just begun.
Top comments (0)