Code Snippets Category Page - PythonForBeginners.com https://www.pythonforbeginners.com Learn By Example Thu, 15 Jun 2023 14:24:20 +0000 en-US hourly 1 https://wordpress.org/?v=5.8.13 https://www.pythonforbeginners.com/wp-content/uploads/2020/05/cropped-pfb_icon-32x32.png Code Snippets Category Page - PythonForBeginners.com https://www.pythonforbeginners.com 32 32 201782279 Python Code Examples https://www.pythonforbeginners.com/code-snippets-source-code/python-code-examples https://www.pythonforbeginners.com/code-snippets-source-code/python-code-examples#comments Sat, 06 Jun 2020 13:40:00 +0000 https://www.pythonforbeginners.com/?p=5785 This page contains all Python scripts that we have posted our site so far. Examples Using pywhois pywhois is a Python module for retrieving WHOIS information of domains. pywhois works with Python 2.4+ and no external dependencies [Source] Magic 8-ball In this script I’m using 8 possible answers, but please feel free to add more […]

The post Python Code Examples appeared first on PythonForBeginners.com.

]]>
This page contains all Python scripts that we have posted our site so far.

Examples

Using pywhois

pywhois is a Python module for retrieving WHOIS information of domains. pywhois works with Python 2.4+ and no external dependencies [Source]

Magic 8-ball

In this script I’m using 8 possible answers, but please feel free to add more as you wish. There are 20 answers inside the Magic 8 Ball, and you can find them all here.

CommandLineFu with Python

A common first step when you want to use a Web-based services is to see if they have an API. Luckily for me, Commandlinefu.com provides one and can be found here

Find all mp3 files with os.walk and fnmatch

In an earlier post “OS.walk in Python“, I described how to use os.walk and showed some examples on how to use it in scripts. In this article, I will show how to use the os.walk() module function to walk a directory tree, and the fnmatch module for matching file names.

Port scanner in Python

This post will show how you can make a small and easy-to-use port scanner program written in Python.

Backup all MySQL databases, with timestamp.

Backup all MySQL databases, one in each file with a timestamp on the end using ConfigParser.

Google Command Line Script

To make a request to the Web search API, we have to import the modules that we
need.

SSH Connection with Python

Pxssh is based on pexpect. It’s class extends pexpect.spawn to specialize setting up SSH connections.

Date and Time Script

This script can be used to parse date and time.

Bitly Shortener with Python

Bitly allows users to shorten, share, and track links (URLs). It’s a way to save, share and discover links on the web.

Sending Mails using Gmail

The smtplib module defines an SMTP client session object that can be used to send
mail to any Internet machine with an SMTP or ESMTP listener daemon. SMTP stands for Simple Mail Transfer Protocol.

Finding all files in the path that ends with a certain extension

This short script uses the os.listdir function (that belongs to the OS module) to search through a given path (“.”) for all files that endswith “.txt”.

Command Line speedtest.net via tespeed

Speedtest.net is a connection analysis website where users can test their internet
speed against hundreds of geographically dispersed servers around the world.

Search computer for specific files

In this article, I will show how to use the os.walk() module function to walk a
directory tree, and the fnmatch module for matching file names.

Parsing with Json

Knowing how to parse JSON objects is useful when you want to access an API
from various web services that gives the response in JSON.

Get the Geo Location of an IP Address

Time for a script again, this one will geolocate an IP address based on input from the user. For this script, we will be using a bunch of Python modules to accomplish this.

Get the username from a prompts

This script will ask the user for its username, by using the raw_input function. Then a list of allowed users is created named user1 and user2. The control statement checks if the input from the user matches the ones that are in the allowed users list.

Tweet Search using Python

This script will use the Twitter API to search for tweets.

Date and Time in Python

In this post, I will show you how you can do it without that by just using
datetime.datetime.now() .

The second part of the post is about the the timedelta class, in which we can see
the difference between two date, time, or datetime instances to microsecond
resolution.

Python Game : Rolling the dice

This is a classic “roll the dice” program.

Monitor Apache / Nginx Log File

This small script will count the number of hits in a Apache/Nginx log file.

Log Checker in Python

This script will show all entries in the file that is specified in the log file
variable.

Count how many days until a birthday

In this post, I will show you how you can print out the dates and times by just using datetime.datetime.now().

Python : Guessing Game part 2

This small program extends the previous guessing game I wrote about in this
: post “Guessing Game”.

Guessing Game written in Python

This script is an interactive guessing game, which will ask the user to guess a
number between 1 and 99.

Python Password Generator

You can use Pythons string and random modules to generate passwords.

OS Walk

OS.walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up.

Convert KM/H to MPH

