<variable> = input <prompt>
[<item1>, <item2>, ...]
(<item1>, <item2>, ...)
{<key1>: <value1>, <key2>: <value2> ... }
<variable>[i]
<variable>[begin:end]
if <condition>
To run your Python script:
.py
" extension#!/usr/bin/env python
at top of script
python scriptname.py
From last time
In [1]: spam = input("2 letter words for (and rhymes with) you and me: ")
In [3]: guido = [spam, 'eggs']
In [4]: if (guido[1] == 'eggs'):
...: guido[1] = 'are the'
...:
In [5]: x = guido
In [6]: sausage = input("Like a time of day, but begins with 'k': ")
In [7]: y = sausage + 's'
In [8]: bacon = input("Fill in the blank in this children's game: Simon ___: ")
In [9]: z = ['who', bacon[0:-1]]
In [10]: print(x, y, z, "Ni!")
Now you can put everything together
In [1]: def main():
...: spam = input("2 letter words for (and rhymes with) you and me: ")
...: guido = [spam, 'eggs']
...: if (guido[1] == 'eggs'):
...: guido[1] = 'are the'
...: x = guido
...: sausage = input("Like a time of day, but begins with 'k': ")
...: y = sausage + 's'
...: bacon = input("Fill in the blank in this children's game: Simon ___: ")
...: z = ['who', bacon[0:-1]]
...: print(x, y, z, "Ni!")
...:
In [2]: main()
You can now save this in a file with the .py
extension!
def <function>():
<function>()
In [1]: def example_function():
...: print("This is a normal function")
...:
In [2]: example_function()
This is a normal function
def <function>(<arg1>, <arg2>):
In [1]: def greet(person):
...: print('Hello ', person)
...:
In [2]: def main():
...: name = input("What is your name?: ")
...: greet(name)
...:
In [3]: main()
What is your name?: Victor
Hello Victor
In [1]: def square(x):
...: z = float(x)**2
...: return z
...:
In [2]: def main():
...: number = input("Pick a number, any number: ")
...: y = square(number)
...: print("The square of your number is: ", y)
...:
In [3]: main()
Pick a number, any number: 16
The square of your number is: 256.0
See how I had to change the input. It was a string, so I changed it to a float!
In [1]: def square(x):
...: """
...: Returns the square of a number `x`
...:
...: Parameters
...: -----------
...: x : `float`, `str`, `int`
...: Input number.
...:
...: Returns
...: ----------
...: z : `float`
...: Square value of `x`
...: """
...: z = float(x)**2
...: return z
In [3]: square?
Signature: square(x)
Docstring:
Returns the square of a number `x`
Parameters
-----------
x : `float`, `str`, `int`
Input number.
Returns
----------
z : `float`
Square value of `x`
File: ~/<ipython-input-2-56d47fb12480>
Type: function
For more info on how to properly write docstrings, see:
https://docs.python-guide.org/writing/documentation/#docstrings-and-magic
for
loopsThe main format of the for
loop is:
for <variable> in <sequence>:
do something
Examples
In [1]: word = 'spam'
In [2]: for letter in word:
...: print(letter)
...:
In [3]: for i in [1, 3, 5, 7, 9]:
...: print(i * i)
In [4]: for i in range(10):
...: x = 3.9 * i * (1 - i)
...: print(x)
while
loopsThe main format of the while
loop is:
while <condition>:
<body>
Examples
In [2]: while(i < 10):
...: print(i)
...: i = i + 1
...:
0
1
2
3
4
5
6
7
8
9
Note that you can also write:
i += 1
instead of i = i + 1
<filevar>.read()
<filevar>.readline()
\n
<filevar>.readlines()
# How to open a file. The 'r' stands for 'read'.
infile = open('filename.dat', 'r')
# Saves the entire content of the file as a single string
data = infile.read()
# Print out data
print(data)
# Closes the file. Always remember to close your files!
infile.close()
Now you can print out the first 6 lines of sample.dat
# Opens the file in 'read' mode
infile = open('sample.dat', 'r')
# Loops over the first 6 lines
for i in range(6):
# Saves output to 'line'
line = infile.readline()
print( line[:-1] )
# Closes the file.
infile.close()
You can open files with the r
option.
<filevar>.write(<string>)
# Writes to file 'out.dat' and saves it as the object 'outfile'
outfile = open('out.dat', 'w')
# You write strings to 'outfile'.
# See the newline character and how it is being added
# to the string.
outfile.write( "Spam and eggs\n")
outfile.write( "Spam, bacon, eggs, and spam\n")
# Close the file
outfile.close()
Watch out ... 'w'
will overwrite the file each time it is reopened.
You can use 'a'
instead to append to the file
<format specifier> % (<values>)
%<width>.<precision>.<datatype>
You can specify the type of data types as well!
As part of the string, you can specify:
width and precision are optional
Some examples are
In [1]: a = 165.2
In [2]: print( '%.2d' %(a))
165
In [3]: b = 1024.65748
In [4]: print( '%.3f' %b)
1024.657
In [5]: print( '%s and another %s' %('spam', 'ham'))
spam and another ham
There is a better and easier way of formatting strings.
'some_string_{0}'.format(something)
In [1]: a = 123.45
In [2]: b = 45
In [3]: c = 'some string'
In [4]: 'a is equal to {0}, but b is equal to {1}'.format(a, b)
Out[4]: 'a is equal to 123.45, but b is equal to 45'
In [5]: 'you can also print out strings: {0}'.format(c)
Out[5]: 'you can also print out strings: some string'
In [6]: 'And combine numbers (a = {0:.1f} and strings (c = {1})'.format(a, c)
Out[6]: 'And combine numbers (a = 123.5 and strings (c = some string)'
format
is really easy to use
In [7]: array1 = [1, 'pancake', 2.0, 'testing']
In [8]: str1 = 'First is "{0}", then "{1}". Third element is "{2}", and finally "{3}"'
In [9]: str1.format(*array1)
Out[9]: 'First is "1", then "pancake". Third element is "2.0", and finally "testing"'
format
is really easy to useWhenever you write a script or interact with Python, you want to include some packages:
Ways of using a package
import <library>
## Import the complete package
import math
# Access a function
math.sqrt(x)
Ways of using a package
from <library> import <function>
## Importing only a module of the package
from numpy import arange
# Access a function
arange(10)
Ways of using a package
from <library> import *
## Importing only a module of the package
from numpy import *
# Access a function
arange(10)
Out of the three methods of importing a package,
the best one is the:
import <library>
because you're not overwriting namespace
More info: here
Back to main website: