Skip to main content

python

Python is a wonderful and powerful programming language that's easy to use (easy to read and write) and with Raspberry Pi lets you connect your project to the real world.


Python syntax is very clean, with an emphasis on readability and uses standard English keywords. Start by opening IDLE from the desktop.


IDLE

The easiest introduction to Python is through IDLE, a Python development environment. Open IDLE from the Desktop or applications menu:



IDLE gives you a REPL (Read-Evaluate-Print-Loop) which is a prompt you can enter Python commands in to. As it's a REPL you even get the output of commands printed to the screen without using print.

Note two versions of Python are available: Python 2 and Python 3. Python 3 is the newest version and is recommended, however Python 2 is available for legacy applications which do not support Python 3 yet. For the examples on this page you can use Python 2 or 3 (see Python 2 vs. Python 3).

You can use variables if you need to but you can even use it like a calculator. For example:
>>> 1 + 2
3
>>> name = "Sarah"
>>> "Hello " + name
'Hello Sarah'
IDLE also has syntax highlighting built in and some support for autocompletion. You can look back on the history of the commands you've entered in the REPL with Alt + P (previous) and Alt + N (next).
BASIC PYTHON USAGE
Hello world in Python:
print("Hello world")
Simple as that!

INDENTATION
Some languages use curly braces { and } to wrap around lines of code which belong together, and leave it to the writer to indent these lines to appear visually nested. However, Python does not use curly braces but instead requires indentation for nesting. For example a for loop in Python:
for i in range(10):
    print("Hello")
The indentation is necessary here. A second line indented would be a part of the loop, and a second line not indented would be outside of the loop. For example:
for i in range(2):
    print("A")
    print("B")
would print:
A
B
A
B
whereas the following:
for i in range(2):
    print("A")
print("B")
would print:
A
A
B

VARIABLES

To save a value to a variable, assign it like so:
name = "Bob"
age = 15
Note here I did not assign types to these variables, as types are inferred, and can be changed (it's dynamic).
age = 15
age += 1  # increment age by 1
print(age)
This time I used comments beside the increment command.

COMMENTS

Comments are ignored in the program but there for you to leave notes, and are denoted by the hash # symbol. Multi-line comments use triple quotes like so:
"""
This is a very simple Python program that prints "Hello".
That's all it does.
"""

print("Hello")
LISTS
Python also has lists (called arrays in some languages) which are collections of data of any type:
numbers = [1, 2, 3]
Lists are denoted by the use of square brackets [] and each item is separated by a comma.

ITERATION

 Some data types are iterable, which means you can loop over the values they contain. For example a list:
numbers = [1, 2, 3]

for number in numbers:
    print(number)
This takes each item in the list numbers and prints out the item:
1
2
3
Note I used the word number to denote each item. This is merely the word I chose for this - it's recommended you choose descriptive words for variables - using plurals for lists, and singular for each item makes sense. It makes it easier to understand when reading.
Other data types are iterable, for example the string:
dog_name = "BINGO"

for char in dog_name:
    print(char)
This loops over each character and prints them out:
B
I
N
G
O
RANGE
The integer data type is not iterable and tryng to iterate over it will produce an error. For example:
for i in 3:
    print(i)
will produce:
TypeError: 'int' object is not iterable
Python error
However you can make an iterable object using the range function:
for i in range(3):
    print(i)
range(5) contains the numbers 0, 1, 2, 3 and 4 (five numbers in total). To get the numbers 1 to 5 use range(1, 6).
LENGTH
You can use functions like len to find the length of a string or a list:
name = "Jamie"
print(len(name))  # 5

names = ["Bob", "Jane", "James", "Alice"]
print(len(names))  # 4
IF STATEMENTS
You can use if statements for control flow:
name = "Joe"

if len(name) > 3:
    print("Nice name,")
    print(name)
else:
    print("That's a short name,")
    print(name)
PYTHON FILES IN IDLE
To create a Python file in IDLE, click File > New File and you'll be given a blank window. This is an empty file, not a Python prompt. You write a Python file in this window, save it, then run it and you'll see the output in the other window.
For example, in the new window, type:
n = 0

for i in range(1, 101):
    n += i

print("The sum of the numbers 1 to 100 is:")
print(n)
Then save this file (File > Save or Ctrl + S) and run (Run > Run Moduleor hit F5) and you'll see the output in your original Python window.
EXECUTING PYTHON FILES FROM THE COMMAND LINE
You can write a Python file in a standard editor like Vim, Nano or LeafPad, and run it as a Python script from the command line. Just navigate to the directory the file is saved (use cd and ls for guidance) and run with python, e.g.python hello.py.
Python command line

Comments

Popular posts from this blog

CLOUD WORKFLOW SCHEDULING WITH DEADLINE AND TIME SLOT ALGORITHM

CLOUD WORKFLOW SCHEDULING WITH DEADLINE AND TIME SLOT ALGORITHM Abstract Allocating service capacities in cloud computing is based on the assumption that they are unlimited and can be used at any time. However, available service capacities change with workload and cannot satisfy users’ requests at any time from the cloud provider’s perspective because cloud services can be shared by multiple tasks. Cloud service providers provide available time slots for new user’s requests based on available capacities. In this paper, we consider workflow scheduling with deadline and time slot availability in cloud computing. An iterated heuristic framework is presented for the problem under study which mainly consists of initial solution construction, improvement, and perturbation. Three initial solution construction strategies, two greedy- and fair-based improvement strategies and a perturbation strategy are proposed. Different strategies in the three phases result in several heuristics. ...

Android Tutorial

Android  is a complete set of software for mobile devices such as tablet computers, notebooks, smartphones, electronic book readers, set-top boxes etc. It contains a  linux-based Operating System ,  middleware  and  key mobile applications . It can be thought of as a mobile operating system. But it is not limited to mobile only. It is currently used in various devices such as mobiles, tablets, televisions etc. This tutorial is developed for beginners and experienced persons. Let's see the topics of android that we are going to learn. Basics of Android In this fundamental chapter, you will learn about android, its components, how to create first android application, internal of first android application etc. What is Android History and Version Software Stack Core Building Blocks Android Emulator Installing softwares Setup Eclipse Hello Android example Internal Details Dalvik VM AndroidManifest.xml R.java Hide Title Bar Activity and I...

Force Sensing Resistor FSR400

Force Sensing Resistor FSR400 This is a small  force sensitive resistor . It has a 0.16" (4 mm) diameter active sensing area. This FSR will vary its resistance depending on how much pressure is being applied to the sensing area. The harder the force, the lower the resistance. When no pressure is being applied to the FSR, its resistance will be larger than 1MΩ, with full pressure applied the resistance will be 2.5kΩ. Two pins extend from the bottom of the sensor with 0.1" pitch making it bread board friendly. These sensors are simple to set up and great for sensing pressure, but they aren't incredibly accurate. Use them to sense if it's being squeezed, but you may not want to use it as a scale. Dimensions: Overall length: 1.75" Overall width: 0.28" Sensing area: 0.3"