This script converts speed from KM/H to MPH, which may be handy for calculating
speed limits when driving abroad, especially for UK and US drivers.

Get all the links from a website

In this script, we are going to use the re module to get all links from any website.

Celsius and Fahrenheit Converter

This script converts temperature between Fahrenheit to Celsius.

How to use the Vimeo API in Python

In this post we will be looking on how to use the Vimeo API in Python.

Show the most popular videos on YouTube

This program will show how we can use the API to retrieve feeds from YouTube.

Calculate the average score

This script will calculate the average of three values.

Check your external IP address

This is a simple Python script to check which external IP address you have.

Python Hangman Game

This is a Python script of the classic game “Hangman”.

Python Command Line IMDB Scraper

This script will ask for a movie title and a year and then query IMDB for it.

Python code examples

Here we link to other sites that provides Python code examples.

ActiveState Code – Popular Python recipes

Snipplr.com

Nullege – Search engine for Python source code

Snipt.net

The post Python Code Examples appeared first on PythonForBeginners.com.

]]>
https://www.pythonforbeginners.com/code-snippets-source-code/python-code-examples/feed 11 5785
DNS Lookup With Python https://www.pythonforbeginners.com/code-snippets-source-code/dns-lookup-python Sat, 19 Sep 2015 14:56:24 +0000 https://www.pythonforbeginners.com/?p=6744 The sockets module provides an easy way to look up a host name’s ip address. import socket addr1 = socket.gethostbyname('google.com') addr2 = socket.gethostbyname('yahoo.com') print(addr1, addr2) Which will output the following ip addresses: 173.194.121.9 98.138.253.109

The post DNS Lookup With Python appeared first on PythonForBeginners.com.

]]>
The sockets module provides an easy way to look up a host name’s ip address.


import socket

addr1 = socket.gethostbyname('google.com')
addr2 = socket.gethostbyname('yahoo.com')

print(addr1, addr2)

Which will output the following ip addresses:


173.194.121.9 98.138.253.109

The post DNS Lookup With Python appeared first on PythonForBeginners.com.

]]>
6744
How to Use MySQL Connector/Python https://www.pythonforbeginners.com/code-snippets-source-code/how-use-mysql-connectorpython Sat, 12 Sep 2015 15:58:15 +0000 https://www.pythonforbeginners.com/?p=6742 MySQL Connector/Python is a driver released by Oracle themselves to make it easier to connect to a MySQL database with Python. MySQL Connecter/Python supports all versions of Python 2.0 and later, also including versions 3.3 and later. To install MySQL Connector/Python simply use pip to install the package. Connecting to database and committing to it […]

The post How to Use MySQL Connector/Python appeared first on PythonForBeginners.com.

]]>
MySQL Connector/Python is a driver released by Oracle themselves to make it easier to connect to a MySQL database with Python. MySQL Connecter/Python supports all versions of Python 2.0 and later, also including versions 3.3 and later.

To install MySQL Connector/Python simply use pip to install the package.


pip install mysql-connect-python --allow-external mysql-connector-python

Connecting to database and committing to it is very simple.


import mysql.connector

connection = mysql.connector.connect(user="username", 
                                     password="password", 
                                     host="127.0.0.1", 
                                     database="database_name")

cur = connection.cursor()

cur.execute("INSERT INTO people (name, age) VALUES ('Bob', 25);")
connection.commit()

cur.close()
connection.close()

The post How to Use MySQL Connector/Python appeared first on PythonForBeginners.com.

]]>
6742
Getting popular pages from your Apache logs https://www.pythonforbeginners.com/code-snippets-source-code/getting-most-popular-pages-your-apache-logfile Sat, 08 Feb 2014 15:23:33 +0000 https://www.pythonforbeginners.com/?p=6740 An Apache log file can be huge and hard to read. Here is a way to get a list of the most visited pages (or files) from an Apache log file. In this example, we only want to know the URLs from GET requests. We will use the wonderful Counter which is in Python’s Collections […]

The post Getting popular pages from your Apache logs appeared first on PythonForBeginners.com.

]]>
An Apache log file can be huge and hard to read.
Here is a way to get a list of the most visited pages (or files) from an Apache log file.

In this example, we only want to know the URLs from GET requests. We will use the wonderful Counter which is in Python’s Collections


import collections

logfile = open("yourlogfile.log", "r")

clean_log=[]

for line in logfile:
    try:
        # copy the URLS to an empty list.
        # We get the part between GET and HTTP
        clean_log.append(line[line.index("GET")+4:line.index("HTTP")])
    except:
        pass

counter = collections.Counter(clean_log)

# get the Top 50 most popular URLs
for count in counter.most_common(50):
    print(str(count[1]) + "	" + str(count[0]))

