Python is an incredibly versatile programming language used for everything from web development and data science to machine learning and automation. Its simple syntax yet extensive capabilities make Python a great choice for beginners looking to get into coding.

In this comprehensive guide, we will walk through 30 practical Python script examples, covering basic concepts like variables and conditionals as well as more advanced features like regular expressions and exception handling. By the end, you‘ll have the fundamental Python building blocks necessary to start writing your own scripts.

1. Hello World

It‘s tradition for your first program in any language to print "Hello World." Here‘s how you do it in Python:

print("Hello World")

This prints the text in quotes to the console when run.

2. Variables

Variables store values so you can reference them later. Here‘s an example:

name = "John"
age = 25 

print(name)
print(age)

This stores the value "John" in a variable called name and the number 25 in a variable called age. We can then print out those variables to display their values.

3. Data Types

Python has several basic data types that each store different types of values:

string = "This is a string"
integer = 25 
float = 25.5
boolean = True # Can also be False

Make sure you store the right data type in your variables.

4. Input from User

You can get input from a user with the input() function:

name = input("Enter your name: ")

This prompts the user to enter their name and stores it in the name variable.

5. Strings

Strings represent text and have lots of useful methods, for example:

string = "hello world"
print(string.upper()) # "HELLO WORLD" 
print(string.count("l")) # 3

upper() makes the string all uppercase letters while count() counts how many times a letter appears.

6. Lists

Lists store ordered sequences of values:

fruits = ["apple", "banana", "cherry"] 

fruits.append("orange") # Add new item 
fruits.remove("banana") # Remove item

You can add and remove items from a list after creating it.

7. Tuples

Tuples are like lists but the values cannot change:

point = (2.5, 6.7)

Trying to reassign a value in a tuple will result in an error.

8. Dictionaries

Dictionaries map keys to values, like a map or hash table:

student = {
  "name": "Mark",
  "grades": [90, 88, 92]  
}

print(student["name"]) # Mark

The key "name" maps to the value "Mark". Dictionaries are useful for storing related data.

9. Conditional Logic (if/else)

You can use if/else statements to conditionally run code:

age = 25
if age >= 18:
  print("You are old enough to vote")
else:
  print("You are too young to vote")

The statements under if run if the condition passes, otherwise the else branch runs.

10 While Loops

While loops repeat code as long as a condition is true:

count = 0
while count < 5:
   print("Count:", count)  
   count = count + 1 

This prints "Count: 0" up to "Count: 4". The loop exits once count reaches 5.

11. For Loops

For loops iterate over iterables like lists and strings:

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

This loops through and prints each fruit from the list.

12. Functions

Functions group code for reuse:

def multiply(x, y):
  return x * y

a = multiply(6, 8) # 48

multiply accepts two arguments and returns their product. Functions are essential for structuring your programs.

13. Classes

Classes define new types with methods (functions) and attributes (data):

class Person:
  def __init__(self, name): 
    self.name = name

  def greet(self):
      print("Hello, my name is", self.name)

person = Person("John")  
person.greet()

Classes allow you to model real-world entities like people.

14. Modules

Modules provide reuseable functionality that can be imported:

import datetime

now = datetime.datetime.now() 
print(now) # 2023-02-05 13:02:29.745297  

This imports Python‘s datetime module to work with dates and times.

15. Reading Files

You can read a file‘s contents with:

file = open("text.txt") 
contents = file.read()
print(contents)
file.close() 

Make sure to close files when finished.

16. Writing Files

Similarly, you can write to files like so:

file = open("created_file.txt", "w") 
file.write("This file was created by a python script!")  
file.close()

The "w" mode argument opens the file for writing rather than reading.

17. Exception Handling

Use try/except blocks to handle errors gracefully:

try:
  num = int(input("Enter a number: "))
except ValueError:
  print("That‘s not a number!") 

This catches invalid numeric input and handles the error.

18. Command Line Arguments

Script command line args come in as a list:

import sys 

print(sys.argv) # [‘script.py‘, ‘arg1‘, ‘arg2‘]

You can process these arguments however you want.

19. Regex

Regular expressions are sequences that match string patterns:

import re

pattern = r"spam"

if re.search(pattern, "I love spam!"):  
  print("Match found!")

Great for parsing and matching text.

20. Random Numbers

Python‘s random module generates psuedo-random numbers:

from random import randint, choice 

roll = randint(1, 6) # Random dice roll  

winner = choice(["Alice", "Bob", "Claire"]) # Random choice 

Useful when you need controlled randomness.

21. Sending Email

Send automated emails with SMTP:

import smtplib 

connection = smtplib.SMTP("smtp.gmail.com", 587)
connection.starttls() 
connection.login("youremail@gmail.com", "password")
connection.sendmail("you@gmail.com", "friend@gmail.com", "Hello")  
connection.quit()

Credentials let your scripts use your email.

22. Web Scraping

Scrape data from websites using BeautifulSoup:

from bs4 import BeautifulSoup
import requests  

page = requests.get("https://dataquestio.github.io/web-scraping-pages/simple.html")  
soup = BeautifulSoup(page.content, ‘html.parser‘)

print(soup.find(id="name").get_text())  
# Displays the text that matches the HTML element with id="name"

Great for gathering data.

23. Working with CSV

Python has builtin CSV functionality:

import csv 

with open("data.csv") as file:
  reader = csv.reader(file)  
  next(reader) # Skip header row  

  for row in reader:
    print(row) 

This reads a CSV file and prints each row. CSVs are common data filetypes.

24. Working with PDF

Python can generate and parse PDF files too.

import PyPDF2

reader = PyPDF2.PdfReader("file.pdf")
writer = PyPDF2.PdfWriter() 

for page in reader.pages:
    writer.addPage(page)

writer.write("new_file.pdf")  

Lots you can do with PDFs.

25. Multithreading

Speed up I/O-bound tasks with threads:

from threading import Thread

def print_nums():
  for num in range(100):
    print(num)

t1 = Thread(target=print_nums)
t2 = Thread(target=print_nums)  

t1.start()  
t2.start() 

Threads allow parallel execution.

Next Steps

And that‘s 30 Python script examples ranging from basic to advanced functionality. With the core concepts and features covered here, you have strong foundations to start writing your own Python scripts for a world of different applications.

Some things you can try your hand at next:

  • Automating tasks on your computer
  • Developing games and visualizations
  • Building machine learning models
  • Creating web applications
  • Anything else you can dream up!

Python‘s versatility, vast ecosystem and supportive community make it a joy to work with. I encourage you to use these examples as inspiration for your own projects. Keep practicing, be curious and have fun with coding!

Similar Posts