Python Basics Bootcamp

Python Basics Bootcamp

ยท

10 min read

Hello Techies ๐Ÿ‘‹๐Ÿป

Welcome to our latest blog post where we explore the exciting world of Python programming! In this post, we will dive into the fundamentals of this popular programming language, and provide you with a comprehensive guide to help you get started with Python. Whether you're a beginner or an experienced programmer looking to brush up on your skills, this post has something for everyone. Get ready to learn about variables, data types, loops, functions, and much more! So, sit back, relax, and join us on this journey to discovering the power of Python programming.

Agenda:-

  1. Introduction to programming and Python

  2. Variables and data types in Python

  3. Operators and expressions

  4. Conditional statements (if/else)

  5. Loops (for and while)

  6. Functions

  7. Strings and string methods

  8. Lists and list methods

  9. Dictionaries and dictionary methods

  10. Tuples

  11. Sets

  12. File handling in Python

Introduction to programming and Python

Programming is the process of writing instructions that a computer can understand and execute. The instructions, known as code, are written in a specific programming language, such as Python.

Python was created in the late 1980s by Guido van Rossum, and its name was inspired by Monty Python's Flying Circus, a popular British comedy show. Today, Python is one of the most widely used programming languages in the world, and it's used by companies such as Google, NASA, and Spotify.

Variables and data types in Python

Variables are used to store values in a program. In Python, variables are created by assigning a value to a name, such as:

name = "John Doe"
age = 30

In Python, there are several data types, including:

  • Strings: used to store text, represented by quotes (single or double)

  • Integers: used to store whole numbers, represented without quotes

  • Floats: used to store numbers with decimal points, represented without quotes

  • Booleans: used to store True or False values

name = "John Doe"  # String
age = 30  # Integer
weight = 70.5  # Float
is_student = False  # Boolean

Operators and Expressions

Operators are used to perform operations on values in a program. In Python, there are several types of operators, including:

Arithmetic operators: used to perform arithmetic operations, such as addition (+), subtraction (-), multiplication (*), and division (/)

Comparison operators: used to compare values, such as equal to (==), not equal to (!=), greater than (>), and less than (<)

Logical operators: used to perform logical operations, such as and (and), or (or), and not (not)

Expressions are combinations of values and operators that produce a result. For example, the expression 2 + 2 produces the result 4.

# Arithmetic operators
x = 5
y = 2
print(x + y)  # 7
print(x - y)  # 3
print(x * y)  # 10
print(x / y)  # 2.5

# Comparison operators
a = 5
b = 2
print(a == b)  # False
print(a != b)  # True
print(a > b)  # True
print(a < b)  # False

# Logical operators
c = True
d = False
print(c and d)  # False
print(c or d)  # True
print(not c)  # False

Conditional Statements (if/else)

Conditional statements are used to control the flow of the program based on specific conditions. The most common conditional statement in Python is the if statement, which allows you to execute a block of code if a certain condition is met. You can also use the else statement to execute a different block of code if the condition is not met.

Here's an example of an if statement in Python:

age = 30
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

Loops (for and while)

Loops are used to repeatedly execute a block of code. In Python, there are two types of loops: for loops and while loops.

A for loop is used to iterate over a sequence, such as a list or string. Here's an example of a for loop in Python:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

This code creates a list of fruits and uses a for loop to iterate over the list. The code inside the for loop is executed for each item in the list, and the output is:

apple
banana
cherry

A while loop is used to repeatedly execute a block of code as long as a certain condition is met. Here's an example of a while loop in Python:

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

This code uses a while loop to repeatedly print the value of count as long as it is less than or equal to 5. The output is:

1
2
3
4
5

Functions

Functions are blocks of code that can be executed when called. In Python, you can define a function using the def keyword, followed by the function name and a set of parentheses that may contain parameters.

Here's an example of a function in Python:

def greet(name):
    print("Hello, " + name + "!")

greet("John Doe")

This code defines a function called greet that takes a parameter name and prints a greeting message. When the function is called with greet("John Doe"), the output is Hello, John Doe!.

Strings and String Methods

Strings are sequences of characters in Python, and they can be manipulated using string methods. Some of the most commonly used string methods in Python include:

len(): returns the length of a string

lower(): returns a string in lowercase

upper(): returns a string in uppercase

str.replace(old, new): replaces all occurrences of old with new in a string

Here's an example of using string methods in Python:

name = "John Doe"
print(len(name))  # 7
print(name.lower()) # john doe
print(name.upper()) # "JOHN DOE"
print(name.replace("John", "Jane")) # "Jane Doe"

In this example, the first line creates a string name with the value "John Doe".

The len() function returns the length of the string, which is 7.

The lower() and upper() methods return the string in lowercase and uppercase, respectively.

The replace() method replaces all occurrences of "John" with "Jane".

Lists and List Methods

Lists are ordered collections of items in Python. You can create a list by enclosing a comma-separated sequence of items in square brackets []. Lists can contain items of different data types, including other lists.

Some of the most commonly used list methods in Python include:

  • len(): returns the number of items in a list

  • sort(): sorts a list in ascending order

  • reverse(): reverses the order of items in a list

  • append(): adds an item to the end of a list

  • insert(index, item): inserts an item at a specified index in a list

  • remove(item): removes an item from a list

Here's an example of using list methods in Python:

fruits = ["apple", "banana", "cherry"]
print(len(fruits))  # 3
fruits.sort()
print(fruits)  # ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)  # ['cherry', 'banana', 'apple']
fruits.append("orange")
print(fruits)  # ['cherry', 'banana', 'apple', 'orange']
fruits.insert(1, "kiwi")
print(fruits)  # ['cherry', 'kiwi', 'banana', 'apple', 'orange']
fruits.remove("banana")
print(fruits)  # ['cherry', 'kiwi', 'apple', 'orange']

In this example, the first line creates a list fruits with the values "apple", "banana", and "cherry". The len() function returns the number of items in the list, which is 3. The sort() method sorts the list in ascending order, the reverse() method reverses the order of items in the list, and the append() and insert() methods add items to the list. The remove() method removes the item "banana" from the list.

Dictionaries and Dictionary Methods

Dictionaries are unordered collections of key-value pairs in Python. You can create a dictionary by enclosing a comma-separated sequence of key-value pairs in curly braces {}.

Some of the most commonly used dictionary methods in Python include:

  • len(): returns the number of key-value pairs in a dictionary

  • keys(): returns a list of all keys in a dictionary

  • values(): returns a list of all values in a dictionary

  • get(key): returns the value of a specified key in a dictionary

  • pop(key): removes a key-value pair from a dictionary and returns the value

Here's an example of using dictionaries in Python:

person = {"name": "John Doe", "age": 30, "gender": "male"}
print(len(person))  # 3
print(person.keys())  # ['name', 'age', 'gender']
print(person.values())  # ['John Doe', 30, 'male']
print(person.get("age"))  # 30
person.pop("age")
print(person)  # {'name': 'John Doe', 'gender': 'male'}

In this example, the first line creates a dictionary person with the key-value pairs "name":"John Doe", "age":30, and "gender":"male". The len() function returns the number of key-value pairs in the dictionary, which is 3. The keys() and values() methods return lists of all the keys and values in the dictionary, respectively. The get() method returns the value of the key "age", which is 30. The pop() method removes the key-value pair "age":30 from the dictionary.

Tuples

Tuples are ordered collections of items in Python that cannot be modified once they are created. You can create a tuple by enclosing a comma-separated sequence of items in parentheses ().

Tuples are often used in situations where you want to store a fixed number of items and ensure that they cannot be changed. For example, you could use a tuple to represent a date: (day, month, year).

Here's an example of using tuples in Python:

date = (7, 2, 2023)
print(date)  # (7, 2, 2023)

In this example, the first line creates a tuple date with the values 7, 2, and 2023. The print() function displays the tuple as (7, 2, 2023).

Sets

Sets are unordered collections of unique items in Python. You can create a set by enclosing a comma-separated sequence of items in curly braces {}.

Sets are often used in situations where you want to store a collection of items and ensure that there are no duplicates. For example, you could use a set to represent a collection of unique numbers: {1, 2, 3}.

Here's an example of using sets in Python:

numbers = {1, 2, 3, 3, 2, 1}
print(numbers)  # {1, 2, 3}
numbers.add(4)
print(numbers)  # {1, 2, 3, 4}

In this example, the first line creates a set numbers with the values 1, 2, 3, 3, 2, and 1. The print() function displays the set as {1, 2, 3}, as sets only store unique items and duplicate items are removed. The add() method adds the item 4 to the set.

File Handling in Python

File handling in Python allows you to read from and write to files on your computer. You can use the open() function to open a file and the write() method to write to a file. When you are finished working with a file, you should close it using the close() method.

Here's an example of writing to a file in Python:

file = open("example.txt", "w")
file.write("Hello, World!")
file.close()

In this example, the first line opens a file named "example.txt" in write mode ("w"). The write() method writes the string "Hello, World!" to the file. The close() method closes the file.

To read from a file in Python, you can use the read() method.

Here's an example of reading from a file in Python:

file = open("example.txt", "r")
content = file.read()
print(content) # Hello, World!
file.close()

In this example, the first line opens the file "example.txt" in read mode ("r"). The read() method reads the entire contents of the file and stores it in the content variable. The print() function displays the contents of the file, which is "Hello, World!". The close() method closes the file.

File handling in Python is a powerful tool for reading and writing data to and from files, and is an essential part of many real-world applications.

In conclusion, the topics covered in this workshop are the basics of Python programming, and include variables and data types, operators and expressions, conditional statements, loops, functions, strings, lists, dictionaries, tuples, sets, and file handling. These concepts are the foundation of all Python programming and are essential for anyone who wants to unleash their coding potential with Python.

So, to recap, the basics of Python programming are:

  1. Introduction to programming and Python

  2. Variables and data types in Python

  3. Operators and expressions

  4. Conditional statements (if/else)

  5. Loops (for and while)

  6. Functions

  7. Strings and string methods

  8. Lists and list methods

  9. Dictionaries and dictionary methods

  10. Tuples

  11. Sets

  12. File handling in Python

By mastering these concepts, you will be well on your way to becoming a proficient Python programmer.

In this workshop, you learned how to use Python to perform basic programming tasks, such as declaring variables, using conditional statements, and working with lists, dictionaries, tuples, and sets. You also learned how to use functions to create reusable blocks of code, and how to work with strings and file handling in Python.

With these new skills and knowledge, you should be able to tackle your own programming projects with confidence, and build amazing things with Python.

So, get started and put your newfound Python skills to the test! Happy coding!

ย