logfile.close()

The post Getting popular pages from your Apache logs appeared first on PythonForBeginners.com.

]]>
6740
How to use Envoy https://www.pythonforbeginners.com/code-snippets-source-code/how-to-use-the-envoy-wrapper Tue, 22 Oct 2013 09:30:29 +0000 https://www.pythonforbeginners.com/?p=5334 About Envoy Recently I stumble upon Envoy. Envoy is a wrapper around the subprocess module and is supposed to humanize subprocess of Python. Its written by Kenneth Reitz (the author of “Requests: HTTP for Humans“) Why use Envoy? It was written to be an easy to use alternative to subprocess. “Envoy: Python Subprocesses for Humans.” […]

The post How to use Envoy appeared first on PythonForBeginners.com.

]]>
About Envoy

Recently I stumble upon Envoy. Envoy is a wrapper around the subprocess module and
is supposed to humanize subprocess of Python.

Its written by Kenneth Reitz (the author of “Requests: HTTP for Humans“)

Why use Envoy?

It was written to be an easy to use alternative to subprocess.

“Envoy: Python Subprocesses for Humans.”

Install Envoy

Envoy is available from PyPI and can be installed with pip.

Search for the Envoy package via the pip command-line tool.

pip search envoy

” envoy – Simple API for running external processes. “Install Envoy

$ pip install envoy

Import Envoy

Just like with any other Python modules, we have to import them first.

Start your Python interpreter and type “import envoy”

import envoy

Great, Envoy is imported, now we can start to discover its functions etc.

Envoy Methods and Attributes

After you have imported a module in Python, it’s always good to see what functions
,classes and methods that the module provides. One way of doing that is using
“dir(envoy)”.

Using dir(module)

That will list the names of all functions and variables, that are defined in the
Envoy module.

>>> dir(envoy)

That will give you an output like this:

['Command', 'ConnectedCommand', 'Response', '__builtins__', '__doc__', '__file__',
'__name__', '__package__', '__path__', '__version__', 'connect', 'core', 'expand_args',
'os', 'run', 'shlex', 'subprocess', 'threading’]

If you want to get one name per line, just run a simple for loop:

>>> for i in dir(envoy): print i

This output shows you one name per line:

...
Command
ConnectedCommand
Response
__builtins__
__doc__
__file__
__name__
__package__
__path__
__version__
connect
core
expand_args
os
run
shlex
subprocess
threading
>>>

You can also use “help(envoy)” to get the documentation on all the functions.

Envoy Usage

Let’s take a look at the “run” method for Envoy.

envoy.run()

To check the uptime of our machine, we can use the “uptime” command.

r = envoy.run("uptime”)

Standard Output

To see the output, we add “std_out”:

>>> r.std_out
'15:11  up 6 days,  1:04, 3 users, load averages: 0.55 0.57 0.61
‘

Status Code

To get the status code, add “status_code” to your object.

print r.status_code
0

Command

Run a command, get the response:

>>> print r

Standard Error

To get the standard error, add “std_err”.

r.std_err

History

Get history.

r.history
[<response 'uptime'="">]

Envoy Examples

Check for the Chrome process

r = envoy.run("ps aux |grep Chrome")
print r.std_out

In our last example, I make use of multiple commands.

import envoy

cmd = ['date', "uptime", "w"]

r = envoy.run(cmd)

print r.std_out

Get the status code of all commands

import envoy

cmd = ['date', "uptime", "w"]

for command in cmd:
    r = envoy.run(cmd)
    print r.status_code

Get the status code + the output of each command

import envoy

cmd = ['date', "uptime", "w"]

for command in cmd:
    r = envoy.run(cmd)
    print r.status_code, r.std_out

Envoy has become my main library to handle external command calls.

It was written to be an easy to use alternative to subprocess and the convenience
of envoy.run is really great.

More Reading

https://github.com/kennethreitz/envoy
http://stackoverflow.com/search?q=envoy

The post How to use Envoy appeared first on PythonForBeginners.com.

]]>
5334
How to use FTP in Python https://www.pythonforbeginners.com/code-snippets-source-code/how-to-use-ftp-in-python https://www.pythonforbeginners.com/code-snippets-source-code/how-to-use-ftp-in-python#comments Thu, 13 Jun 2013 14:50:08 +0000 https://www.pythonforbeginners.com/?p=2621 Overview This article will show how you can use FTP in Python with the help of the ftplib module. Ftplib The ftplib module in Python allows you to write Python programs that perform a variety of automated FTP jobs. You can easily connect to a FTP server to retrieve files and process them locally. To […]

The post How to use FTP in Python appeared first on PythonForBeginners.com.

]]>
Overview

This article will show how you can use FTP in Python with the help of the
ftplib module.

Ftplib

The ftplib module in Python allows you to write Python programs that perform a
variety of automated FTP jobs. You can easily connect to a FTP server to retrieve
files and process them locally.

To use the ftplib module in Python, you first have to import it into your script.

Open a Connection

To “open” a connection to the FTP Server, you have to create the object.

Once the connection is made (opened), you can use the methods in the ftplib
module.

Several methods are available in two flavors: one for handling text files and
another for binary files.

You can easily navigate the directory structure, manage and download files.

How do I use it?

This program will first connect to a FTP server (ftp.cwi.nl) and then list the
files and directories in the FTP server root directory using the LIST() method.

from ftplib import FTP

ftp = FTP('ftp.cwi.nl')   # connect to host, default port

ftp.login()               # user anonymous, passwd anonymous@

ftp.retrlines('LIST')     # list directory contents 

Our second program opens a connection to ‘ftp.sunet.se’ as the user ‘anonymous’
with an email address of ‘[email protected]

It then lists the files and directories on the FTP server by using the dir()
method.

The output is saved to the ‘files’ variable.

I then use print to see the files on screen.

If I want I to change directory I would just use ftp.cwd(path) to do so.

To close the FTP connection, use the quit() method.

import ftplib

ftp = ftplib.FTP('ftp.sunet.se', 'anonymous', '[email protected]')

print "File List: "

files = ftp.dir()

print files

ftp.cwd("/pub/unix") #changing to /pub/unix

Common FTP Methods

FTP.connect(host[, port[, timeout]])

Connect to the given host and port.

The default port number is 21, as specified by the FTP protocol specification.

It is rarely needed to specify a different port number.

This function should be called only once for each instance

It should not be called at all if a host was given when the instance was created.

All other methods can only be used after a connection
has been made.

The optional timeout parameter specifies a timeout in seconds for the connection
attempt.

If no timeout is passed, the global default timeout setting will be used.

FTP.getwelcome()

Return the welcome message sent by the server in reply to the initial connection.

This message sometimes contains disclaimers or help information that may be
relevant to the user

FTP.login([user[, passwd[, acct]]])

Log in as the given user.

The passwd and acct parameters are optional and default to the empty string.

If no user is specified, it defaults to ‘anonymous’.

If user is ‘anonymous’, the default passwd is ‘anonymous@’.

This function should be called only once for each instance, after a connection
has been established.

It should not be called at all if a host and user were given when the instance
was created.

Most FTP commands are only allowed after the client has logged in.

The acct parameter supplies “accounting information”; few systems implement this.

FTP.retrbinary(command, callback[, maxblocksize[, rest]])

Retrieve a file in binary transfer mode.

Command should be an appropriate RETR command: ‘RETR filename’.

The callback function is called for each block of data received, with a single
string argument giving the data block.

The optional maxblocksize argument specifies the maximum chunk size to read on
the low-level socket object created to do the actual transfer.

A reasonable default is chosen. rest means the same thing as in the transfercmd()
method.

FTP.retrlines(command[, callback])

Retrieve a file or directory listing in ASCII transfer mode.

Command should be an appropriate RETR command or a command such as LIST, NLST or
MLSD.

LIST retrieves a list of files and information about those files.

NLST retrieves a list of file names.

On some servers, MLSD retrieves a machine readable list of files and information
about those files.

The callback function is called for each line with a string argument containing
the line with the trailing CRLF stripped.

The default callback prints the line to sys.stdout.

FTP.dir(argument[, …])

Produce a directory listing as returned by the LIST command, printing it to
standard output.

The optional argument is a directory to list (default is the current server
directory).

Multiple arguments can be used to pass non-standard options to the LIST command.

If the last argument is a function, it is used as a callback function as for
retrlines(); the default prints to sys.stdout.

This method returns None.

FTP.delete(filename)

Remove the file named filename from the server.

If successful, returns the text of the response, otherwise raises error_perm on
permission errors or error_reply on other errors.

FTP.cwd(pathname)

Set the current directory on the server.

FTP.mkd(pathname)

Create a new directory on the server.

FTP.pwd()

Return the pathname of the current directory on the server.

FTP.quit()

Send a QUIT command to the server and close the connection.

This is the “polite” way to close a connection, but it may raise an exception if
the server responds with an error to the QUIT command.

This implies a call to the close() method which renders the FTP instance useless
for subsequent calls.

FTP.close()

Close the connection unilaterally.

This should not be applied to an already closed connection such as after a
successful call to quit().

After this call the FTP instance should not be used any more.

After a call to close() or quit() you cannot reopen the connection by issuing
another login() method).

For more information, please see the official Python Documentation

The post How to use FTP in Python appeared first on PythonForBeginners.com.

]]>
https://www.pythonforbeginners.com/code-snippets-source-code/how-to-use-ftp-in-python/feed 1 2621
Sending emails using Google https://www.pythonforbeginners.com/code-snippets-source-code/sending-emails-using-google Thu, 30 May 2013 08:40:13 +0000 https://www.pythonforbeginners.com/?p=5300 Overview A common task for system administrators and developers is to use scripts to send emails if an error occurs. Why use Gmail? Using Googles SMTP servers are free to use and works perfectly fine to relay emails. Note that Google has a sending limit: “Google will temporarily disable your account if you send messages […]

The post Sending emails using Google appeared first on PythonForBeginners.com.

]]>
Overview

A common task for system administrators and developers is to use scripts to send emails if an error occurs.

Why use Gmail?

Using Googles SMTP servers are free to use and works perfectly fine to relay emails. Note that Google has a sending limit: “Google will temporarily disable your account if you send messages to more than 500 recipients or if you send a large number of undeliverable messages. ” As long as you are fine with that, you are good to go.

Where do I start?

Sending mail is done with Python’s smtplib using an SMTP (Simple Mail Transfer Protocol) server. Since we will use Google’s SMTP server to deliver our emails, we will need to gather information such as server, port, authentication. That information is easy to find with a Google search.

Google’s Standard configuration instructions

Outgoing Mail (SMTP) Server – requires TLS or SSL: smtp.gmail.com

Use Authentication: Yes

Port for TLS/STARTTLS: 587

Port for SSL: 465

Server timeouts: Greater than 1 minute, we recommend 5

Account Name or User Name: your full email address (including @gmail.com or @your_domain.com)

Email Address: your email address ([email protected] or username@your_domain.com) Password: your Gmail password

Getting Started

Begin with opening up your favorite text editor and import the smtplib module at the top of your script.

import smtplib

Already at the top we will create some SMTP headers.

fromaddr = '[email protected]'
toaddrs  = '[email protected]'
msg = 'Enter you message here’

Once that is done, create a SMTP object which is going to be used for connection with the server.

server = smtplib.SMTP("smtp.gmail.com:587”)

Next, we will use the starttls() function which is required by Gmail.

server.starttls()

Next, log in to the server:

server.login(username,password)

Then, we will send the email:

server.sendmail(fromaddr, toaddrs, msg)

The final program

You can see the full program below, by now you should be able to understand what it does.

import smtplib
# Specifying the from and to addresses

fromaddr = '[email protected]'
toaddrs  = '[email protected]'

# Writing the message (this message will appear in the email)

msg = 'Enter you message here'

# Gmail Login

username = 'username'
password = 'password'

# Sending the mail  

server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
More Reading

Using Python to send email

The post Sending emails using Google appeared first on PythonForBeginners.com.

]]>
5300
Tweet Search with Python https://www.pythonforbeginners.com/python-on-the-web/tweet-search-with-python Mon, 22 Apr 2013 05:05:14 +0000 https://www.pythonforbeginners.com/?p=5033 Overview Twitter’s API is REST-based and will return results as either XML or JSON, as well as both RSS and ATOM feed formats. Public timelines can be accessed by any client, but all other Twitter methods require authentication. About this script The program is well documented and should be straightforward. Open up a text editor, […]

The post Tweet Search with Python appeared first on PythonForBeginners.com.

]]>
Overview

Twitter’s API is REST-based and will return results as either XML or JSON, as well as both RSS and ATOM feed formats. Public timelines can be accessed by any client, but all other Twitter methods require authentication.

About this script

The program is well documented and should be straightforward. Open up a text editor, copy & paste the code below.

Save the file as: “tweet_search.py” and exit the editor.

Getting Started

Let’s take a look at the program below that we call tweet_search.py

#!/usr/bin/python

import json
import sys
import urllib2
import os

usage = """
Usage: ./tweet_search.py 'keyword'
e.g ./tweet_search.py pythonforbeginners

Use "+" to replace whitespace"
e.g ./tweet_search.py "python+for+beginners"
"""

# Check that the user puts in an argument, else print the usage variable, then quit.
if len(sys.argv)!=2:
    print (usage)
    sys.exit(0)

# The screen name in Twitter, is the screen name of the user for whom to return results for. 

# Set the screen name to the second argument
screen = sys.argv[1]

# Open the twitter search URL the result will be shown in json format
url = urllib2.urlopen("http://search.twitter.com/search.json?q="+screen)

#convert the data and load it into json
data = json.load(url)

#to print out how many tweets there are
print len(data), "tweets"

