Friday, March 31, 2017

An introduction to Python on Android

There are many reasons that you might want to start Android development. Building an app that will make you rich and change the world is only one motivation; others include learning to code, building tools that you can use yourself or even just having fun and impressing others. Programming is a fantastic skill to learn and with Android being so open and accessible, it's a great place to start.

Python is a particularly simple and elegant coding language that is designed with the beginner in mind.

The problem is that learning to code with Android isn't quite pick-up-and-play. Before you can even run a simple 'Hello World' program, you need to download Android Studio, the Android SDK and the Java JDK. You need to set paths, figure out how to create APKs and add certain permissions on your phone. Even once all that is ready, you need to get to grips with things like views before you can actually show anything on the screen.

That's why learning to code with Python might offer an appealing alternative for some. Python is a particularly simple and elegant coding language that is designed with the beginner in mind. What's more, is that you can start building scripts and testing them on your Android device almost immediately!

 

In short, this is one of the fastest ways to get up and running with some basic coding on Android. What's more, is that once you start playing around with some of the more advanced features, you can use it to pull off some awesome tricks for automating your phone and more. And yes, with a little playing around you can even build full APKs.

What is Python?

Python is a relatively new programming language that was created by Guido van Rossum and released in 1991. Its ruling design philosophy is 'readability': in other words, code should be easy to follow even for a non-coder. It utilizes a lot of white space and makes efficient use of commands – meaning it's possible to get more done with fewer lines of code.

Python is also the main programming language used with the Raspberry Pi, meaning that you can make a wide range of exciting gadgets with it.

This simplicity and elegance makes Python a great choice for new programmers but it also has a lot else going for it. For starters, there are interpreters available on multiple operating systems, meaning that you can run scripts on Windows, Mac, Linux and Android. Python is also one of the main programming language used with the Raspberry Pi, meaning that you can make a wide range of exciting gadgets with it and making it an ideal language to teach kids. It's also great for web development via the Django Project. Pinterest was written using Django!

Getting started

So, with that said, how do we go about getting started with Python? If you were learning Python for PC development, then you would begin by downloading the latest version of either Python 2 or Python 3 and then an IDE (integrated development environment) such as PyCharm. You can get Python for Windows here.

But PC development is not what we're interested in here. To get started with Python on an Android device, you'll want to use QPython for now, or QPython3. QPython is really a script engine for Python 2, while QPython3 runs Python 3.

Python is an ongoing project that is constantly undergoing improvements. In order to ensure your code runs as smoothly as possible, you need to get the latest version of Python. At the time of writing, that is Python 3.6.1.

The slight complication is that the jump from Python version 2 to Python version 3 was so significant, that it broke backwards compatibility. That meant that code written in Python 2 would not work for Python 3 without some tweaks. That's not so much of an issue, but what is a little irksome is that some popular libraries were also broken in the upgrade. A library as you may know is a collection of code that other developers can use in their own programs and that therefore shortens development time and enables additional functionality.

If you're learning Python for the first time then, it makes sense to start with Python 3 and therefore to have the most up-to-date knowledge. In future though, just know that you may need to revert to Python 2 so that you can support certain libraries.

The main library we'll be using later on is 'Kivy' and fortunately, this supports Python 3.

Writing some simple code with variables and inputs

Once you've downloaded and installed QPython3 (which is free), you'll have your own little development environment on which to start programming. You'll be able to load scripts from here and that will be nearly as useful as creating your own native apps. That is to say that if you want to create a basic tool to perform some maths, to test you on a subject, or to store and retrieve data… well then you can do!

And we're going to learn how to do that sort of stuff right here. First things first, let's build our 'hello world' app.

To do this, open up QPython3 and then choose 'Editor'. As you might guess, this is the editor where you can type out your code or edit other scripts. Personally, I can't be dealing with this kind of development unless I have a bluetooth keyboard and mouse to work with but that is optional!

Now just type:

  print("Hello World")   

Then save the script, remembering to add the extension '.py'. Save by clicking the floppy disk icon at the bottom. Note that the word 'print' must be lower case.

Click 'Play' (the arrow icon) and you should see the words 'Hello World' appear on the screen along with a whole lot of other jargon. This is the 'console' and it's where your scripts will run until we start adding graphical features.

 

