python --version
It provides
Visit https://go.lehigh.edu/linux to use Anaconda (and other Linux software) installed and maintained by the Research Computing group on your local Linux laptop or workstation
print("Hello World!")
Hello World!
input('What is your name? ')
What is your name? John Doe
'John Doe'
print("Hello There!")
!python myscript.py
Hello There! 1
!cat myscript.py
#!/usr/bin/env python print("Hello There!") x = 1 print(x)
%%bash
chmod +x myscript.py
./myscript.py
Hello There! 1
%%bash
is used to enter a series of bash command!
followed by the commandmessage = 'And now for something completely different'
n = 17
pi = 3.1415926535897931
the third assigns the (approximate) value of $\pi$ to pi
To display the value of a variable, you can use a print function
print(message)
And now for something completely different
type(message)
str
type(n)
int
type(pi)
float
76trombones = 'big parade'
File "<ipython-input-11-ee59a172c534>", line 1 76trombones = 'big parade' ^ SyntaxError: invalid syntax
class = 'Advanced Theoretical Zymurgy'
File "<ipython-input-12-73fc4ce1a15a>", line 1 class = 'Advanced Theoretical Zymurgy' ^ SyntaxError: invalid syntax
and | del | for | is | raise |
as | elif | from | lambda | return |
assert | else | global | not | try |
break | except | if | or | while |
class | exec | import | pass | with |
continue | finally | in | yield | |
def |
A statement is a unit of code that the Python interpreter can execute. We have seen two kinds of statements: print and assignment.
When you type a statement in interactive mode, the interpreter executes it and displays the result, if there is one.
A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute.
Operator | Meaning | Example |
---|---|---|
+ (unary) | Unary Positive | +a |
+ (binary) | Addition | a + b |
- (unary) | Unary Negation | -a |
- (binary) | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus | a % b |
// | Floor Division (also called Integer Divison | a // b |
** | Exponentiation | a ** b |
a = 4
b = 3
print(+a)
print(-b)
4 -3
print(a + b)
print(a - b)
7 1
print(a * b)
print(a / b)
print(3 * a // b)
print(2 * a % b)
print(a ** b)
12 1.3333333333333333 4 2 64
print(1)
x = 2
print(x)
1 2
print(x)
2
The result, for this function, is the type of the argument.
It is common to say that a function "takes" an argument and "returns" a result.
Function | Description |
---|---|
ascii() | Returns a string containing a printable representation of an object |
bin() | Converts an integer to a binary string |
bool() | Converts an argument to a Boolean value |
callable() | Returns whether the object is callable (i.e., some kind of function) |
chr() | Returns string representation of character given by integer argument |
complex() | Returns a complex number constructed from arguments |
float() | Returns a floating-point object constructed from a number or string |
hex() | Converts an integer to a hexadecimal string |
int() | Returns an integer object constructed from a number or string |
oct() | Converts an integer to an octal string |
ord() | Returns integer representation of a character |
repr() | Returns a string containing a printable representation of an object |
str() | Returns a string version of an object |
type() | Returns the type of an object or creates a new type object |
!cat mymodule.py
foo = 100 def hello(): print("i am from mymodule.py")
import mymodule
mymodule.foo
100
mymodule.hello()
i am from mymodule.py
from mymodule import hello
hello()
i am from mymodule.py
import mymodule as my
my.foo
100
Function | Description |
---|---|
abs() | Returns absolute value of a number |
divmod() | Returns quotient and remainder of integer division |
max() | Returns the largest of the given arguments or items in an iterable |
min() | Returns the smallest of the given arguments or items in an iterable |
pow() | Raises a number to a power |
round() | Rounds a floating-point value |
sum() | Sums the items of an iterable |
import math
print(math)
<module 'math' from '/Users/apacheco/anaconda3/lib/python3.7/lib-dynload/math.cpython-37m-darwin.so'>
degrees = 45
radians = degrees / 360.0 * 2 * math.pi
math.sin(radians)
0.7071067811865475
Function | Description |
---|---|
all() | Returns True if all elements of an iterable are true |
any() | Returns True if any elements of an iterable are true |
enumerate() | Returns a list of tuples containing indices and values from an iterable |
filter() | Filters elements from an iterable |
iter() | Returns an iterator object |
len() | Returns the length of an object |
map() | Applies a function to every item of an iterable |
next() | Retrieves the next item from an iterator |
range() | Generates a range of integer values |
reversed() | Returns a reverse iterator |
slice() | Returns a slice object |
sorted() | Returns a sorted list from an iterable |
zip() | Creates an iterator that aggregates elements from iterables |
Python has 5 Data types
print(123123123123123123123123123123123123123123123123 + 1)
123123123123123123123123123123123123123123123124
print(10)
print(0o10)
print(0b10)
10 8 2
Prefix | Interpretation | Base |
---|---|---|
0b | Binary | 2 |
0o | Octal | 8 |
0x | Hexadecimal | 16 |
type(10)
int
type(0o10)
int
type(0x10)
int
4.2
4.2
type(0.2)
float
type(.4e7)
float
4.2e-4
0.00042
1.79e308
1.79e+308
1.8e+308
inf
5e-324
5e-324
2e-324
0.0
0.5 - 0.4 - 0.1
-2.7755575615628914e-17
int(4.2)
4
float(15)
15.0
a = 2 + 3j
type(a)
complex
print(a.real, a.imag)
2.0 3.0
a*a
(-5+12j)
a*a.conjugate()
(13+0j)
print("I am a string.")
I am a string.
type("I am a string.")
str
print('I am too.')
I am too.
type('I am too.')
str
''
''
print("This string contains a single quote (') character.")
print('This string contains a double quote (") character.')
This string contains a single quote (') character. This string contains a double quote (") character.
print('This string contains a single quote (\') character.')
print("This string contains a double quote (\") character.")
This string contains a single quote (') character. This string contains a double quote (") character.
Escape Sequence | Escaped Interpretation |
---|---|
\' | Literal single quote (') character |
\" | Literal double quote (") character |
\newline | Newline is ignored |
\\ | Literal backslash () character |
\n | ASCII Linefeed (LF) character |
\r | ASCII Carriage Return (CR) character |
\t | ASCII Horizontal Tab (TAB) character |
\v | ASCII Vertical Tab (VT) character |
# To run example within Jupyter Notebook or IPython or Python Shell
name = input ("What is your name? ")
print("Hello ",name)
What is your name? Jane Doe Hello Jane Doe
print('''This string has a single (') and a double (") quote.''')
This string has a single (') and a double (") quote.
print("""This is a
string that spans
across several lines""")
This is a string that spans across several lines
str1="Hello"
str2="Hello"
print(id(str1),id(str2))
4414402376 4414402376
str1+=", Welcome to LTS Seminars"
print(str1,id(str1),id(str2))
Hello, Welcome to LTS Seminars 4414004880 4414402376
str1[0]
'H'
s = "So, you want to learn Python? " * 4
print(s)
So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? So, you want to learn Python?
s[start:end]
will return part of the string starting from index start
to index end - 1
s[3:15]
' you want to'
start
index and end
index are optional. start
index is 0 end
is the last index of the strings[:3]
'So,'
s[15:]
' learn Python? So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? '
s[:]
'So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? So, you want to learn Python? '
len(s)
120
a = [10, 20, 30, 40]
print(a)
[10, 20, 30, 40]
b = ['spam', 2.0, 5, [10, 20]]
print(b)
['spam', 2.0, 5, [10, 20]]
c=[]
print(c)
[]
numbers = [17, 123]
print(numbers,id(numbers))
[17, 123] 4414144648
numbers[0] = 5
print(numbers,id(numbers))
[5, 123] 4414144648
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
[1, 2, 3, 4, 5, 6]
c[2:5]
[3, 4, 5]
t1 = ['a', 'b', 'c']
t1.append('d')
print(t1)
['a', 'b', 'c', 'd']
t2 = ['e', 'f']
t1.extend(t2)
print(t1)
['a', 'b', 'c', 'd', 'e', 'f']
t = ['d', 'c', 'e', 'b', 'a']
t.sort()
print(t)
['a', 'b', 'c', 'd', 'e']
t = ['a', 'b', 'c']
x = t.pop(1)
print(t)
['a', 'c']
print(x)
b
t = ['a', 'b', 'c']
del t[1]
print(t)
['a', 'c']
t = ['a', 'b', 'c', 'd', 'e', 'f']
t.remove('b')
print(t)
['a', 'c', 'd', 'e', 'f']
t = ['a', 'b', 'c', 'd', 'e', 'f']
del t[1:5]
print(t)
['a', 'f']
s = 'spam'
t = list(s)
print(t)
['s', 'p', 'a', 'm']
s = 'pining for the fjords'
t = s.split()
print(t)
['pining', 'for', 'the', 'fjords']
s = 'spam-spam-spam'
delimiter = '-'
s.split(delimiter)
['spam', 'spam', 'spam']
t = ['pining', 'for', 'the', 'fjords']
delimiter = ':'
delimiter.join(t)
'pining:for:the:fjords'
eng2sp = dict()
print(eng2sp)
{}
eng2sp['one'] = 'uno'
print(eng2sp)
{'one': 'uno'}
eng2sp['two'] = 'dos'
print(eng2sp)
{'one': 'uno', 'two': 'dos'}
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
print(eng2sp)
{'one': 'uno', 'two': 'dos', 'three': 'tres'}
print(eng2sp['three'])
tres
del eng2sp['two']
print(eng2sp)
{'one': 'uno', 'three': 'tres'}
eng2sp.clear()
print(eng2sp)
{}
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
len(eng2sp)
3
t = ('a', 'b', 'c', 'd', 'e')
t1 = ('a',)
type(t1)
tuple
t2 = ('a')
type(t2)
str
t = tuple()
print(t)
()
t = tuple('lupins')
print(t)
('l', 'u', 'p', 'i', 'n', 's')
t = ('a', 'b', 'c', 'd', 'e')
print(t[1])
b
print(t[1:])
('b', 'c', 'd', 'e')
t[0] = 'A'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-100-7e674cdf20e6> in <module> ----> 1 t[0] = 'A' TypeError: 'tuple' object does not support item assignment
print(t,id(t))
t = ('A',) + t[1:]
print(t,id(t))
('a', 'b', 'c', 'd', 'e') 4412348112 ('A', 'b', 'c', 'd', 'e') 4412348640
a = 1
b = 2
temp = a
a = b
b = temp
print(a,b)
2 1
a,b = b,a
print(a,b)
1 2
a, b = 1,2,3
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-105-6b644e00ae5e> in <module> ----> 1 a, b = 1,2,3 ValueError: too many values to unpack (expected 2)
quot, rem = divmod(7, 3)
print(quot)
2
print(rem)
1
type(True)
bool
type(False)
bool
Operator | Meaning | Example |
---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
< | Less than | a < b |
<= | Less than or equal to | a <= b |
> | Greater than | a > b |
>= | Greater than or equal to | a >= b |
a = 10
b = 20
print(a == b)
False
c = 'Hi'
d = 'hi'
print(c == d)
print( c < d)
print(ord('H'),ord('h'),ord('i'))
False True 72 104 105
'HI' < 'Hi'
True
Operator | Example | Meaning |
---|---|---|
not | not x | True if x is False False if x is True (Logically reverses the sense of x) |
or | x or y | True if either x or y is True False otherwise |
and | x and y | True if both x and y are True False otherwise |
x = 5
not x < 10
False
x < 10 or callable(x)
True
x < 10 and callable(len)
True
def celcius_to_fahrenheit(tempc):
tempf = 9.0 / 5.0 * tempc + 32.0
return tempf
tempc = float(input('Enter Temperature in Celcius: '))
print("%6.2f C = %6.2f F" % (tempc, celcius_to_fahrenheit(tempc)))
Enter Temperature in Celcius: 25 25.00 C = 77.00 F
print(tempf)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-119-8f86e1a6cd78> in <module> ----> 1 print(tempf) NameError: name 'tempf' is not defined
Syntax:
if condition:
statements
The boolean expression after the if statement is called the condition.
if statements have the same structure as function definitions:
if x < 0:
pass
if ... else ...
conditional
if condition:
statments_1
else:
statements_2
if x % 2 == 0:
print('x is even')
else:
print('x is odd')
x is odd
if ... elif ... else
conditional
if condition1:
statements_1
elif condition2:
statements_2
else
statements_3
y = 10
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')
x is less than y
choice='d'
if choice == 'a':
print('choice is a')
elif choice == 'b':
print('choice is b')
elif choice == 'c':
print('choice is c')
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
x is less than y
if 0 < x:
if x < 10:
print('x is a positive single-digit number.')
x is a positive single-digit number.
if 0 < x and x < 10:
print('x is a positive single-digit number.')
x is a positive single-digit number.
Python provides three control statements that can be used within conditionals and loops
def factorial(n):
if n < 1:
return 1
else:
return n*factorial(n-1)
factorial(5)
120
def double_fact(n):
if n < 2:
return 1
else:
return n * double_fact(n - 2)
double_fact(10)
3840
There may be a situation when you need to execute a block of code a number of times.
A loop statement allows us to execute a statement or group of statements multiple times.
for iterating_var in sequence:
statements(s)
for letter in 'Hola':
print('Current Letter :', letter)
Current Letter : H Current Letter : o Current Letter : l Current Letter : a
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print ('Current fruit :', fruit)
Current fruit : banana Current fruit : apple Current fruit : mango
fruits = [0,1,2,3,4]
for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
Current fruit : 0 Current fruit : 1 Current fruit : 2 Current fruit : 3 Current fruit : 4
range(5)
range(0, 5)
list(range(5))
[0, 1, 2, 3, 4]
for var in list(range(5)):
print(var)
0 1 2 3 4
for keys in eng2sp.keys():
print(keys)
one two three
for vals in eng2sp.values():
print(vals)
uno dos tres
while expression:
statement(s)
number = int(input('Enter any integer: '))
fact = count = 1
while (count <= number ):
fact = count * fact
count += 1
print('Factorial of %d is %d' % (number, fact))
Enter any integer: 15 Factorial of 15 is 1307674368000
number = int(input('Enter any integer: '))
fact = count = 1
while (count <= number ):
fact = count * fact
print('Factorial of %d is %d' % (number, fact))
numbers = [11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num%2 == 0:
print ('the list contains an even number')
break
else:
print ('the list does not contain even number')
the list does not contain even number
count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")
0 is less than 5 1 is less than 5 2 is less than 5 3 is less than 5 4 is less than 5 5 is not less than 5
open(filename, mode)
mode | description |
---|---|
r | Opens a file for reading only, default mode |
w | Opens a file for writing only |
a | Opens a file for appending only. File pointer is at end of file |
rb | Opens a file for reading only in binary |
wb | Opens a file for writing only in binary |
fout = open('output.txt', 'w')
print(fout)
<_io.TextIOWrapper name='output.txt' mode='w' encoding='UTF-8'>
line1 = "This here's the wattle,\n"
fout.write(line1)
24
line2 = "the emblem of our land.\n"
fout.write(line2)
24
fout.close()
!cat output.txt
This here's the wattle, the emblem of our land.
Method | Description |
---|---|
read([number]) | Return specified number of characters from the file. if omitted it will read the entire contents of the file. |
readline() | Return the next line of the file. |
readlines() | Read all the lines as a list of strings in the file |
f = open('myscript.py', 'r')
f.read()
'#!/usr/bin/env python\n\nprint("Hello There!")\n\nx = 1\nprint(x)\n\n\n'
f.close()
f = open('myscript.py', 'r')
f.readlines()
['#!/usr/bin/env python\n', '\n', 'print("Hello There!")\n', '\n', 'x = 1\n', 'print(x)\n', '\n', '\n']
f.close()
f = open('myscript.py', 'r')
f.readline()
'#!/usr/bin/env python\n'
f.close()
f = open('myscript.py', 'r')
for line in f:
print(line)
f.close()
#!/usr/bin/env python print("Hello There!") x = 1 print(x)
f = open('output.txt', 'w')
x = 52
f.write(str(x))
f.close()
!cat output.txt
52
tempc = float(input('Enter Temperature in Celcius: '))
print("%6.2f C = %6.2f F" % (tempc, celcius_to_fahrenheit(tempc)))
Enter Temperature in Celcius: 35 35.00 C = 95.00 F
The general syntax for print function is print(format string with placeholder % (variables) )
The general syntax for a format placeholder is %[flags][width][.precision]type
type | data type |
---|---|
s | strings |
f or F | floating point numbers |
d or i | integers |
e or E | Floating point exponential format |
g or G | same as e or E if exponent is greater than -4, f or F otherwise |
fin = open('bad_file')
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-155-a7d7d7ad396b> in <module> ----> 1 fin = open('bad_file') FileNotFoundError: [Errno 2] No such file or directory: 'bad_file'
fout = open('/etc/passwd', 'w')
--------------------------------------------------------------------------- PermissionError Traceback (most recent call last) <ipython-input-156-8a9adb191927> in <module> ----> 1 fout = open('/etc/passwd', 'w') PermissionError: [Errno 13] Permission denied: '/etc/passwd'
fin = open('/home')
--------------------------------------------------------------------------- IsADirectoryError Traceback (most recent call last) <ipython-input-157-a2032f82d461> in <module> ----> 1 fin = open('/home') IsADirectoryError: [Errno 21] Is a directory: '/home'
try:
fin = open('bad.txt')
for line in fin:
print(line)
fin.close()
except:
print('Something went wrong.')
Something went wrong.
!cat test1.py
fin = open('bad.txt') for line in fin: print(line) fin.close() print('Hello World!')
!python test1.py
Traceback (most recent call last): File "test1.py", line 1, in <module> fin = open('bad.txt') FileNotFoundError: [Errno 2] No such file or directory: 'bad.txt'
!cat test2.py
try: fin = open('bad.txt') for line in fin: print(line) fin.close() except: print('Something went wrong.') print('Hello World!')
!python test2.py
Something went wrong. Hello World!
import numpy as np
a = np.array([2,3,4])
print(a, a.dtype)
[2 3 4] int64
b = np.array([(1.2, 3.5, 5.1),(4.1,6.1,0.5)])
print(b, b.dtype)
[[1.2 3.5 5.1] [4.1 6.1 0.5]] float64
c = np.array( [ [1,2], [3,4] ], dtype=complex )
c
array([[1.+0.j, 2.+0.j], [3.+0.j, 4.+0.j]])
print('Zeros: ',np.zeros( (3,4) ))
print('Ones', np.ones( (2,4), dtype=np.float64 ))
print('Empty', np.empty( (2,3) ))
Zeros: [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] Ones [[1. 1. 1. 1.] [1. 1. 1. 1.]] Empty [[1.2 3.5 5.1] [4.1 6.1 0.5]]
np.arange( 10, 30, 5 )
array([10, 15, 20, 25])
a = np.arange(15).reshape(3, 5)
a
array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])
print("array dimensions: ", a.shape)
print("number of dimensions: ", a.ndim)
print("element types: ", a.dtype.name)
print("size of elements: ", a.itemsize)
print("total number of elements: ",a.size)
print("type of object:",type(a))
array dimensions: (3, 5) number of dimensions: 2 element types: int64 size of elements: 8 total number of elements: 15 type of object: <class 'numpy.ndarray'>
a = np.array( [20,30,40,50] )
b = np.arange( 4 )
print('a: ', a)
print('b:', b)
print('a-b:', a-b)
print('B**2', b**2)
print('10*sin(a): ', 10*np.sin(a))
print('Which elements of a < 35:', a<35)
print('Elements of a < 35: ',a[a<35])
a: [20 30 40 50] b: [0 1 2 3] a-b: [20 29 38 47] B**2 [0 1 4 9] 10*sin(a): [ 9.12945251 -9.88031624 7.4511316 -2.62374854] Which elements of a < 35: [ True True False False] Elements of a < 35: [20 30]
A = np.array( [[1,1], [0,1]] )
B = np.array( [[2,0], [3,4]] )
print('A = ', A)
print('B = ', B)
print('A*B = ', A*B)
print('A . B = ', A.dot(B))
print('Numpy A. B = ', np.dot(A, B))
A = [[1 1] [0 1]] B = [[2 0] [3 4]] A*B = [[2 0] [0 4]] A . B = [[5 4] [3 4]] Numpy A. B = [[5 4] [3 4]]
np.linspace(0,2*pi,4)
array([0. , 2.0943951 , 4.1887902 , 6.28318531])
np.random.random((2,3))
array([[0.32677336, 0.10528816, 0.20271135], [0.68526784, 0.58842625, 0.44910518]])
B = np.arange(3)
print('B: ',B)
print('exp(B): ',np.exp(B))
print('sqrt(B): ',np.sqrt(B))
C = np.array([2., -1., 4.])
print('C: ', C)
print('B + C: ', np.add(B, C))
B: [0 1 2] exp(B): [1. 2.71828183 7.3890561 ] sqrt(B): [0. 1. 1.41421356] C: [ 2. -1. 4.] B + C: [2. 0. 6.]