# Start parse the tweets from the result

# Get only text
for tweet in data["results"]:
    print tweet["text"]

# Get the status and print out the contents
for status in data['results']:
    print "(%s) %s" % (status["created_at"], status["text"])

How does it work?

Let’s break down the script to see what it does.

The script starts with importing the modules we are going to need

Line 3-6

import json
import sys
import urllib2
import os

We create a usage variable to explain how to use the script.

Line 8-14 usage = """ Usage: ./tweet_search.py 'keyword' e.g ./tweet_search.py pythonforbeginners Use "+" to replace whitespace" e.g ./tweet_search.py "python+for+beginners" """

On Line 16 we check that the user puts in an argument, else print the usage variable, then quit.



if len(sys.argv)!=2:
    print (usage)
    sys.exit(0)

Line 21-24 sets the Twitter screen name to the second argument.



screen = sys.argv[1]

Line 27 open the twitter search URL and the result will be shown in json format.



url = urllib2.urlopen("http://search.twitter.com/search.json?q="+screen)

Line 30 converts the data and loads it into json



data = json.load(url)

On Line 33 we print out the number of tweets



print len(data), "tweets"

From Line 38 we start to parse the tweets from the result

for tweet in data["results"]:
    print tweet["text"]

The last thing we do in this script is to get the status and print out the contents (Line 42)



for status in data['results']:
    print "(%s) %s" % (status["created_at"], status["text"])

Go through the script line by line to see what it does. Make sure to look at it, and try to understand it.

The post Tweet Search with Python appeared first on PythonForBeginners.com.

]]>
5033
Magic 8-ball Game Written in Python https://www.pythonforbeginners.com/code-snippets-source-code/magic-8-ball-written-in-python https://www.pythonforbeginners.com/code-snippets-source-code/magic-8-ball-written-in-python#comments Sun, 14 Apr 2013 03:46:38 +0000 https://www.pythonforbeginners.com/?p=5023 The Magic 8 Ball is a toy game for fortune-telling or seeking advice. In this article, we will implement the magic 8-ball game in Python. What is the Magic 8-Ball Game? A magic 8-ball is a hollow sphere made out of plastic and printed to look like the 8-ball from a billiards game. It is […]

The post Magic 8-ball Game Written in Python appeared first on PythonForBeginners.com.

]]>
The Magic 8 Ball is a toy game for fortune-telling or seeking advice. In this article, we will implement the magic 8-ball game in Python.

What is the Magic 8-Ball Game?

A magic 8-ball is a hollow sphere made out of plastic and printed to look like the 8-ball from a billiards game. It is filled with a dark blue or black liquid, usually alcohol, and contains a 20-sided die. Instead of numbers on the die, the sides are printed with a variety of yes, no, and maybe-type answers. A standard Magic 8 Ball has twenty possible answers, including ten affirmative answers, five non-committal answers, and five negative answers.

To play the magic 8-ball game, the player holds the ball and thinks of a yes or no question. They then shake the ball, which agitates a printed die floating in the dark blue liquid inside of the ball. When the shaking stops, the die settles to the bottom of the ball, revealing a yes, no, or vague answer. You can read more about this game on its wiki page.

The core functionality of the magic 8-ball game is to predict the outcome of a certain event from 20 possible outcomes in a random manner. To implement this functionality, we can use the random module in Python.

How to Implement Magic 8-ball Game in Python?

We can implement the magic 8-ball game in Python using the randint() function with if-else statements. Alternatively, we can also use the choice() function defined in the random module in Python to implement the magic 8-ball game. Let us discuss both approaches one by one.

Using The randint() Function

To implement the magic 8-ball game in Python using the randint() function, we will use the following steps.

  • First, we will ask the user to enter a question using the input() function.
  • Next, we will generate a random number between 1 to 20 using the randint() function. For this, we will pass the value 1 as its first input argument and the value 20 as its second input argument.
  • After generating the random number, we will select one of the possible answers using the if-else block and print it.
  • Until the user keeps entering questions, we will continue the game using a while loop. If the user doesn’t input any questions, we will terminate the loop using the break statement.

You can observe the above process in the following example.

