Python Programming Basics
Main.PythonBasics History
Show minor edits - Show changes to markup
The easiest way to convert a number to a string is with the built-in function str. However, this method may produce a number that has too many decimal places. Numbers can be customized in floating point (f), scientific notation (e), or percentage (%) form with format such as:
An easy way to convert a number to a string is with the built-in function str or with formatted output. However, this method may produce a number that has too many decimal places. Numbers can be customized in floating point (f), scientific notation (e), or percentage (%) form with format such as:
(:html:)
<div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'apmonitor'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'https://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> <a href="https://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
(:htmlend:)
(:html:) <iframe width="560" height="315" src="https://www.youtube.com/embed/BdATXeUkKnw" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> (:htmlend:)
Guess a number (0-10): 5 Too high Guess a number (0-10): 3 Too high Guess a number (0-10): 1 Too low Guess a number (0-10): 2 Correct!
Python has addition (+), subtraction (-), multiplication (*), division (/), and power (**) as standard mathematical operators. The Math module is available with:
import math
These provide a number of other mathematical operators such as shown in the example below:
Python has addition (+), subtraction (-), multiplication (*), division (/), and power (**) as standard mathematical operators. The Math module is available by importing the math package. The math module provides a number of common mathematical operators such as shown in the example below.
The Numpy module also has many of the mathematical operators. This course uses many NumPy and SciPy built-in values and functions for scientific computing. Below is an example of using a built-in value and a trigonometric function (sine).
The Numpy module also has many of the mathematical operators. This course uses many NumPy and SciPy built-in values and functions for scientific computing. Below is an example of using a built-in value and a trigonometric function (sine). In this case, the NumPy package is renamed as np to shorten the future references (numpy.pi => np.pi).
myVar myVariable my4Variable myVariable4 _myVariable __myVariable MYVARIABLE myvariable
myVar myVariable my4Variable myVariable4 _myVariable __myVariable MYVARIABLE myvariable
my Variable 4myVariable myVariable!
my Variable 4myVariable myVariable!
There are also many built-in functions that should also be avoided when creating variable names such as:
There are also many built-in functions that should also be avoided when creating variable names. Some common functions are listed below.
max # return the maximum value min # return the minimum value
len # number of elements in a collection max # maximum value min # minimum value pow # power (e.g. pow(x,2) or use x**2)
round # nearest integer value
Python is an object-oriented programming language. Each Python object has defining properties including the Identity (an identification number), Type (e.g. String, Integer, Float), and Value. Below is an example of assigning 'x' as an Integer and printing the object properties.
Python is an object-oriented programming language. Each Python object has defining properties including the Identity (a memory address), Type (e.g. string, integer, floating point number), and Value. Below is an example of assigning 'x' as an Integer and printing the object properties.
print(x) # print value => 3
print(x) # print value => 2
Python Data Types
Data can be stored a variety of formats. Fundamental Data Types include Numbers (e.g. int and float), Sequences (e.g. str, list, and tuple), and Mappings (dict). Below are a few examples:
(:source lang=python:) x=2 # integer y=2.02 # float z='3' # string print(str(x)+z) # 23 print(x+int(z)) # 5
a=[x,y,z] # list print(a[1]) # 2.02
b=(x,y) # tuple print(b[1]) # 2.02
c={'m':7,'n':8} # dictionary print(c['m']) # 7 (:sourceend:)
Python Math Expressions
Python has addition (+), subtraction (-), multiplication (*), division (/), and power (**) as standard mathematical operators. The Math module is available with:
import math
These provide a number of other mathematical operators such as shown in the example below:
(:source lang=python:) import math x=3.1415 print(math.sin(x)) # 9.265e-05 (:sourceend:)
The Numpy module also has many of the mathematical operators. This course uses many NumPy and SciPy built-in values and functions for scientific computing. Below is an example of using a built-in value and a trigonometric function (sine).
(:source lang=python:) import numpy as np x=np.pi print(math.sin(x)) # 1.225e-16 (:sourceend:)
The result of mathematical expressions may be slightly off the expected value such as the example above that should equal to zero for sin(pi). This is due to finite machine precision (32-bit or 64-bit) calculations that have some round-off error at the last stored digit.
Python Strings
Strings are a list of characters. Strings are combined with the addition (+) symbol and either the single or double quotes are used.
(:source lang=python:) first = 'Tom' last = "Smith" name = first + ' ' + last print(name) # Tom Smith (:sourceend:)
Comments can are added to Python scripts with the hash (#) symbol. When included inside a string, the comment character becomes part of the text and is no longer a comment.
(:source lang=python:) hashtag = '#learnpython' print(hashtag) # prints: #learnpython (:sourceend:)
There are also special escape sequences such as newline (\n), tab indent (\t), double quote (\"), single quote (\'), and backslash (\\).
(:source lang=python:) flight = 'Landing at\n O\'Hare International Airport' print(flight)
- prints:
- Landing at
- O'Hare International Airport
(:sourceend:)
To avoid using special escape sequences such as newline, a raw string identifier (r) can be used before the string definition.
(:source lang=python:) flight = r'Landing at\n O\'Hare International Airport' print(flight)
- prints:
- Landing at\n O\'Hare International Airport
(:sourceend:)
The easiest way to convert a number to a string is with the built-in function str. However, this method may produce a number that has too many decimal places. Numbers can be customized in floating point (f), scientific notation (e), or percentage (%) form with format such as:
(:source lang=python:)
- import the number pi
import numpy as np x = np.pi
- format pi
print(str(x)) # 3.141592653589793 print('{:.2f}'.format(x)) # 3.14 print('{:.10f}'.format(x)) # 3.1415926536 print('{:.5e}'.format(x)) # 3.14159e+00 print('{:.3%}'.format(x)) # 314.159% (:sourceend:)
This tutorial is an introduction to Python basics such as how to assign a variable value or increment that value. Valid variable names are those that start with a letter (upper or lower case) or underscore. Valid variable names include:
myVariable my4Variable myVariable4 _myVariable __myVariable MYVARIABLE myvariable
This tutorial is an introduction to Python basics such as how to assign a variable value and change that value. There is also a list of reserved keywords although use of these keywords is explained later.
Python Variable Names
Valid variable names are those that start with a letter (upper or lower case) or underscore. Valid variable names include:
myVar myVariable my4Variable myVariable4 _myVariable __myVariable MYVARIABLE myvariable
Invalid variable names include those that start with a number or have a space in the name such as:
my Variable 4myVariable
Invalid variable names include those that start with a number, have a space in the name, or contain special characters such as:
my Variable 4myVariable myVariable!
Python Reserved Keywords
There are reserved keywords in Python that control the flow of the program and cause unique behavior. Built-in constants include:
True # True logical condition False # False logical condition None # Absense of a value
Note that True, False, and None are capitalized. Common reserved keywords include:
and # logical 'and' (both conditions True) as # aliasing (e.g. with open(file) as f:) assert # internal self-check (e.g. assert x=y) break # break out of a loop class # define a new class (variables and functions) continue # advance to next 'for' or 'while' loop def # define a function del # set a variable to 'None' elif # 'else if' condition of 'if' statement else # 'else' condition of 'if' statement except # catch errors finally # 'try' exit code for # 'for' loop from # specify package element for loading global # create a global variable if # 'if' statement import # load package in # membership operator (e.g. x in y) is # test for equal identification numbers lambda # create anonymous function nonlocal # expand variable scope outside function not # logical 'not' or # logical 'or' pass # null operator when statement is required print # create display output line raise # error notification (e.g. raise Exception('Error')) return # return from function try # 'try'...'except' code structure for error catching while # loop until condition is not True with # flow control for automatic clean-up yield # intermediate return from function
There are reserved keywords in Python that control the flow of the program and cause unique behavior. These reserved keywords include:
There are also many built-in functions that should also be avoided when creating variable names such as:
float # convert number to floating point type id # identification number int # convert number to integer type max # return the maximum value min # return the minimum value range # sequence generator str # convert to string type type # object type
These reserved keywords should be avoided when creating variable names. Most Integrated Development Environments (IDEs) for Python and text editors for Python scripts will automatically highlight the reserved keywords such as the example below where reserved keywords are highlighted in orange and green.
(:toggle hide mycode1 button show="Show Example of Reserved Keywords":) (:div id=mycode1:)
answer = randint(0,100)
answer = randint(0,10)
guess = int(input("Guess a number: "))
guess = int(input("Guess a number (0-10): "))
(:divend:)
Python Objects
Python is an object-oriented programming language. Each Python object has defining properties including the Identity (an identification number), Type (e.g. String, Integer, Float), and Value. Below is an example of assigning 'x' as an Integer and printing the object properties.
(:source lang=python:) x=2 # create variable 'x' print(x) # print value => 3 print(id(x)) # print id number => 1737348944 print(type(x)) # print type => <class 'int'> (:sourceend:)
(:title Python Programming Basics:) (:keywords Python, variable naming, assignment, False, True:) (:description Python is a versatile language but can be intimidating for first-time programmers. This tutorial is designed for beginners to get started.:)
This tutorial is an introduction to Python basics such as how to assign a variable value or increment that value. Valid variable names are those that start with a letter (upper or lower case) or underscore. Valid variable names include:
myVariable my4Variable myVariable4 _myVariable __myVariable MYVARIABLE myvariable
Invalid variable names include those that start with a number or have a space in the name such as:
my Variable 4myVariable
There are reserved keywords in Python that control the flow of the program and cause unique behavior. These reserved keywords include:
(:source lang=python:) from random import * answer = randint(0,100) correct = False while not(correct):
guess = int(input("Guess a number: ")) if guess < answer: print("Too low") elif guess > answer: print("Too high") else: print("Correct!") correct = True
(:sourceend:)
(:html:)
<div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'apmonitor'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'https://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> <a href="https://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
(:htmlend:)