Let's move on to variables. Variables are words that represent other data – that act like 'containers'. So, the letter 'x' could represent a number like 2 or 3, or the word 'name' could represent a name like 'Adam'. Variables that represent whole numbers are called integers, while variables that represent names are called 'strings'.

The good news is that you don't need to 'define' variables in Python. That is to say that you can simply say that one word is equal to another word, or that it is equal to a letter. For example, if we use the following code:

  Name = "Adam"  print("Hello " + Name)  

We now have a code that creates a variable called name and sets it as 'Adam', before welcoming the user by their name. We could just have easily have said:

  Number=7  print("The number is " + Number)  

The real point of variables is that it allows us to dynamically change elements of our code. So, we can now write Number = Number + 1 to increase its value. Likewise, we can create a little app that responds to the user like so:

  Name = input("What is your name please?")  print("Why hello " + Name)  

As you can see, the command input allows us to get data from the user and in this case, we're using their input to define our Name variable. Remember: variables are case sensitive! It makes sense to use capitals for variables in Python, seeing as the commands are always written in lower case. It helps them to stand out!

Using just these few bits of code, we can already do some fun things. Here's a little script that will tell you how old you are in stark detail…

  Age = int(input("How old are you?"))  print("In ", 100 – Age, " years, you will be 100! That's around ", (100 -Age) * 365, " days!")  

This will tell you how many days until you are 100 and to do that, we've just used a little maths ('operators'). In computer code an '*' symbol represents multiplication and  '/' is division. The only other new thing here is the word int which tells Python that we're accepting inputs as integers. I'm also using commas now to append my strings instead of '+' because we're working with integers.

Loops and if statements