import random
while True:
    question=input("Ask the magic 8 ball a question: (press enter to quit) ")
    answer=random.randint(1,20)
    if question=="":
        print("Stopping the Game.")
        break
    if answer==1:
        print("It is certain.")
    elif answer==2:
        print("It is decidedly so.")
    elif answer==3:
        print("Without a doubt.")
    elif answer==4:
        print("Yes definitely.")
    elif answer==5:
        print("You may rely on it.")
    elif answer==6:
        print("As I see it, yes.")
    elif answer==7:
        print("Most likely.")
    elif answer==8:
        print("Outlook good.")
    elif answer==9:
        print("Yes.")
    elif answer==10:
        print("Signs point to yes.")
    elif answer==11:
        print("Reply hazy, try again.")
    elif answer==12:
        print("Ask again later.")
    elif answer==13:
        print("Better not tell you now.")
    elif answer==14:
        print("Cannot predict now.")
    elif answer==15:
        print("Concentrate and ask again.")
    elif answer==16:
        print("Don't count on it.")
    elif answer==17:
        print("My reply is no.")
    elif answer==18:
        print("My sources say no.")
    elif answer==19:
        print("Outlook not so good.")
    elif answer==20:
        print("Very doubtful.")

Output:

Ask the magic 8 ball a question: (press enter to quit) Python is awesome
Yes.
Ask the magic 8 ball a question: (press enter to quit) PFB is great.
Yes definitely.
Ask the magic 8 ball a question: (press enter to quit) 
Stopping the Game.

In the above code, we have used 20 if-else blocks to implement the answers. You can observe that the if-else blocks made the code redundantly large. Hence, we can use a Python dictionary to imitate the functionality of the if-else blocks. For this, we will use the numbers as the keys and the answers for each number as the corresponding values.

After predicting a number using the randint() method, we can get the answer from the dictionary and print it as shown below.

import random
answer_dict={1:"It is certain.",
            2:"It is decidedly so.",
            3: "Without a doubt.",
            4:"Yes definitely.",
            5:"You may rely on it.",
            6:"As I see it, yes.",
            7:"Most likely.",
            8:"Outlook good.",
            9:"Yes.",
            10:"Signs point to yes.",
            11:"Reply hazy, try again.",
            12:"Ask again later.",
            13:"Better not tell you now.",
            14:"Cannot predict now.",
            15:"Concentrate and ask again.",
            16:"Don't count on it.",
            17:"My reply is no.",
            18:"My sources say no.",
            19:"Outlook not so good.",
            20:"Very doubtful."}
while True:
    question=input("Ask the magic 8 ball a question: (press enter to quit) ")
    answer=random.randint(1,20)
    if question=="":
        print("Stopping the Game.")
        break
    answer_string=answer_dict[answer]
    print(answer_string)

Output:

Ask the magic 8 ball a question: (press enter to quit) Python is awesome.
Yes definitely.
Ask the magic 8 ball a question: (press enter to quit) PFB is great.
Reply hazy, try again.
Stopping the Game.

In this example, we first generate a random number between 1 to 20 using the randint() function to predict the answer. As we have already defined the dictionary with numbers as keys and the possible answers as their values, we use the indexing operator to get the string value associated with the random number and print it.

Using The choice() Function

Instead of the randint() function, we can also use the choice() function defined in the random module to implement the magic 8-ball game. The choice() function takes a list as its input argument and returns a random element from the list. To implement the game, we will put all 20 answers in a list. After this, whenever the user asks a question, we will select a value from the list using the choice function and print it as shown in the following example.

import random
answer_list=['It is certain.', 
             'It is decidedly so.', 
             'Without a doubt.',
             'Yes definitely.', 
             'You may rely on it.', 
             'As I see it, yes.',
             'Most likely.',
             'Outlook good.', 
             'Yes.', 
             'Signs point to yes.',
             'Reply hazy, try again.', 
             'Ask again later.', 
             'Better not tell you now.',
             'Cannot predict now.', 
             'Concentrate and ask again.',
             "Don't count on it.", 
             'My reply is no.', 
             'My sources say no.', 
             'Outlook not so good.',
             'Very doubtful.']
while True:
    question=input("Ask the magic 8 ball a question: (press enter to quit) ")
    if question=="":
        print("Stopping the Game.")
        break
    answer_string=random.choice(answer_list)
    print(answer_string)

Output:

Ask the magic 8 ball a question: (press enter to quit) Python is awesome
You may rely on it.
Ask the magic 8 ball a question: (press enter to quit) PFB is great
You may rely on it.
Ask the magic 8 ball a question: (press enter to quit) PFB is awesome.
My reply is no.
Ask the magic 8 ball a question: (press enter to quit) PFB is good.
Yes definitely.
Ask the magic 8 ball a question: (press enter to quit) 
Stopping the Game.

In this example, we have stored all the possible answers in a list. When the user asks for an answer, we directly select a random answer from the list using the choice() function and print it.

Conclusion

In this article, we discussed three ways to implement the magic 8-ball game in Python. To learn more about Python programming, you can read this article on rolling the dice game in Python. You might also like this article on python trees.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

