- Python Programming for Arduino
- Pratik Desai
- 2033字
- 2021-07-23 20:11:34
Python operators and built-in types
Now that you have a brief idea regarding the Python prompt, let's get you familiar with some of the basic Python commands. For these exercises, we will be using the Python IDLE, which also opens with the Python interactive prompt. You will require a method to describe the code segments, tasks, and comments when writing large and complex code. Non-executable content is called comments in any programming language, and in Python, they start with the hashtag character (#
). Like comments, you will be frequently required to check the output by printing on the prompt using the print command:
>>> # Fundamental of Python >>> # My first comment >>> name = "John" # This is my name >>> print name John
Operators
Python supports the usage of basic mathematical operators such as +, -, *, and /, directly from the interpreter. Using these operators, you can perform basic calculations in the prompt, as shown in the following examples. Try these operations in your prompt in order to start using the Python interpreter as a calculator:
>>> 2 + 2 4 >>> (2*3) + 1 7 >>> (2*3) / 5 1
Note
When working with the Python interpreter, it is recommended that you follow the Style Guide for Python Code, which is also popularly known as PEP-8 or pep8. For more information about PEP-8, visit https://www.python.org/dev/peps/pep-0008/.
Built-in types
Python is a dynamically typed language, which means that you don't have to explicitly declare the type of the variables when initializing them. When you assign a value to a variable, the Python interpreter automatically deduces the data type. For example, let's declare the following variables in the interactive mode of the interpreter:
>>> weight = height = 5 >>> weight * height 25 >>> type(weight) <type 'int'>
While assigning the value to the weight
variable, we didn't specify the data type, but the Python interpreter assigned it as an integer type, int
. The interpreter assigned the int
type due to the reason that the numerical value didn't contain any decimal points. Let's now declare a variable with a value containing a decimal point. The built-in function type()
that can be used to find out the data type of a specified variable:
>>> length = 6.0 >>> weight * height * length 150.0 >>> type(length) <type 'float'>
As you can see, the interpreter assigns the data type as float
. The interpreter can also deduce the type of complex numbers, as shown in following examples. You can access the real and imaginary value of a complex number using the dot (.
) operator followed by real
and imag
:
>>> val = 2.0 + 3.9j >>> val.real 2.0 >>> val.imag 3.9
Just to play more with complex numbers, let's try the abs()
and round()
functions as displayed in the following examples. They are built-in Python functions to obtain the absolute value and the rounded number respectively:
>>> abs(val) 4.382921400162225 >>> round(val.imag) 4.0
Like numbers, the Python interpreter can also automatically identify the declaration of string data types. In Python, string values are assigned using single or double quotes around the value. When the interpreter sees any value enclosed within quotes, it considers it to be a string. Python supports the usage of the +
operator to concatenate strings:
>>> s1 = "Hello" >>> s2 = "World!" >>> s1 + s2 'HelloWorld!' >>> s1 + " " + s2 'Hello World!'
A character type is a string of size one and the individual characters of a string can be accessed by using index numbers. The first character of a string is indexed as 0. Play with the following scripts to understand indexing (subscripting) in Python:
>>> s1[0] 'H' >>> s1[:2] 'He' >>> s1 + s2[5:] 'Hello!'
Note
Similar to the primary prompt with default notation >>>
, the Python interactive interpreter also has a secondary prompt that uses three dots (…) when it is being used from the terminal. You won't be able to see the three dots in IDLE when you use the secondary prompt. The secondary prompt is used for a multiline construct, which requires continuous lines. Execute the following commands by manually typing them in the interpreter, and do not forget to indent the next line after the if
statement with a tab:
>>> age = 14 >>> if age > 10 or age < 20: ... print "teen" teen
Python supports four main data structures (list
, tuple
, set
, and dictionary
) and there are a number of important built-in methods around these data structures.
Lists are used to group together values of single or multiple data types. The list
structure can be assigned by stating values in square brackets with a comma (,) as a separator:
>>> myList = ['a', 2, 'b', 12.0, 5, 2] >>> myList ['a', 2, 'b', 12.0, 5, 2]
Like strings, values in a list can be accessed using index numbers, which starts from 0. A feature called slicing is used by Python to obtain a specific subset or element of the data structure using the colon operator. In a standard format, slicing can be specified using the myList[start:end:increment]
notation. Here are a few examples to better understand the notion of slicing:
- You can access a single element in a list as follows:
>>> myList[0] 'a'
- You can access all the elements in the list by having empty start and end values:
>>> myList[:] ['a', 2, 'b', 12.0, 5, 2]
- You can provide start and end index values to obtain a specific subset of the list:
>>> myList[1:5] [2, 'b', 12.0, 5]
- Use of the minus symbol with an index number tells the interpreter to use that index number backwards. In the following example,
-1
backwards actually represents the index number5
:>>> myList[1:-1] [2, 'b', 12.0, 5]
- You can obtain every other element of the list by providing the increment value with start and end values:
>>> myList[0:5:2] ['a', 'b', 5]
- You can check the length of a list variable using the
len()
method. The usage of this method will be handy in the upcoming projects:>>> len(myList) 6
- You can also perform various operations to add or delete elements in the existing list. For example, if you want to add an element at the end of the list, use the
append()
method on the list:>>> myList.append(10) >>> myList ['a', 2, 'b', 12.0, 5, 2, 10]
- To add an element at a specific location, you can use the
insert(i, x)
method, wherei
denotes the index value, whilex
is the actual value that you want to add to the list:>>> myList.insert(5,'hello') >>> myList ['a', 2, 'b', 12.0, 5, 'hello', 2, 10]
- Similarly, you can use
pop()
to remove an element from the list. A simplepop()
function will remove the last element of the list, while an element at a specific location can be removed usingpop(i)
, wherei
is the index number:>>> myList.pop() 10 >>> myList ['a', 2, 'b', 12.0, 5, 'hello', 2] >>> myList.pop(5) 'hello' >>> myList ['a', 2, 'b', 12.0, 5, 2]
Tuples are immutable data structures supported by Python (different from the mutable structures of lists). An immutable data structure means that you cannot add or remove elements from the tuple data structure. Due to their immutable properties, tuples are faster to access compared to lists and are mostly used to store a constant set of values that never change.
The tuple
data structure is declared like list
, but by using parentheses or without any brackets:
>>> tupleA = 1, 2, 3 >>> tupleA (1, 2, 3) >>> tupleB = (1, 'a', 3) >>> tupleB (1, 'a', 3)
Just like in a list
data structure, values in tuple
can be accessed using index numbers:
>>> tupleB[1] 'a'
As tuples are immutable, list manipulation methods such as append()
, insert()
, and pop()
don't apply for tuples.
The set
data structure in Python is implemented to support mathematical set operations. The set
data structure includes an unordered collection of elements without duplicates. With its mathematical use cases, this data structure is mostly used to find duplicates in lists, as conversion of a list to a set using the set()
function removes duplicates from the list:
>>> listA = [1, 2, 3, 1, 5, 2] >>> setA = set(listA) >>> setA set([1, 2, 3, 5])
The dict
data structure is used to store key-value pairs indexed by keys, which are also known in other languages as associative arrays, hashes, or hashmaps. Unlike other data structures, dict
values can be extracted using associated keys:
>>> boards = {'uno':328,'mega':2560,'lily':'128'} >>> boards['lily'] '128' >>> boards.keys() ['lily', 'mega', 'uno']
Note
You can learn more about Python data structures and associated methods at https://docs.python.org/2/tutorial/datastructures.html.
Controlling the flow of your program
Just like any other language, Python supports controlling the program flow using compound statements. In this section, we will briefly introduce these statements to you. You can get detailed information about them from the official Python documentation at https://docs.python.org/2/reference/compound_stmts.html.
The if
statement is the most basic and standard statement used to set up conditional flow. To better understand the if
statement, execute the following code in the Python interpreter with different values of the age
variable:
>>> age = 14 >>> if age < 18 and age > 12: print "Teen" elif age < 13: print "Child" else: print "Adult"
This will result in Teen
being printed on the interpreter.
Python's for
statement iterates over the elements of any sequence according to the order of the elements in that sequence:
>>> celsius = [13, 21, 23, 8] >>> for c in celsius: print " Fahrenheit: "+ str((c * 1.8) + 32)
This will result in the Python interpreter generating the following output that will display the calculated Fahrenheit values from the given Celsius values:
Fahrenheit: 55.4 Fahrenheit: 69.8 Fahrenheit: 73.4 Fahrenheit: 46.4
The while
statement is used to create a continuous loop in a Python program. A while
loop keeps iterating over the code block until the condition is proved true:
>>> count = 5 >>> while (count > 0): print count count = count - 1
The while
statement will keep iterating and printing the value of the variable count and also reduce its value by 1 until the condition, that is (count > 0
), becomes true. As soon as the value of count
is lower than or equal to 0, the while
loop will exit the code block and stop iterating.
The other compound statements supported by Python are try/catch
and with
. These statements will be explained in detail in the upcoming chapters. Python also provides loop control statements such as break
, continue
, and pass
that can be used while a loop is being executed using the compound statements mentioned earlier. You can learn more about these Python features from https://docs.python.org/2/tutorial/controlflow.html.
Built-in functions
Python supports a number of useful built-in functions that do not require any external libraries to be imported. We have described a few of these functions as a collection of a respective category, according to their functionalities.
Conversion methods such as int()
, float()
, and str()
can convert other data types into integer, float, or string data types respectively:
>>> a = 'a' >>> int(a,base=16) 10 >>> i = 1 >>> str(i) '1'
Similarly, list()
, set()
, and tuple()
can be used to convert one data structure into another.
Python also supports built-in mathematical functions that can find the minimum and/or maximum values from a list. Check out the following examples and play around with the different data structures to understand these methods:
>>> list = [1.12, 2, 2.34, 4.78] >>> min(list) 1.12 >>> max(list) 4.78
The pow(x,y)
function returns the value of x
to the power of y
:
>>> pow(3.14159, 2) 9.869587728099999
Python provides easy access to string manipulation through built-in functions that are optimized for performance. Let's take a look at the following examples:
- Code to replace occurrences of a string or substring with a different one:
>>> str = "Hello World!" >>> str.replace("World", "Universe") 'Hello Universe!'
- Code to split a string with a separating character where the default character is space:
>>> str = "Hello World!" >>> str.split() ['Hello', 'World!']
- Code to split a string from a separating character for any other character:
>>> str2 = "John, Merry, Tom" >>> str2.split(",") ['John', ' Merry', ' Tom']
- Code to convert an entire string value into uppercase or lowercase:
>>> str = "Hello World!" >>> str.upper() 'HELLO WORLD!' >>> str.lower() 'hello world!'
Note
The Python documentation on the official website covers every built-in function in detail with examples. For better understanding of Python programming, visit https://docs.python.org/2/library/functions.html.
- Learning Neo4j
- The Complete Rust Programming Reference Guide
- Instant Testing with CasperJS
- OpenCV 3和Qt5計算機視覺應用開發
- Nginx Essentials
- ArcGIS By Example
- Windows Server 2016 Automation with PowerShell Cookbook(Second Edition)
- Elasticsearch Server(Third Edition)
- Gradle for Android
- Hands-On Full Stack Development with Go
- Visual Studio Code 權威指南
- 智能手機故障檢測與維修從入門到精通
- Microsoft Exchange Server 2016 PowerShell Cookbook(Fourth Edition)
- 用Python動手學統計學
- Build Your Own PaaS with Docker