A loop does exactly what it sounds like it should: it loops around and around until a certain set of conditions are satisfied. Add the following lines to the last script we wrote:

  Count = 0  print("Let's count your remaining years…")    while Count < Age:   Count = Count + 1   print("That's ", Count, " years, ", Age – Count, " to go!")    print("And we're done!)  

Remember how we said that Python was 'readable'? This is readily on show in this example: the command while literally means that the code that follows will run while the following statement is true. Of course it is also up to us to maintain this readability by using only logical names for our variables that will make sense when read.

In this case, that statement is that Count < Age: Count is equal to less than Age. Notice how the next two lines are indented, which means that they are part of the loop. In Java, we would show this as curly brackets. Formatting becomes very important in Python then – if you hit tab and the wrong part of your code gets indented, then it won't run!

Along with loops, 'if statements' are also a very important part of programming in Python. Again, these do what they sound like they should do: they ask if a certain set of conditions are true and then run a segment of code if they are.

For example, we can say:

  if Age > 50:   print("You're over half way!")  

Alternatively, you can use the command else which executes when the statement is not true. For example:

  if Age > 50:   print("You're over half way!")   else:   print("Ah, still young!")  

Then you have elif, which is a portmanteau of 'else if' and which presents an alternative set of conditions to be met:

  if Age > 50:   print("You're over half way!")   elif Age < 50:   print("Ah, still young!")   else:   print("You're exactly halfway!")  

Here, Python will say 'you're exactly halfway' only if the user is not over 50 or under 50 – i.e. they are 50!

Using libraries and making a simple little game

Using the code we've learned here, we're almost ready to make a simple little game. Before we can do that though, we're going to first need to learn one more crucial thing: how to use external libraries.

The game I want to show you is a number guessing game like 'higher or lower'. To do this though, we need to generate a random number and there is no command in Python that can do that! Fortunately though, Python comes with a bunch of libraries in a bundle called the 'Python Standard Library'. That means we don't need to install anything extra and can simply write the line:

  from random import randint  

From there, we can then use the function randint which is followed by parentheses and two numbers: the lowest and highest range.

Now we can use the following code to make our simple game. Note that != means 'does not equal'.

  from random import randint  RandomNumber = randint(0, 10)  print("I'm thinking of a number between 1 and 10, can you guess what it is?")    Guess = 11    while Guess != RandomNumber:   Guess = int(input("Have a guess…"))   if Guess > RandomNumber:    print("Too high!")   if Guess < RandomNumber:    print("Too low!")    print("Got it!")  

While these aren't Android apps, there's nothing to stop you from creating little scripts like this and sharing them with friends or co-workers. As long as they have QPython3 installed, they'll be able to try them out and use them. And by using the Python Standard Library and a few others, you'll be able to write files on your device, download things from the web and more.

Of course there are plenty more things left to learn for those that want to take their education further. Classes are created very simply for example like so:

  def counter(Name):   length = len(Name)   return length;    NamePlease = input("Name length counter! Enter your name ")  print(counter(NamePlease))  

(Check out my recent post on object oriented programming if you're not sure what a class is.)

While lists are written as such:

  List = ["Apples", "Oranges", "Pears"]  

There are plenty of resources where you can learn more, but my advice is to pick up new skills and commands only as you need them. Start here!

Using the Python Android Scripting Layer

But what if you want to create a real Android app in Python? Well, in that case you have a few options – depending on what your idea of 'real' is.

If you're just looking to access some native features of your phone, then you can do this with a library called sl4a – or Python Android Scripting Layer. This will let us do things like showing dialogs, reading sensors and even accessing the camera.

The following line will open up your camera and save a photo:

  import sl4a    droid = sl4a.Android()  droid.cameraInteractiveCapturePicture("/sdcard/qpython.jpg")  

Or how about opening up a web page? We can do this simply by saying:

  from android import Android    droid = Android()  droid.webViewShow("http://ift.tt/lZ4kEL")  

We can even use to launch web views containing HTML files stored on the device, making it a great way to show GUI elements:

  droid.webViewShow('file:///sdcard/ index.html')  

Or what about creating a file based on information gathered from your script in order to show dynamic HTML? There are countless options here and when you combine this functionality with Tasker (an automation tool for Android devices) then you open up a whole world of possibilities.

Kivy and creating APKs

If you want to go further then you'll need to use Kivy. Kivy basically blows the doors wide open by letting us create fully functional Android apps with multi-touch, graphics and more. And this is also how you can turn your Python scripts into APKs that you can install directly on your Android device or even distribute via the Play Store. The best bit is that Kivy is also cross platform, so you can make apps for a variety of platforms this way.

Now we can show UI elements like buttons and canvases with graphics. As a taster, here is what a bit of code to show a button might look like:

  from kivy.app import App  from kivy.uix.button import Button    class HelloWorld(App):   def build(self):    btn = Button(text='Hello World')   return btn    HelloWorld().run()  

To do this though, we need to run Kivy on a PC. You can develop through Kivy on Windows but if you want to create APKs then I recommend using Linux instead. The problem is that creating APKs from Python scripts is still a long-winded and complex process on Windows and involves installing multiple libraries, the Android NDK, setting paths etc. It is complicated to the point of being nigh impossible.

Fortunately, a tool exists that can handle all of the heavy lifting for you which is called 'Buildozer'. This doesn't run on Windows, but fortunately it is easy enough to get Linux up and running on a virtual machine through VirtualBox and to then download a disc image from Kivvy that comes with everything you need to build your apps. Read the README.txt file that comes with your VM and it will talk you through everything you need to know. Once you've typed the commands instructed into the terminal, all that is left to do is to edit the 'buildozer.spec' file. This is where you will enter things such as your app's name, package name and any other files that need to be included.

You can find the full details and everything you need to download here. This is also a great opportunity to play around with Linux, try downloading some additional software etc. If you like Ubuntu then stay tuned – I'll be showing you how to run it on your Android device in a future post!

You will likely need to update a few things and install an IDE (such as Ninja IDE) and change various settings. Suffice to say that this still isn't quite 'plug and play' and really, at this point you would be better off sticking with Android Studio and Java. I really just included this section to demonstrate that it is possible to create apps in Python if you so wish. For the most part, I recommend sticking with QPython and using it as a place to try out code and maybe make yourself some handy tools.

Conclusion

So, Python isn't ideal for developing professional apps but it's a great way to create scripts and tools for your own use; whether that means building a tool to help you do some calculations or manage some data, or using Tasker to automate functions of your phone.

Moreover, Python is an excellent introduction to programming made all the easier thanks to QPython3. This is one of the easiest ways to start playing around with code on your mobile device and even in this short tutorial, we've seen how that can lead to all sorts of fascinating possibilities. That's why I love programming and that's why I love Android!



from Android Authority http://ift.tt/2nCRE2P
via IFTTT

No comments:

Post a Comment