(Bookflare - Net) - Hacking University Mobile Phone & App Hacking & The Ultimate Python Programming PDF
(Bookflare - Net) - Hacking University Mobile Phone & App Hacking & The Ultimate Python Programming PDF
By Isaac D. Cody
QUICK TABLE OF CONTENTS
This book will contain 2 manuscripts from the Hacking Freedom and Data
Driven series. It will essentially be two books into one.
Both books are for intended for beginner’s and even those with moderate
experience with Hacking Mobile Devices and with Python.
Hacking University: Sophomore Edition
By Isaac D. Cody
Copyright 2016 by Isaac D. Cody - All rights reserved.
This document is geared towards providing exact and reliable information in regards to the topic and
issue covered. The publication is sold with the idea that the publisher is not required to render
accounting, officially permitted, or otherwise, qualified services. If advice is necessary, legal or
professional, a practiced individual in the profession should be ordered.
- From a Declaration of Principles which was accepted and approved equally by a Committee of the
American Bar Association and a Committee of Publishers and Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic
means or in printed format. Recording of this publication is strictly prohibited and any storage of this
document is not allowed unless with written permission from the publisher. All rights reserved.
The information provided herein is stated to be truthful and consistent, in that any liability, in terms of
inattention or otherwise, by any usage or abuse of any policies, processes, or directions contained
within is the solitary and utter responsibility of the recipient reader. Under no circumstances will any
legal responsibility or blame be held against the publisher for any reparation, damages, or monetary
loss due to the information herein, either directly or indirectly.
The information herein is offered for informational purposes solely, and is universal as so. The
presentation of the information is without contract or any type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of the trademark is without
permission or backing by the trademark owner. All trademarks and brands within this book are for
clarifying purposes only and are the owned by the owners themselves, not affiliated with this
document.
Disclaimer
All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in any
form or by any means, including photocopying, recording, or other electronic or mechanical methods,
without the prior written permission of the publisher, except in the case of brief quotations embodied in
critical reviews and certain other noncommercial uses permitted by copyright law.
Table of Contents
Introduction
Jailbreaking iOS
Rooting Android
PlayStation
PS2
PS3
Xbox
Xbox 360
PC Emulators
Conclusion
Introduction
Thank you for downloading the book “Hacking University: Sophomore Edition”. If you are
reading this, than either you have already completed “Hacking University: Freshman Edition” or you
believe that you already have the hacking skills necessary to start at level 2. This eBook is the
definitive guide for building your hacking skill through a variety of exercises and studies.
As explained in the previous book, hacking is not a malicious activity. Hacking is exploring
the technology around us and having fun while doing so. This book’s demonstrations will mainly focus
on “unlocking” or “jailbreaking” a variety of devices, which is in no way illegal. However, performing
unintended servicing or alterations of software and hardware may possibly void any warranties that you
have. Continue at your own risk, as we hold no fault for damage that you cause. However, if you wish
to gain real control over the phones and game consoles that you own, continue reading to see how top
hackers employ their trade.
History of Mobile Hacking
Phone hacking, also known as Phreaking, has a peculiar history dating back to the 1950’s.
Phreaking was discussed at length in the 1st book, so it will only be briefly recalled here. After phone
companies transitioned from human operators to automatic switchboards, a dedicated group of
experimental “phreakers” found the exact frequencies and tones that can “hack” the switchboards. The
act grew into a hobby and culture of individuals who could make long distance calls for free or
eavesdrop on phone lines. When landlines became more complicated and cell phones took over,
phreaking died out to be replaced by computer hacking.
The first cellphone hackers simply guessed the passwords for voicemail-boxes because the cell
phone owners rarely ever changed their PIN from the default. With a simple number such as “0000” or
“1234” as a passcode, hackers can effortlessly gain access to the voicemail-box and can listen in on any
message.
Another technique, known as “spoofing”, allows an attacker to change the number that shows
on the caller-ID. By impersonating a different number, various attack strategies with social engineering
possibilities are available.
With the advent of flip-phones mobile devices became smaller and more efficient. Although
some dedicated hackers could flash new ROMs onto stolen phones or read text messages with
complicated equipment, the early cell phones did not have too much sensitive data to steal. It wasn’t
until phones became more advanced and permanently tied to our online life that cell phone hacking
became a lucrative field.
With the early 2000’s Blackberry phones and the later 2000’s iPhones advancing cellular
technology to be on par with personal computers, more of our information was accessible from within
our pockets. Security is often sacrificed for freedom and ease-of-use, so hackers were able to exploit
the weak link of mobile technology fairly easily.
How are hackers able to break into the mini-computers in our pockets? Through mostly the
same techniques that hackers use to break into regular desktop PCs- software vulnerabilities, bugs,
social engineering, and password attacks.
Most mobile hacks are low-level stories of celebrities getting their private pictures stolen or
risqué messages being leaked. Typically these attacks and hacks come about because of the
technological ineptitude of celebrities and their less-than-best security habits. Every once in a while,
though, the spotlight will shine upon big-name jobs, such as Hillary Clinton’s email server leaks, or
Edward Snowden and his disclosure of classified government information. Events like these show just
how critical security is in all facets of digital life- and a person’s phone should never be the device that
facilitates a hacking attack on them.
Perhaps the most widely discussed phone hack in recent news would be the San Bernardino
terrorist attack of 2015 and the resulting investigation. After a couple killed 16 and injured 24 more in
the California town, both assailants were killed in the aftermath and an investigation began of the two’s
background. Farook, one of the shooters, had a county-issued iPhone 5C that investigators believed
would contain additional evidence surrounding the attacks. Additionally, having access to the device
would mean that the FBI could investigate any communications into and out of the phone, possibly
revealing any active terrorist groups or influences.
However, the iPhone was password protected and up to date with iOS’s advanced security
features that guaranteed the government could not access the contents of the phone. The NSA, FBI,
and other government groups could not break the protection, so they demanded Apple provide a
backdoor in iOS for the FBI to access data. Apple refused, stating such a backdoor would provide
hackers, viruses, and malware a vector through which to target all iOS devices indiscriminately.
Tensions ramped up between the FBI and Apple, but Apple stood its ground long enough for
the government to seek help elsewhere. Finally on March 28th, 2016, the phone was cracked by 3rd
party group of hackers for a million US dollars. How the group successfully broke the unbreakable is
not fully known, but it is believed that a zero-day vulnerability (a vulnerability that nobody knew
about) was used to gain access to the iOS.
The whole scenario showed that the government is not above civilian privacy- they will use all
resources at their disposal to gain access to our devices. While most agree that the phone needed to be
unlocked as a matter of national security, it still holds true that if Apple were to comply with the
government than groups like the NSA and FBI would have direct links to all iOS devices and their data
(a clear breach of trust). Mobile phone security will continue to be a hot issue in the coming years, so
learning how to protect yourself by studying how hackers think will save you in the long run.
Security Flaws in Mobile Devices
Mobile devices including phones and laptops are especially vulnerable to the common IT
problems. However the portability of the handy devices only amplifies the variety of attack vectors.
Wi-Fi points often exist in coffee shops, public eateries, and libraries. Free and open Wi-Fi is always
helpful, except they open up mobile devices to data interception and “man-in-the-middle” attacks.
For example, say a hacker creates a public Wi-Fi point. By naming it something
inconspicuous such as “Starbucks free Wi-Fi”, people will be sure to connect with their phones and
laptops. At this point, the hacker has installed Kali Linux (refer to “Freshman Edition” for more info)
and also connected to the compromised internet. They run a packet capture program and steal online
banking information in real time while the victims thinks nothing is wrong. Security minded
individuals should always remember that open Wi-Fi hotspots are dangerous, and they should only ever
be connected to for simple browsing or with a VPN running.
Social engineering plays a large part in mobile hacking as well. Phone users usually forget that
phones can get viruses and malware just as PCs can, so the user is often off-guard and willing to click
links and download Trojan horses when browsing from their phone. The following demonstration
(courtesy of http://wonderhowto.com) takes advantage of an Android device on the same network
(we’re in a Starbucks) and gives control to the hacker.
1. Start a laptop with Kali Linux and the metasploit application installed.
9. Now you’ll need to deliver the exploit to your victim. You could come up to them and
ask “hey, have you tried Starbuck’s free game app for Android? It’s pretty fun”. With
their permission, you could email them the application. When they download and start it
on their phone, return to your laptop and type exploit into the metasploit console. The
two devices will communicate and you will be given control over parts of the phone.
The lesson learned is to never install any app that seems strange or comes from an irreputable
source. Later in the book, especially when talking about jailbreaking and rooting, we will install lots of
“unverified” applications. Ultimately there is no real way to know if we are installing a legitimate app
or a Trojan horse like above. When it comes to unofficial applications, you must trust your security
instincts and only install from trusted sources.
Heartbleed is a famous 2014 OpenSSL bug that affected half a million web servers and also hit
nearly 50 million Android devices. The vulnerability allowed hackers to read data stored in memory
such as passwords, encryption keys, and usernames by overflowing the buffer of TLS encryption. So
massive was the impact that devices everywhere needed emergency patches to protect themselves.
OpenSSL resolved the vulnerability as quickly as possible, and Android vendors issued an update that
patched the problem.
Not just Android is affected by hackers, for the iPhone 6 and 6S running iOS9 versions under 9.3.1
can have their pictures rifled through even if there is a passcode or fingerprint enabled. Here is the
process. Follow along to see if your phone is vulnerable.
3. Siri will ask what to search for, respond with “@yahoo.com”, at “@att.net”,
“@gmail.com”, or any other email suffix.
4. Siri will display relevant results, so find a full email address among them. Press firmly
on the address (3D touch) and then press “add new contact”.
5. By then “adding a photo” to our new “contact”, we have access to the entire picture
library.
This is reminiscent of an earlier iOS9 bug that could totally unlock a phone without a passcode.
You can do this hack on unupdated iOS9.
3. Say anything.
5. Reminders will launch, long press the one you just created and click “share”.
7. Enter any name, then tap on the name to create a new contact.
8. Tap choose photo, and you can then press the home button to go to the home screen
while unlocked.
Most vulnerabilities such as the two mentioned are patched almost as soon as they are discovered,
which is why they will not work on an updated iOS9.
Finally, there is one final tactic that a hacker can use to break into a phone if they have physical
possession of it. If a hacker really wants to gain access to a mobile device, they can do so at the cost of
deleting all data. Through a factory reset, a hacker will erase absolutely everything on the device
including the password and encryption, but they will be able to use the device or sell it to somebody
else.
1. Shut off the phone, connect it to a computer with iTunes, and boot the iPhone into
recovery mode (hold power button and home buttons at same time until recovery mode it
shown).
2. On iTunes, click the “restore” button that pops up to delete all data and claim the phone
as your own.
Every Android device has a different button combination to enter recovery mode, so research your
phone’s model. We will demonstrate factory resetting an Android phone with the most common
combination.
1. Shut off the phone and boot it into recovery mode. The power button and volume down
button held together is a common combination.
2. Use the physical buttons (sometimes volume up and down) to navigate the menu. Select
factory reset and confirm.
Unlocking a Device from its Carrier
Phones and other mobile devices are often “locked” to a specific carrier, meaning the device
cannot have cell service from any other company. The locked phone is essentially held hostage by the
carrier- unless you follow through with an unlocking process. Carriers can help you through the
process, but you usually need a good reason to have the device unlocked (traveling to areas without
coverage, military deployment, contract has expired and you are switching). Stolen devices cannot be
unlocked. The cheapest phones you can find on eBay are sometimes stolen, and carriers may refuse to
unlock if they have the device filed as lost or stolen.
It is important to note that phones run on networks (GSM and CDMA) that limit the number of
carriers a phone can operate on- a mobile device’s network cannot be changed at all, but the carrier that
operates on the same network CAN be changed.
Most unlocks require the phone to be fully payed off, have an account in good standing, and
you must not exceed too many unlocks in one year. The process involves gathering all information
about the phone (phone number, IMEI, account information, account holder information), proving you
own it, and requesting the device be unlocked through phone call or internet form. Sadly, some carriers
simply cannot be unlocked. The most popular cell carriers are listed here.
The networks that different phones operate on actually vary, so you’ll need to do a little
research to find out what networks a phone can run on. The networks listed above are the most popular
ones that are used on different carrier’s devices. The unlock process may prove difficult, but phone
unlocking stores exist that can go through the process for you.
Securing your Devices
As previously explained, older versions of operating systems retain many bugs and exploits.
Especially with phones always install the latest updates as soon as possible.
One of the reasons that the San Bernardino phone was so hard to crack was because of Apple’s
inherent encryption that is enabled when there is a passcode present. What this means for the security-
minded iPhone owner is that having a passcode ensures fantastic protection. So long as a passcode is
enabled, the phone is also encrypted. Simple hacks cannot extract data that is encrypted, and that is
why the FBI had to pay for an alternative exploit.
Readers of the previous book will remember that encryption is the scrambling of data to
dissuade access. Only people with the correct password can decode the jumbled text. Just as with
desktops, encrypting your mobile phone will protect it from unauthorized access. All iPhones (with
newer updates) automatically encrypt when passcode is enabled. Android phones running OS 6.0 and
above are encrypted automatically, but those running older operating systems must enable the feature
manually (“settings”, “security”, “encrypt phone”). Encrypted phones will run slower, but they will be
more secure. Even some text messaging apps (WhatsApp) can encrypt text messages that are sent.
If a hacker or agency were to get possession of the device, though, there is still one trick that
gives opposition the upper hand. Even phones with passcodes and encryption still readily show
notifications on the lock screen by default. Say, for instance, a hacker has possession of the phone and
they attempt to login to your online banking. Without the password, though, the attacker can still send
a verification code to the phone and see it on the lock screen. Nullify lock screen problems by
disabling the notifications entirely. On iDevices go through “settings”, “control center”, and then turn
“Access to Lock Screen” off. On an Android progress through “settings”, “sound and notifications”,
then turn “while locked” to off.
Say there is an app installed on your mobile device and you suspect that it may contain a
Trojan horse or have malicious intent. The app may have been installed from a 3rd party, or you may
have your suspicions that Facebook is collecting data on you. Luckily on both iPhone and Androids
you can turn off specific app permissions to restrict the amount of access the app has. Just as when you
install an app it requests permission for, say, microphone, camera, and contacts, you can revoke those
permissions at any time.
Android phones edit permissions (in Marshmallow 6.0) in the settings app. The “apps” tab
shows all apps installed, and by clicking the settings button in the top right you can select “app
permissions”. The next screen shows every accessible part of your Android, such as camera, contacts,
GPS, etc… You can edit each category and change which apps have permission to use them. It is
always recommended that apps only be given the least amount of permissions necessary to perform
their tasks, so disable anything that you don’t use or don’t need.
iOS has debatably better app permission methods, as it only requests use of a peripheral when
the app wants to use it. Security-minded individuals can take the hint that a request for permissions at
an odd time would obviously mean nefarious activity is taking place. Nonetheless app permissions can
be taken away too, through the “privacy” tab in “settings”. Just as with Android, tapping on a category
shows all apps that use that function and give you the option to revoke the permissions.
Malware and viruses still exist for mobile devices. Phones and tablets can be secured by
installing an antivirus app from a trusted source. Some attackers like to disguise Trojan horses as
antivirus apps, though; only download apps that seem reputable and have good reviews. Don’t be
against paid antivirus apps, either, because they are usually the ones that work best.
Modding, Jailbreaking, and Rooting
Contemporary devices are locked down, running proprietary software, and closed to
customization. The act of modding a device to gain additional functionality has a slew of different
names; on iPhones the modding process is commonly known as “Jailbreaking”, on Android phones it is
known as “rooting”, and on video game consoles the action is referred to as just “modding”.
Hackers enjoy modding their hardware to increase the amount of freedom it gives them. For
example, iPhones only have one layout, icon set, set of ringtones, and very few customization settings.
Android phones have decent customization, but some settings are set in stone and unchangeable.
Rooting adds more customization and allows apps to interact with the core filesystem for unique
features. Commonly people root and jailbreak for extra apps and games. Modding game consoles
allows them to run full- fledged operating systems or even play backup games from burned discs.
Below we will discuss the benefits, downsides, and features of modding a few popular devices. Once
again it is important to note that you may void a warranty by altering your gadgets. Also, modding has
a small risk of ruining the hardware permanently (bricking); this makes the technology unusable. We
are not responsible for damages, so do the demonstrations at your own risk and proceed cautiously.
Jailbreaking iOS
The iPhone is conceivably the most “hacked” device because of the limited customizability
and strict app store guidelines that Apple imposes. Some groups love the simplicity of the iPhone in
that regard, though, while adept technological experimenters would rather have full control. If one
jailbreaks their iPhone, they gain access to the minute details usually locked away and unchangeable.
Suddenly they can change the pictures on the icons, how many icons are in a row, animations, what the
lockscreen layout looks like and much more. Furthermore, a jailbroken iPhone is not restricted to just
the “Apple Store”, there are other free app stores that Jailbroken iPhones can download applications
from. The range of functions that these new and “banned” apps bring to you certainly make
jailbreaking worth it.
There are a few restrictions though, as Apple tries to deter jailbreaking through patching their
iOS. To see if your iDevice is able to be jailbroken, you will need to know which version of iOS you
are running. From the “Settings” app, tap “General” and then “About”. Note the version number and
check https://canijailbreak.com, a popular website that lists the jailbreakable versions of iOS. Each
version of iOS will have a link to the tool that will help jailbreak the iDevice.
“Tethered” jailbreaks are conditional jailbreaks that require you to boot the iDevice with the
help of a computer. A tethered jailbreak could possibly damage your phone if started without the aid of
a PC, and if your battery dies away from home than the phone is basically unusable even after a charge.
This is obviously not the best solution, so consider if a “tethered” jailbreak is worth the trouble to you.
Some versions of iOS are able to be untethered, though, which is ideal in nearly all situations.
Before starting any jailbreak, make a backup of your phone data just in case something goes
wrong or you wish to return to a normal, unjailbroken phone.
Pangu / Evasi0n
1. Download the application you need to your computer.
7. Follow any on-screen prompts. You will need to follow any instructions the application
gives you, including taking action on the desktop computer or iDevice.
Each iDevice may or may not be jailbreakable, but generally most iPhones and iPads can be
exploited so long as they are not running the newest iOS update. But attempting to jailbreak a device
which is definitely known to not work may result in a totally bricked device.
A jailbroken iPhone’s best friend is Cydia, the “hacked” appstore. Cydia allows you to add
repositories and download applications. A repository is a download storage that contains applications
and modifications. In order to download a few specific apps, you will have to add the repository to
Cydia. Each version of Cydia may have slightly different default repositories, this process below is
how you check the installed repos and add new ones:
Repositories are typically URLs, and you can find them in a variety of places. You can internet
search for “best Cydia repos” or just find an alphabetical list and search for good ones. Be careful of
adding too many sources, though, because that will slow down the Cydia app as it tries to contact each
server and get the app lists regularly. Some of the best sources include:
BigBoss
ModMyI
iSpazio
Telesphoreo Tangelo
Ste
ZodTTD
The previous sources are usually default, but here are some that you might have to add manually:
iHacksRepo (http://ihacksrepo.com)
SiNful (http://sinfuliphonerepo.com)
iF0rce (http://apt.if0rce.com)
InsanelyiRepo (http://repo.insanelyi.com)
BiteYourApple (http://repo.biteyourapple.net)
Customizing the icons and colors of iOS is possibly the most used feature of a jailbroken iOS. The
two best apps to change out parts of iOS are Winterboard and Anemone. Search for these two apps
within Cydia and install them. Now you can search through the repositories for a theme you want to
apply. Winterboard themes in particular can be entire cosmetic changes that replace every bit of the
iOS with new colors, content, and icons. For a new set of icons only, just search for icon packs.
Apps that change the look of iOS are aesthetically pleasing, but they can often conflict and cause
bugs within the operating system. Some themes and icon sets may crash apps or cause the phone to
restart occasionally. This is an unfortunate side effect of compatibility and newer developers with poor
code, so use themes at your discretion.
There are too many Cydia apps to count, so here is a short list of a few popular ones and why you
should consider downloading them.
iCaughtU takes a snapshot when your device’s passcode is entered incorrectly. Catch
snoopers and thieves in the act.
iFile allows you to actually interact with the files on your iDevice. This is a feature built
into Android that is mysteriously missing in iOS.
Tage/Zephyr are two apps that allow customization of multitasking gestures. You can
make, say, swiping in a circle launch your text messages to save time. Tage is the newest
app, but older devices may need to run Zephyr.
Activator allows you to launch apps or start iOS features with buttons such as triple
tapping home or holding volume down.
TetherMe creates a wireless hotspot without having to pay your carrier’s fee for doing
so.
The app possibilities are endless. You can take hours just searching through Cydia to find your
favorite tweaks and modifications. Once again be warned that installing too many may bog down iOS
and cause it to crash, so install sparingly.
Another benefit to jailbreaking comes about through the games that can be played. While there are
a few game “apps” that are available for download through Cydia, the main attraction for gamers are
certainly emulators. Emulators are apps that imitate game consoles so their games can be played on
iOS, usually for free. The process to play emulated games is somewhat difficult, but major steps will
be explained below. Please note that the steps will vary as per emulator, game, and device.
2. The source may or may not be included on your specific device, so search for
“RetroArch”. If it does not show, add the source http://buildbot.libretro.com/repo/cydia
or possibly http://www.libretro.com/cydia, restart the app and search again.
3. Download and install RetroArch.
4. Launch the app, navigate to “Online Updater”, and update every entry starting from the
bottom.
5. When you get to “Core Updater”, update “Playstation (PCSX ReARMed) [Interpreter]”.
RetroArch is downloading the actual emulator that you will use to play PS1 games here.
6. Go back to the main menu, “Load Core”, then select the Playstation entry that we just
downloaded.
Now we need to obtain a ROM (game file). ROMs are digital backups of the games we play.
There is nothing illegal about putting your PS1 game CD into your computer and making an .iso
backup with a tool like PowerISO (http://poweriso.com) or IMGBurn (http://www.imgburn.com).
Basically you install one of the aforementioned programs, launch it, insert your PS1 disc into the CD
drive, and then create an .iso file with the program. Finally, with a PC program such as iFunBox
(http://www.i-funbox.com/), you can transfer that .iso onto your iOS device.
The above process is fairly confusing, and hackers usually want to emulate games they don’t
already own. An astute hacker can download a ROM straight from the internet to their iOS device, but
the legality of this action varies depending on country and state. We do not condone illegally
downloading ROMs, but the process must be explained for educational purposes. Some websites such
as CoolROM (http://coolrom.com), romhustler (http://romhustler.com), and EmuParadise
(http://emuparadise.me) offer PS1 rom downloads for free, and a curious individual can search there for
just about any ROM game they want. After downloading the file, another app such as iFile is needed to
place the downloaded ROM in the correct folder. Install iFile from Cydia, navigate to where your
browser downloads files (it varies based on browser, but try looking in
var/mobile/containers/data/application to find your browser’s download path). Copy the file, then
navigate to /var/mobile/documents and paste it there.
Lastly after the long process restart RetroArch, tap “Load Content”, “Select File”, and then tap the
game’s .iso. You will now be playing the game.
iPhone emulation is difficult. There is no easy way to download ROMs and put them where they
need to be. You must also be careful while searching for ROMs on the internet, because many websites
exist solely to give out viruses to unsuspecting downloaders. Also, the emulators on iPhone are poor
compared to Android, so the above process may not even work well for you. In this case, consider
downloading another PS1 emulator from Cydia. RetroArch is capable of playing a few other systems
too, just replace Playstation steps above with your console of choice. Ultimately, though, if your game
crashes or fails to start there is not much you can do. Consider looking into PC emulation, as it is much
easier to emulate old console games on Windows.
Overall, jailbreaking iOS is a great hacking experience with many new options for iOS devices.
Consider jailbreaking, but be wary of voiding warranties.
Rooting Android
Rooting an Android phone involves mostly the same process as jailbreaking, however since
Android OS runs on a plethora of different phones, tablets, and mini-computers, there is a lot of
research involved in determining if your device is rootable. Generally, older devices have been out
longer and are therefore usually rootable since developers and hackers have had the chance to exploit
the technology more. It is extremely important that you figure out if your device is even rootable to
begin with or there is a great chance of bricking it. One tool we will discuss for rooting is “Kingo
Root”, and at the moment you can check the compatibility list (http://www.kingoapp.com/android-
root/devices.htm) to see if your device is specifically mentioned.
Why might you want to root your Android device? Just as with jailbreaking, rooting grants
access to the intricacies of the operating system. Some apps in the Play store require rooted phones
because parts of the app interact with locked settings in the OS. A few cell phone carriers also block
access to features of Android, and hackers like to root their phones to have the freedom to use their
device as it was intended. The default apps installed on Android devices take up too much room, and
they often bog down a device; a rooted Android can remove default apps. Finally, many hackers are
distraught with a Google-based operating system and the amount of data it collects on the user, so the
tech-savvy rooter can “flash” a new operating system that is free from spyware and Google’s prying
eyes.
Once again, make a backup of your device and be prepared to follow directions exactly as to not brick
it. Make doubly sure that you can root your specific device. We’re going to follow the steps for
KingoRoot (https://www.kingoapp.com/), but follow your specific app’s procedure.
4. Follow any on-screen or on-device prompts. Your phone may restart multiple times.
After rooting, there are a few interesting things you can now do. Firstly, you can delete that
obnoxious and space-hogging bloatware that comes preinstalled on Android. Second, you are now free
to use whatever features of the device that you like. For example, newer Galaxy phones have Wi-Fi
hotspot tethering built-in, but some carriers lock the feature behind a price that you must pay monthly.
With a rooted Galaxy, you are free to download apps (Barnacle Wi-Fi Tether on Play Store) that do the
tethering for you and without asking the carrier for permission.
There is no “Cydia” equivalent for Android rooting, because you can download and install .apk
files from anywhere. By just searching on the internet for Android .apk files, you can find whole
websites (https://apkpure.com/region-free-apk-download) dedicated to providing apps for Android.
The only change you need to make to your device to enable installation of .apk files is to enter the
“settings” and tap the “security” tab. Check the box “allow installation of apps from sources other than
the Play Store” and close settings. Now you can download any .apk and install it, most of which you
might not need to be rooted for.
Rooting provides apps with additional control over the operating system, any many apps that you
may have tried to download form the Play Store claim that root is required in order for full
functionality- those apps are usable now.
Emulation on Android devices is somewhat easier due to removable SD cards. If you own an SD
card reader, you can transfer .iso files easily with Windows. Emulating games is a great way to play
older console titles, and here is the easiest way on Android OS.
1. Download the ePSXe app. It may not be available in the Play Store, so search on the
internet for an .apk file, then install it.
2. You will also need PS1 BIOS files. You can rip them from your Playstation console
yourself (http://ngemu.com/threads/psx-bios-dumping-guide.93161/) or find them on the
internet (http://www.emuparadise.me/biosfiles/bios.html). The legality of downloading
BIOS is confusing, so make sure that it is legal to download BIOS instead of ripping
them from your console.
3. Lastly, rip or download the PS1 rom you want to play on your device. See the section
about emulating on iOS for tips on how to rip your own ROMs or obtain other backups
online.
4. Configure ePSXe by pointing it to your BIOS files. Then pick the graphics settings your
device can handle. Navigate to the location of your ROM and launch it to begin
enjoying PS1.
Gaming on an Android is fun, if not difficult due to the onscreen buttons blocking your view of the
games. Android has built-in functionality for wired Xbox controllers that are plugged in via USB port.
If your Android device has a full size USB port, you can just plug the Xbox controller in directly and it
will work. If you have a phone with an OTG (smaller) port, you will need to purchase an OTG to USB
female adapter. With a rooted device the Bluetooth can be taken advantage of fully. The app
“SixaxisPairTool” will pair a PS3 controller for wireless gaming. You’ll just need the app on your
phone, the PC version application on your computer, a PS3 controller, and a cable to connect it to the
computer.
4. Copy the “Bluetooth address” from the phone to the “Current Master” box on the PC
application. Click update.
5. Unplug the PS3 controller and turn it on. It should search for a PS3 to sync to, but the
address that is programmed will lead to your Android device. Enjoy the wireless
gaming!
Deep Android customization comes from the Xposed Framework. After installing
(http://repo.xposed.info/module/de.robv.android.xposed.installer), you are free to customize your
device through “modules” (https://www.androidpit.com/best-xposed-framework-modules) that edit the
tiniest specifics of Android. This is the feature that makes Android much more customizable than iOS.
If you can’t get the device to work perfectly to your liking, you can always flash a new
operating system. This procedure is more dangerous than rooting, and each new OS might not be
compatible with your device. As always, do some internet research to find out if your particular device
is compatible with the operating system you are thinking about flashing. CyanogenMod
(http://www.cyanogenmod.org/) is a popular Android variant developed by the original Android team.
Some devices can even support a Linux distro, making for an extremely portable yet functional device.
We won’t discuss the specifics of flashing here, but you can find plenty of tutorials and guides on the
websites of the custom OS builds that you find.
There are other great rooted apps, such as those that manage specific permissions (PDroid,
Permissions Denied), and apps that remove ads (AdAway), but these apps are commonly taken down
and blocked by federal governments. The only way to get one of these apps is to find it uploaded on an
apk website, or to use a VPN/Proxy to fake your location as another country.
Conclusively, rooting Android gives almost limitless possibilities. You can truly have
complete control over your device after rooting or flashing a new OS. Be very careful when making
modifications, because there is a great chance of voiding warranty or even bricking the technology.
The benefits received, however, are almost too great for hackers and modders to give up.
Risks of Mobile Hacking and Modification
Hacking on or infiltrating another mobile device falls under the same legal dubiousness as PC
and server hacking- some states and federal governments consider hacking illegal, regardless of
whether a phone or computer is involved.
Remember the hacker’s manifesto, though, where a hacker is benevolent because they are only
curious. Some see carriers and phone manufacturers guilty of restricting access to a device, so hackers
attempt to correct the situation through jailbreaking and modding- making the devices truly their own.
An individual probably will never go to jail for simple modifications of their own devices.
Hackers only void their warranties by jailbreaking and rooting. Bricking is a possibility too, but that is
a personal consequence and not a legal one.
Tampering with other people’s devices without permission could be dangerous and illegal,
though, and many courts will consider it an invasion of privacy. Hackers must always protect
themselves with the same strategies laid out in the previous book (VPN, proxies, hiding identity, using
“burner” devices, TOR, etc…).
Overall, so long as hackers are ethical and proceed with benevolent intent, there are not too
many risks involved with experimentation. Large profile crimes will not go unnoticed, however. And
no matter how skillfully a hacker can protect themselves, as seen by the San Bernardino incident, if the
crime is large enough than governments will assign large amounts of resources to oppose the hacker.
Hack with caution and always stay ethical.
Modding Video Game Consoles
Video game consoles have been modded since the beginning of living room entertainment. In
the NES era, some unlicensed companies produced games by flashing their software onto empty
cartridges and bypassing copy-protection. Modding became the norm for subsequent consoles as well,
as many readers might remember tales of PlayStations that could play burned discs, or Wiis that could
read games from SD cards. If the reader has never had the pleasure of seeing a hacked and modded
console in person, I assure them that it is a marvel of hacking knowledge and skill. Just about every
game console can be altered in some way that improves its function, and this chapter will go through
some of the popular modifications and how to perform them. For reference there are two types of
mods- hardmods and softmods. Hardmods are nearly irreversible physical changes to a console such as
those that involve soldering modchips. Software are mods to the software of a console, such as PS2’s
FreeMCBoot memory card hack.
NES
While most people grew up playing a NES, there is no doubt that the console is extremely
difficult to play on modern LCD and LED televisions. Either the new televisions do not have the
needed hookups, or the quality looks awful traveling through antiquated wires and inefficient graphics
chips. Luckily there exists a mod to enable the NES to output video and audio through HDMI- a huge
step up that increases the graphical quality of the old console.
PlayStation
A modchip is a piece of hardware with a clever use. In the original PlayStation 1, a modchip can
be installed that allows you to play burned discs. This means that a hacker can download a ROM of a
game off of the internet, burn it to a CD, and then be able to play it on the original hardware without
trouble and without configuring difficult emulators. Modchips work by injecting code into the console
that fools it into thinking that the inserted disc has successfully passed disc copy protection. Thus a
modchip needs to be soldered to the motherboard. On the PlayStation it is a fairly easy process.
1. You will need a modchip corresponding to your PS1 model number. http://www.mod-
chip.net/8wire.htm contains the most popular modchip- make sure your SCPH matches
the compatible models. (We will be using the 8 wire mod.)
2. Disassemble the PS1, take out all the screws, remove the CD laser, remove everything
and get the bare motherboard onto your soldering station. Take pictures of the
deconstruction process to remind yourself how to put everything back together later.
1. Place a piece of tape over the sensor so discs can spin while the tray is open. While
opening and closing the tray you can see the button that the lid pushes to tell the console
it is closed. Tape it up so the console is always “closed”.
2. Put a legitimate disc into the tray and start the console.
3. The disc will spin fast, and then slow down to half speed. While it is halved, quickly
swap the legitimate disc for the burned copy. The process is quick and must be done in
less than a second.
4. The burned disc will spin at full speed and then slow down to half to scan for copy
protection. As soon as it slows, swap it back for the real PS1 disc.
5. Watch the screen, and as soon as it goes black switch back again to the burned disc and
close the tray. The fake disc will now play.
Both of these methods are how mods were done for years, but a new product entered the market
which simplifies PS1 hacking. The PSIO (http://ps-io.com/) is a piece of hardware that allows the PS1
to read games from an SD card. For a fee the creator will install the handy device onto your
PlayStation and simplify playing bootleg and backup games forevermore.
PS2
The PlayStation 2 remained a popular console for years after the last games were produced.
Although there exist hardware mods and complicated procedures, the easiest way to hack the PS2
console is to buy a memory card. FreeMcBoot (FMCB) is a software exploit that hijacks the “fat” PS2
and allows custom software to execute through a softmod. You can simply buy a FMCB memory card
online for 10 dollars, or you can create one yourself. You’ll need a fat PS2, a copy of AR Max EVO, a
blank memory card, and a USB flash drive.
3. Navigate to the media player and access “next item” to load FREE_MCBOOT.ELF on
the flash drive. Press play.
4. Follow the instructions and FreeMCBoot will install on the memory card.
5.
Now FreeMCBoot will have tons of great software preinstalled- all you have to do start the PS2
with the modded memory card inserted and FreeMCBoot will temporary softmod your console.
Playing backup games is fairly easy as well.
1. Have the .iso file of the game you want to play on the computer.
2. Download the ESR disc patcher (www.psx-scene.com/forums/showthread.php?
t=58441), run it and patch the .iso.
3. Burn a blank DVD with the modified .iso. ImgBurn is a great program for this.
4. Put the disc into the PS2, start the PS2, FreeMCBoot will load. Navigate to the ESR
utility on the menu. Launch it and the game will start.
PS3
The Playstsation 3 started out with functionality that allowed operating systems such as Linux
to be installed- turning a simple game console into a home computer. Hackers exploited “OtherOS”
and “jailbroke” the PS3. A modded device is capable of playing backup/downloaded games and
“homebrew” (indie) software. There are conditions that restrict the number of PS3 consoles that can be
modded though. Only PS3s with a firmware version 3.55 and below can be modified; you can check
this through “Settings”, “System”, and then “System Information”. If your PS3 happens to be updated
beyond this point there is not much that you can do to downgrade, and 3.55 PS3s are very expensive on
eBay. We won’t explain the downgrade process, but do research on the E3 Flasher to bring your
version number to 3.55.
If your version number is below 3.55 the software must be updated to the correct version. DO
NOT let the PS3 do this automatically, or it will update past 3.55 and ruin our chances of modding.
Instead you will need to download the 3.55 update
(http://www.mediafire.com/download/dp6uhz4d15m3dll/ofw+3.55.rar, but the link may change), create
a folder on a blank flash drive called PS3. Inside that folder create an UPDATE folder. Extract the
3.55 update into the UPDATE folder and plug it into your PS3. Start PS3 recovery mode by holding
down the power button until you hear 3 total beeps. Recovery mode will start, and you will need to
plug in a controller to interact with the menu. Choose “update”, follow onscreen directions, and the
PS3 will update from the USB drive. You’ve now upgraded to 3.55.
To install custom firmware on your 3.55 PlayStation 3, follow the process below.
2. Create a PS3 folder on the drive, then an UPDATE file within it.
4. Put the update files onto the flash drive, boot into recovery mode, and install
PS3UPDAT.PUP. You now have custom firmware.
Playing games on a custom PS3 is a straightforward process using a tool called MultiMAN. The
application runs on the custom firmware and allows backing up and playing games. First, obtain a
copy of MultiMAN version 4.05 and up
(http://www.mediafire.com/download/16dbcwn51gtzu47/multiMAN_ver_04.78.02_STEALTH_%2820160328%29.zip
link may change), as these versions support the CFW that we installed. Extract it and put the files on a
USB drive, plug it in and start the modded PS3. In the “Game” section, select “Install Packages Files”,
then install the MultiMAN pkg file. The application will be installed.
One great feature of MultiMAN is making backups of discs right on the PS3. Rent a game or
borrow one from a friend, start MultiMAN, put a disc in the system, and the application will show you
the game. Access the options, and choose to “copy”. The game will be copied to the internal HDD and
be playable through MultiMAN without the disc. If you have downloaded copies of games, then
MultiMAN will also recognize them when they are plugged in via external hard drive, and you will be
able to play them.
Overall there are limitless possibilities on PlayStation 3 custom firmware, and this book can never
hope to document them all. Be careful when flashing, and always triple check the procedures and
research. http://www.ps3hax.net/archive/index.php/t-18606.html contains a great guide for installing
custom firmware and playing backup games; check the website before following through with
installing CFW. There are a few other things to worry about, such as connecting to the internet on a
CFW PS3. Sony servers collect information on internet connected PS3s, and they could have the
ability to remotely disable a PS3 that they detect running CFW. All of that aside, enjoy the hacking
process and congratulate yourself for attempting something particularly difficult and dangerous.
Xbox
The original Xbox is a popular console to hack because of the easy method and multiple features
gained from modification. You will need a flash drive, the Xplorer360 program (http://www.xbox-
hq.com/html/article2895.html), the hack files (http://www.1337upload.net/files/SID.zip, link may
change- if it does search for XBOX softmod files), a controller with a USB port, and a game that can
exploit. Splinter Cell works with the above files. Here is the softmod guide.
2. Plug USB into PC, extract the downloaded softmod files, and open Xplorer360.
3. Click “drive”, “open”, “hard drive or memory card”. Partition 0 will be the USB.
4. Drag the extracted softmod files into the 360 program and they will be put onto the USB.
5. Plug the USB into the Xbox and move the files over onto the internal HDD.
6. Start the game and load the save data (the softmod). Follow the onscreen prompts to
hack the Xbox.
With the softmodded Xbox you can do plenty of neat media center things, such as play video and
audio, or even use emulators. Check online for all possibilities.
Xbox 360
Xboxes with a dashboard before 7371 (kernel 2.0.7371.0) are hackable, those with a later version must
use the “RGH” method. Exploited 360s can run backup games and homebrew applications. The
process (known as JTAG) is too difficult and varied to cover completely here, so we’ll only go over a
brief overview. The motherboard that your 360 has determines which process to follow, so pay close
attention.
1. Assemble necessary parts (1 DB-25 connector, 1 DB-25 wire, a 1n4148 diode, 3 330
ohm resistors (xenon motherboards)).
3. Plug DB-25 connector into computer and dump the “nand” using software in the link.
4. Test CB in nand to ensure specific model is exploitable.
5. Select the correct file for flashing and flash the motherboard. Copy the CPU key after
booting back up. Your 360 will be modded but thoroughly useless on its own. Use
separate programs such as X360GameHack to play backup and downloaded games.
Here is a great video of the 360 hacking process. Be careful, because this 360 and the PS3 hack are
very dangerous and could brick the consoles.
What to do with a Bricked Device
Sometimes a modification fails. Even though a device may seem lost, they are not always totally
bricked. Once you’ve given up on a device and are ready to throw it in the trash, consider the
following options.
Try flashing again. Maybe the process will complete fully this time and make the device
usable again.
If a jailbreak failed, boot into recovery mode and try restoring from a computer with
iTunes.
Research the problem and exactly where it went wrong. Maybe other people have had the
same situation and resolved it.
If the device is under warranty you can make a plausible excuse for why it isn’t working.
(iPhone got overheated so now it doesn’t boot!)
Scrap the device for parts. Just because one part is broken doesn’t mean everything else
is.
If you don’t have a console or are too nervous to mod them, you could always use your PC to
play console games. Emulators on PC are great for any hacker with a strong computer. Computers and
their high powered graphics processing capabilities open up emulation of more modern systems, such
as PlayStation 2, Dreamcast, or even something as new as the Xbox 360. Refer to the table below for a
few of the best PC emulator programs that you can download.
Some of the above emulators might be depreciated or gone when you read this, but at the
current date these are the best programs that you can download for Windows in terms of emulation.
Certainly the more modern consoles, such as Xbox 360, require the equivalent of a supercomputer to
run well; older consoles like the N64 are emulated almost perfectly on more basic hardware.
Conclusion
The world of mobile hacking, jailbreaking, rooting, console modding, and emulation is a
peculiar one. Customization and freedom are available to those that can achieve it, but hacking is
always a dangerous task with serious consequences. Only warranties and contracts are at stake with
personal hacking, but hacking others can catch the attention of authorities.
Always remember to hack ethically, or at least stay hidden and protect yourself for more
fiendish actions. Ultimately though, aren’t mobile carriers and console makers the despicable ones for
locking away true ownership of the devices that we buy? Thank you for purchasing and reading this
book. Be sure to leave feedback if you’d like to see more hacking guides.
Hacking University: Junior Edition. Learn Python
Computer Programming from Scratch
Introduction
Related Software
Online Resources
History of Python
Benefits of Python
Hello World
Programming Concepts
Variables
Variable Types
Input
String Formatting
Example Program 1
Decision Structures
Conditional Operators
Example Program 2
Loops
Example Program 3
Example Program 4
Functions
Example Program 5
Classes
Special Methods
Example Program 6
Inheritance
Example Program 7
Modules
Example Program 8
Common Errors
Conclusion
Related Titles
Copyright 2016 by Isaac D. Cody - All rights reserved.
This document is geared towards providing exact and reliable information in regards to the topic and
issue covered. The publication is sold with the idea that the publisher is not required to render
accounting, officially permitted, or otherwise, qualified services. If advice is necessary, legal or
professional, a practiced individual in the profession should be ordered.
- From a Declaration of Principles which was accepted and approved equally by a Committee of the
American Bar Association and a Committee of Publishers and Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic
means or in printed format. Recording of this publication is strictly prohibited and any storage of this
document is not allowed unless with written permission from the publisher. All rights reserved.
The information provided herein is stated to be truthful and consistent, in that any liability, in terms of
inattention or otherwise, by any usage or abuse of any policies, processes, or directions contained
within is the solitary and utter responsibility of the recipient reader. Under no circumstances will any
legal responsibility or blame be held against the publisher for any reparation, damages, or monetary
loss due to the information herein, either directly or indirectly.
The information herein is offered for informational purposes solely, and is universal as so. The
presentation of the information is without contract or any type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of the trademark is without
permission or backing by the trademark owner. All trademarks and brands within this book are for
clarifying purposes only and are the owned by the owners themselves, not affiliated with this
document.
Disclaimer
All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in any
form or by any means, including photocopying, recording, or other electronic or mechanical methods,
without the prior written permission of the publisher, except in the case of brief quotations embodied in
critical reviews and certain other noncommercial uses permitted by copyright law.
Introduction
For enhancing your Python skill, use an IDE. If you have not
downloaded it yet, Atom is highly recommended for Python programming.
Atom is customizable, in that you can install add-ons at any time to make
programming easier. “autocomplete-python” is one such add-on that can
guess what you are typing and automatically fill in the rest of the command.
VI and Emacs are two other popular text editors for programmers.
Both are considered highly advanced and optimized for writing code, but a
bit of a “flame war” exists between fans of both softwares. For the Linux
Python programmer, investigate the two text editors and test whether it helps
with Python workflow.
After you have finished a particularly useful Python program and wish
to distribute it to users, you have to keep in mind that many of them do not
have Python installed and will likely not want to install it just to run your
program. PyInstaller (http://www.pyinstaller.org/) is a piece of software that
builds your Python script and the needed modules into an .exe file that does
not need Python to run. It is a handy software should distribute your
applications.
Online Resources
For obtaining online help related to Python, you can always check the
online documentation (https://www.python.org/doc/). The documentation
contains examples and manual pages for every function built-in to Python
and its included modules.
For times when programming code just does not work, you can always
turn to search engines to resolve your problem. Typing in the error text into
Google can turn up other programmers who also had the same problem and
posted online. If the problem cannot be fixed by observing other code,
websites such as Stack Overflow (http://stackoverflow.com/) are notoriously
helpful in resolving code issues. Make an account their and post your
problem politely and somebody will probably help you out.
Finally, there are websites that offer tutorials online about how to learn
intermediate and advanced Python programming.
http://www.learnpython.org/ is one particularly exemplary one, but the sheer
amount comes from the fact that Python is highly used and well understood.
For any time Python help is needed, a quick internet search may solve your
curiosities.
The Job Market
The term “scripting language” refers to the fact that written code is not
actually compiled, but rather it is interpreted by an application. Normally this
means that scripting languages are not nearly as powerful as actual
programming languages. For Python, though, the opposite is true- the
language remains one of the most powerful available for web servers and
desktop clients. Development of Python continued throughout the 1990’s
until version 2 was released in 2000. The interpreter behind Python became
intricate enough that current versions of Python are almost indistinguishable
from lower level programming languages.
When first starting out learning how to program, the huge amount of
options, information, and advice can be truly intimidating. Some experts
claim that the difficult but time-honored C language is the best start, but other
professionals say starting on an easier language such as Java or Python will
give the learner a chance to actually absorb key concepts. Python is
recommended for this exact reason- programming will not be as foreign and
confusing by starting with a straightforward scripting language.
Large companies such as Google, Disney, NASA, and Yahoo all use
Python for their own programs; having Python knowledge could potentially
land a programmer a job working at a high-profile organization. Moreover,
because Python is continuously developed today with new features always
being added, interest in the language will continuously increase with time.
More companies will discover that Python is an exceedingly useful
programming language, so learning it now will prepare you for the future.
Benefits of Python
In addition to being easy and fast, Python also has various other
benefits. Python is very portable, meaning that Python code can run on a
variety of different operating systems. Windows, Mac OSX and Linux
distributions are all supported directly, and code written on one platform can
be used on all of them.
Now that there is a development environment set up, you can continue
onwards to begin writing your first Python program.
Hello World
Next, we save the file. In IDLE (and most IDEs such as Atom) one
must go through “file” and click “save as”. In Nano ctrl+x must be pressed.
Name the file with a “.py” extension and save it in an easily accessible
directory- your desktop is perfectly fine. For this demonstration we will
name the file ”test.py”.
If the above programming code was copied exactly, the output “Hello,
World!” will be seen. The program will run and then exit back to
terminal/prompt. Not entirely glamourous, but a worthy first step into
learning Python.
Programming Concepts
Anything can be put within the quotations of the print function and it
will be written to the console. Since Python starts at the beginning of a script
and reads lines individually, multiple print functions can be placed one after
another like so:
print (“Notice how each print command puts the text on a new line!”)
After saving and running the file, all three functions will print their
respective parameters. As mentioned previously, the quotations explain that
text will be displayed. By forgoing quotations, numbers can be displayed
instead.
print (42)
Python starts at the beginning of the script file and works its way down
one line at a time until no more lines are found, in which case the program
exits back to prompt or terminal.
Variables
lucky_number = 7
And then we can use the print function to view the variable we created.
print (lucky_number)
Because Python starts at the top of a program and works downwards,
the above lines need to be in the correct order. If lucky_number is not first
created, then print() will return an error for attempting to call a variable that
does not yet exist.
Variables can contain values of multiple types. Our first variable was
assigned a numerical value, but Python has methods for handling values of
different types as well.
secret_message = “rosebud”
print (secret_message)
first_num = 2
result = 3 + first_num
print (result)
first_num = 3
result = 3 + first_num
print (result)
Both integers and floats can easily perform calculations using the above
operators. Note, though, that integers will generally return integer answers
(whole numbers) while floats will always return an answer with a decimal
point. Python can usually transform an integer into a float when it is needed,
but good programming form comes from choosing the correct data type at the
appropriate time. For example, see how floats are used in the program
below:
first_number = 5.0
second_number = 3.0
result = first_number / second_number
print (result)
first_number = 5.0
second_number = 3.0
name = “Bill”
print (name)
my_string = “Hello,”
my_string2 = “World! ”
The output would be “Hello, World!” for the first print(), and “World!
World! World!” for the second print(). The addition operator combines two
strings together into one massive string, and the multiplication operator
repeats a string the specified number of times.
Input
When a program reaches this line, it will display the text specified and
wait for user input. Whatever is input will be assigned to favorite_number,
which can be called just as any other variable.
There are a lot of new nuances going on in this program. For example,
int() is used to convert the input into an integer. Notice how int() surrounds
the entire input() function, which happens because input() must be passed as
the entire parameter of int(). Next, the print statement is printing multiple
bits of output, and the equation “favorite_number + 2” is evaluated before
being printed.
Using int() will always return an integer answer, but float() could have
been used to extract a decimal answer instead. The int() function works
essentially by transforming the string “3” into the number 3. Definitely
remember to include it whenever getting numerical input.
String Formatting
Being able to display strings with print() is useful, but sometimes our
programs require us to display variables within them. To actually insert a
variable into a string without first editing it or combining multiple variables,
we can use a “string formatter”. The format() function can be included
within a print() statement to do positional formatting of variables.
dog_name = “Rex”
When you run the above code, it automatically replaced the brackets
{} with the supplied variable. The format() is placed directly after the string
it will be editing, and before the closing parenthesis. So when the code is
run, the console outputs “My dog’s name is Rex…”. Without using format(),
we would have had to use a multi-line complicated print setup. But
format()’s greatest use comes from situations with multiple variables.
dog_name = “Rex”
dog_age = 12
print ("{0} is {1} years old. They have a {3} GPA, probably because they
have {2} pets.".format(user_name, user_age, user_pets, user_GPA))
Depending upon the medium in which you are reading this publication,
some of the above lines may have word-wrapped to multiple lines. This is
not how you should be typing it into a text editor though, as the print() line is
one single command. Furthermore, copy and pasting from this document
may introduce extra characters that Python does not understand. Therefore
the correct way to input project 1’s code is by typing it out yourself.
Homework program:
Now that the basics of Python 3 are explained, we can begin to offer
truly interactive programs by implementing decision structures into our code.
Decision structures are pieces of code (called conditional statements) that
evaluate an expression and branch the program down differing paths based on
the outcome. Observe the following example:
if (user_input == 2):
print ("Correct!")
else:
print ("Incorrect...")
First we obtain input from the user. We test user_input against 2 (the
correct answer). If the conditional statement turns out true, then the program
will print “Correct!”. However, if the user provides the wrong answer
Python will return “Incorrect...”. There is a lot of new concepts going on
here, so we will break it down line by line.
If the user had input the correct answer of 2 instead, the if statement
would evaluate to true and the console would print “Correct”. In that
situation, the else statement would not run at all. Focus once again on the
indented code and understand that those lines are indented because they are
part of the “if” and “else” code blocks. Also realize that only one statement
from a decision structure can ever run in a program, so if “else” runs, that
means “if” did not run. Likewise a program that has “if” activated will not
run the code block under “else”. Conditional statements are not limited to
single lines of code, as you can see below.
if (user_input == "Python"):
print ("Correct!")
else:
print ("Incorrect...")
Double equal signs (==) are only one of the many operators that can be
used to create a conditional expression. This small list shows other operators
in Python.
== - Equal to
For situations that require more than just two potential outcomes, the
keyword “elif” can be used.
else:
Elif is a keyword that can be used to split the decision making process
into multiple branching paths. Between if and else statements, any number of
elif conditionals can be used. Also, another new keyword is used above-
“and”. Our first comparison checks to see if age is less than or equal to 18
AND greater than 0. Therefore that conditional will only evaluate to true if
the age value satisfies both requirements. Pretend the user input 75. The first
statement evaluates, and 75 is indeed greater than 0, but it is not also less than
18, so that statement is skipped. Then, the first elif is evaluated. Age is not
greater than 80, so that statement is skipped as well. Thirdly, age is definitely
between 18 and 80, so the console prints “Ah, a good age to learn” and then
skips the else statement altogether.
Remembering that only one statement in a decision “tree” can ever run,
we can see that any elif that activates essentially runs its code block and then
breaks from the decision structure. Else is used as a “catch-all” type
expression in our above program. Any invalid input, such as “-1” would be
picked up by else and displayed as such. Good programming form comes
from catching potential user errors like this, and as an aspiring programmer
you should always be expecting the user to incorrectly input values whenever
the chance arises.
print("Python Quiz!")
answered = 0
correct = 0
print()
print("A: 1, B: 2, C: 3")
print()
correct += 1
print ("Correct")
else:
print ("Incorrect")
print()
print("How many 'else' statements can be in a decision tree?")
answered += 1
print()
correct += 1
print ("Correct")
else:
print ("Incorrect")
print()
answered += 1
print()
if (user_answer == "B" or user_answer == "b"):
correct += 1
print ("Correct")
else:
print ("Incorrect")
print()
if (correct == 3):
print ("Congratulations! Good score.")
else:
print ("Go back and read over the section again, I'm sure you'll get it.")
Homework program:
answer = 0
print ("Correct!")
answer = 0
if (answer != 2):
print ("Incorrect...")
print ("Correct!")
Another common loop is the “for” loop. For is different from while in
that a for loop runs through a range of numbers or a set of values instead of
checking a conditional.
print (user_variable)
For takes the specified variable “user_variable” and uses the supplied
range. The variable will be initialized at 1, and it will be iterated every time
the function loops. By observing the output we can see how this works.
1
2
3
4
print (user_variable)
For example, only “range” is left out here, but the output is very
different.
1
5
Python runs the loop with the first value, 1, and then runs it with the
second value, 5. We will learn that using for loops this way is especially
useful for lists, dictionaries, and tuples.
print("Adding simulator")
line = "a"
total = 0
line = input("")
if (line == ""):
break
total += int(line)
Homework program:
Lists are another data type beneficial to talk about. A list is an array of
values that are grouped together into a single variable. The single variable
can then be used to call upon any of the “sub variables” it contains. They are
mostly used for organization and grouping purposes, and also to keep related
variables in a similar place. List variables are created by initializing them.
state = "Texas"
Entry 0 1 2 3
number:
Data value: 8 “West state “A”
Elementary”
A list could be initially declared with 3 entries, and it would have the
range 0-2. The number of entries is nearly infinite, and it is only limited by
the computer’s memory and the amount of variables the programmer fills it
with.
state = "Texas"
jack_info = [8, "West Elementary", state, "A"]
jack_info[0] = 9
jack_info.append(22)
The new additions to the program change the list ever so slightly to
now have a new set of values.
Entry 0 1 2 3 4
number:
Data value: 9 “West state “A” 22
Elementary”
Entry 0 1 2 3 4 5 6 7 …
Character H e l l o , W …
And likewise, individual entries can be displayed from the string list.
Moving onwards, tuples are another data type within Python. They are
declared by using parentheses instead of square brackets. Tuples are actually
static lists, or lists that cannot be edited. They are used when the programmer
needs to ensure a range of data cannot change.
jim_grades = (99, 87, 100, 99, 77)
print (jim_grades[2])
print (albums)
The humorous example above is a simple dictionary used to store the
number of albums a person has. At the beginning the dictionary has a set
number of albums for each band, but the second line has the collector gaining
a new Milkduds album. That line also uses a new code shortcut. Whenever
“+=” is used, the code is actually expanded to be “albums["Milkduds"] =
albums["Milkduds"] + 1”, but much time and space is saved in the program
by using the shorthand. Third line has the collector realizing they only had 2
7750’s albums, so the command changes the value of the entry altogether.
Next update() is introduced. It shows how an entirely new entry can be
added to the dictionary. Sadly, though, Harold Gene is deleted from the
dictionary because the collector sold away the album. Finally, printing the
entire dictionary can be done by not specifying any entry.
number_grades = 0
grade_list = []
total = 0
print()
number_grades += 1
grade_list.append(grade)
Devise code for more math functions, such as medians and modes.
Functions
Every function used thus far has been built-in to Python and
programmed by Python’s developers. Functions are actually code shortcuts,
as functions are condensed versions of code that take data as parameters, run
longer blocks of code behind the scenes, and then return a result. The use of
functions is to save time and code when doing commonly repeated tasks.
Python retains the ability for programmers to write their own functions, and
they are done like so:
def happy(name):
happy("Dana")
intdiv(first, second)
First, the UDF is declared. This code does not run automatically
because it has not yet been called. The program actually starts on the fifth
line. The variable “first” is declared within the main program’s scope based
on the user’s input. So too is the variable “second”. The UDF “intdiv” is
invoked with first and second as the two parameters. The variables are
passed as parameters so they can be transferred into the UDF. First and
second are not actually leaving their scope, though, because the UDF uses the
variables num_one and num_two to perform calculations.
Variables can be passed back from a UDF by using the return
keyword.
orig_num = base
return base
So when we call the function like above, the answer (base) is given
back as the result and assigned to the variable “answer”.
def cm_to_inch(cm):
inch = cm * 0.39
return inch
def inch_to_cm(inch):
cm = inch * 2.54
return cm
print("Inch/cm converter")
print("1: Convert cm to inch")
if (choice == 1):
if (choice == 2):
Homework program:
Classes are a feature of Python that bring it more in line with some of
the more difficult programming languages. They are essentially “programs
within programs” because of how many features you can put into one.
Moreover, it is good programming form to use classes for organization.
Object-oriented languages such as Python occasionally show their object
roots through concepts like these, whereas objects contain attributes in the
form “object.attribute”. See the example below to understand.
class student:
self.name = name
self.grade = grade
self.gpa = 0.0
The class that we create is called “student”, and student contains its
own variables. Classes give us a way to organize objects and give them
personal attributes. So instead of having student1_name, student1_grade,
student2_grade, etc… as different variables, they can be consolidated by
belonging to a class. Within a program, the class declaration goes at the very
top. Just like a UDF, it does not actually run in the main program until
called.
Our newly declared “student” class is used to create the student1 object
with the attributes “Tim” and “Freshman”. This would have previously taken
two lines, but it is condensed considerably with classes. Classes
compartmentalize the related variables of the object so that each “student”
declared has the 3 properties “name”, “grade”, and “gpa”. The second line of
our class declaration contains __init__, which is a “method” (user defined
function) that runs when an object in the student class is created. Init’s
parameters are the ones required when creating that object. Self is not
actually a parameter, it just refers to “student”, but “name” and “grade” are
required, which is why we included them when creating “student1”.
Attributes of student1 can be called like so:
print (student1.name)
Which would simply print “Tim”. We did not declare the GPA
variable during the student1 initialization, so we can do that with an
assignment statement.
student1.gpa = 4.0
student1.grade = “Sophomore”
self.name = name
self.grade = grade
self.gpa = 0.0
def record(self):
print (student3.record())
The __init__ stays the same, but we add a UDF definition with the
name “record”. It passes the parameter self (because it has to refer to the
class) and returns a formatted string. In our actual main program student3 is
created. Finally, we call the UDF with student3.record() (object.function). It
returns our formatted string, and therefore it is printed out by print().
Special Methods
Other special methods exist, and they are called on different events.
class student:
self.name = name
self.grade = grade
self.gpa = 0.0
def __str__(self):
return "{}".format(self.name)
def record(self):
print (student4)
total_foods = 0
self.name = name
self.calories = 0
self.foodgroup = ""
food.total_foods += 1
def __del__(self):
food.total_foods -= 1
def __str__(self):
return "{}".format(self.name)
def get_total():
return food.total_foods
def record(self):
food1.foodgroup = "Vegetables"
food2.calories = 100
food2.foodgroup = "Grains"
print (food.get_total())
del food2
print (food.get_total())
As the program creates a food, 1 is added to total_foods. Then, a food
object is deleted so 1 is taken away. The console prints 2, then 1 to show
how our UDF can be called to check the class variable. Keeping track of the
number of something is a common use for class variables, but they are highly
useful for other situations as well.
Example Program 6 – project6.py
class house:
self.name = name
self.bedrooms = bedrooms
self.bathrooms = bathrooms
self.cost = cost
x += 1 #wait a while
print("Sold!")
del house1
Homework program:
In your more robust and expansive programs, you might use multiple
related classes. As an example, think of the program where you must
categorize devices on a network. Each device type (desktop, laptop, phone,
etc…) will have its own class, but you will ultimately be repeating commonly
used attributes. Both desktops and laptops will have names, departments, and
IP addresses, but they will also have a few distinct variables specific to them
such as Wi-Fi for the laptops and graphics cards for the desktop.
class device:
total_devices = 0
self.owner = owner
device.total_devices += 1
def __del__(self):
device.total_devices -= 1
def __str__(self):
return "{}".format(self.name)
def get_total():
return device.total_devices
class laptop(device):
def __str__(self):
class cellular(device):
self.connection = connection
self.BYOD = BYOD
def __str__(self):
print (device1)
print (device2)
print (device.get_total())
Both children contain a __str__ method, even though the parent class
also has one. Through a process called overwriting, if a special method is
called that exists in both the parent and child, than only the child method will
run. In the absence of a called method in a child, the parent will runs its
method instead. This is why referencing a laptop object as a string will
display laptop information, but deleting a laptop object will fall back to the
parent and run its destructor method instead.
Understanding how inheritance works can provide your applications
with unprecedented organization and composition. Most higher-level and
advanced programs take advantage of classes and their properties to quickly
devise a framework for many applications such as database tools, so learning
them would undoubtedly improve your Python skills.
Example Program 7 – project7.py
class house:
self.name = name
self.bedrooms = bedrooms
self.bathrooms = bathrooms
self.cost = 0
class apartment(house):
self.montly_payment = 0
forsale1.montly_payment = 250
Homework program:
import math
import math
print (math.sin(3))
answer = math.sqrt(16)
print (answer)
In particular, sqrt(), sin(), and gcd() are three examples you can notice
above. Every module has a defined purpose, and math’s is to provide
advanced mathematical functions. Here is a list of the most important ones.
math.e – 2.71828
Those needing to use complicated functions such as the ones above only
need to “import math” at the top of the program.
current_time = datetime.datetime.now()
print (current_time.hour)
print (current_time.minute)
print (current_time.second)
year
month
day
Or os, a module that unlocks operating system functions for altering files.
Here is a small program for creating a new folder and then making it the
active directory.
import os
And other highly useful modules, such as random, statistics, and pip exist
that can give new features to your Python applications that were not
previously possible. Python also has support for downloading and using
user-created modules, but that is an advanced concept not covered here.
Example Program 8 – project8.py
import random
rng = random.randrange(1, 7)
if (rng == 1):
After every comparison statement and loop (such as if, elif, else, for,
while, def, and class) there is a colon (:). This colon denotes that the next
line should be indented, and thus all indented lines will fall within the
function’s scope. Failure to place a colon returns a syntax error.
Beginners will often try to use functions that are not in Python by
default without including the correct module. Trying to call an advanced
math function, or editing a file directory is not possible with regular Python.
Always place the import commands for modules you will use at the top of the
program, or the application will simply not run.
Isaac D. Cody is a proud, savvy, and ethical hacker from New York City.
After receiving a Bachelors of Science at Syracuse University, Isaac now
works for a mid-size Informational Technology Firm in the heart of NYC. He
aspires to work for the United States government as a security hacker, but
also loves teaching others about the future of technology. Isaac firmly
believes that the future will heavily rely computer "geeks" for both security
and the successes of companies and future jobs alike. In his spare time, he
loves to analyze and scrutinize everything about the game of basketball.