The post Magic 8-ball Game Written in Python appeared first on PythonForBeginners.com.

]]>
https://www.pythonforbeginners.com/code-snippets-source-code/magic-8-ball-written-in-python/feed 16 5023
CommandLineFu with Python https://www.pythonforbeginners.com/code-snippets-source-code/commandlinefu-with-python Thu, 14 Mar 2013 10:30:24 +0000 https://www.pythonforbeginners.com/?p=4840 Overview One of the best methods to practice Python coding is to study some code and try them out yourself. By doing a lot of code exercises, you will get a much better understanding of what it really does. In other words, learning by doing. To help you improve your Python coding skill, I’ve created […]

The post CommandLineFu with Python appeared first on PythonForBeginners.com.

]]>
Overview

One of the best methods to practice Python coding is to study some code and try them out yourself. By doing a lot of code exercises, you will get a much better understanding of what it really does.

In other words, learning by doing. To help you improve your Python coding skill, I’ve created a program below which is using the API from CommandLineFu.com

CommandLineFu API

A common first step when you want to use a Web-based services is to see if they have an API.

Luckily for me, Commandlinefu.com provides one and can be found here:

“The content of commandlinefu.com is available in a variety of different formats for you to do what you like with. Any page which contains a list of commands (such as the listings by tag, function or user) can be returned in a format of your choice through a simple change to the request URL.”

The example URL that they provide is:

http://www.commandlinefu.com/commands/’command-set’/’format’/

where: command-set is the URL component which specifies which set of commands to return.

Possible values are:

  • browse/sort-by-votes
  • tagged/163/grep
  • matching/ssh/c3No

Format is one of the following:

  • plaintext
  • json
  • rss

I prefer using the json format and that is also what I’m using in the program below.

Creating the “Command Line Search Tool”

I think we have all the API information we need, so let’s get to it. The program is well documented and should be straightforward.

Open up a text editor, copy & paste the code below. Save the file as: “commandlinefu.py” and exit the editor.

#!/usr/bin/env python27
import urllib2
import base64
import json
import os
import sys
import re

os.system("clear")
print "-" * 80
print "Command Line Search Tool"
print "-" * 80

def Banner(text):
    print "=" * 70
    print text
    print "=" * 70
    sys.stdout.flush()

def sortByVotes():
    Banner('Sort By Votes')
    url = "http://www.commandlinefu.com/commands/browse/sort-by-votes/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    #print json.dumps(response,indent=2)
    for c in response:
        print "-" * 60
        print c['command']

def sortByVotesToday():
    Banner('Printing All commands the last day (Sort By Votes) ')
    url = "http://www.commandlinefu.com/commands/browse/last-day/sort-by-votes/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    for c in response:
        print "-" * 60
        print c['command']

def sortByVotesWeek():
    Banner('Printing All commands the last week (Sort By Votes) ')
    url = "http://www.commandlinefu.com/commands/browse/last-week/sort-by-votes/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    for c in response:
        print "-" * 60
        print c['command']

def sortByVotesMonth():
    Banner('Printing: All commands from the last months (Sorted By Votes) ')
    url = "http://www.commandlinefu.com/commands/browse/last-month/sort-by-votes/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    for c in response:
        print "-" * 60
        print c['command']

def sortByMatch():
    #import base64
    Banner("Sort By Match")
    match = raw_input("Please enter a search command: ")
    bestmatch = re.compile(r' ')
    search = bestmatch.sub('+', match)
    b64_encoded = base64.b64encode(search)
    url = "http://www.commandlinefu.com/commands/matching/" + search + "/" + b64_encoded + "/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    for c in response:
        print "-" * 60
  print c['command']

print """
1. Sort By Votes (All time)
2. Sort By Votes (Today)
3. Sort by Votes (Week)
4. Sort by Votes (Month)
5. Search for a command
 
Press enter to quit
"""

while True:
  answer = raw_input("What would you like to do? ")

 if answer == "":
    sys.exit()
  
  elif answer == "1":
   sortByVotes()
 
  elif answer == "2":
   print sortByVotesToday()
  
  elif answer == "3":
   print sortByVotesWeek()
 
  elif answer == "4":
   print sortByVotesMonth()
  
  elif answer == "5":
   print sortByMatch()
 
  else:
   print "Not a valid choice"

When you run the program, you will be presented with a menu in which you can make your choices.


--------------------------------------------------------------------------------
Command Line Search Tool
--------------------------------------------------------------------------------

1. Sort By Votes (All time)
2. Sort By Votes (Today)
3. Sort by Votes (Week)
4. Sort by Votes (Month)
5. Search for a command

Press enter to quit

What would you like to do?
...
...

The post CommandLineFu with Python appeared first on PythonForBeginners.com.

]]>
4840