The core philosophy of the language:
Python enables programs to be written compactly and readably:
On Linux machine, Python is usually installed by default. To install Python on other systems, check out the Python Setup and Usage section in Python help documentation.
If you are using Windows, Anaconda is a good choice.
The Python interpreter is usually installed as
/usr/bin/python3 on those machines where it is available.
To start a Python interpreter, type the command in your terminal:
To terminate the Python interpreter, type an end-of-file character (
Control-D on Linux,
Control-Z on Windows) at the primary prompt. If that doesn’t work, you can exit the interpreter by typing the following command:
Write down your Python script and name it as
Your script contents look like this
#!/usr/bin/python3 print('Hello World')
chmod +x hello.py.
Note: The line
#!/usr/bin/python3 should appear at the very beginning of your file.
Help is available in Python sessions using
Some functions (and modules) have very long help files. When using IPython, these can be paged using the command
function? so that the text can be scrolled using page up and down and
function?? can be used to type the entire function including both the
docstring and the code.
Python has a large standard library, commonly cited as one of Python's greatest strengths, providing tools suited to many tasks.
Modules for creating graphical user interfaces, connecting to relational databases, pseudo random number generators, arithmetic with arbitrary precision decimals, manipulating regular expressions, and doing unit testing are also included.
As of September 2020, the Python Package Index, the official repository of third-party software for Python, contains more than 261,000 packages offering a wide range of functionality, including:
3 + 2 +4
5 + 4*3
8/5.0 # int / float -> float
8//5.0 # explicit floor division discards the fractional part
The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:
a = 3 b = 5 c = a + b c
In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations.
LastName = "Kang" FirstName = "Yanfei"
rbefore the first quote:
print(r"Hello \n World!")
Hello \n World!
Strings can be concatenated (glued together) with the
+ operator, and repeated with
"I " + 'L' + 'o'*5 + 've' + ' you'
'I Looooove you'
n = 10 "G"+"o"*n+"gle"
The built-in function
len() returns the length of a string:
Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated. This feature is particularly useful when you want to break long strings:
print("Hi, my name is Yanfei Kang." " And I am from Beijing.")
Hi, my name is Yanfei Kang. And I am from Beijing.
Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:
Name = "Yanfei Kang" Name
In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain a substring:
Name[0:6] #Remember that [0:6] mathematically means [0, 6).
Name2 = "Yanfei.Kang" Name2.lower().title().split(".")
values = [1,5,7,9,12]
Lists also supports operations like concatenation:
values + ["Hello","World"]*3
[1, 2, 1000, 4, 67, 22, 9999, 'Hello', 'World', 'Hello', 'World', 'Hello', 'World']
Lists are a mutable type, i.e. it is possible to change their content:
values = [1,2,3,4,67,22] values
[1, 2, 3, 4, 67, 22]
values = 1000 values
[1, 2, 1000, 4, 67, 22]
You can also add new items at the end of the list, by using the append() method
[1, 2, 1000, 4, 67, 22, 9999]
Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:
values[2:4] = [2,3,4] values
[1, 2, 2, 3, 4, 67, 22]
values[:] =  values len(values)
The Python interpreter has a number of functions built into it that are always available. They are listed here in alphabetical order. Use e.g.
help(abs) to see the function help.
abs() divmod() input() open() staticmethod() all() enumerate() int() ord() str() any() eval() isinstance() pow() sum() basestring() execfile() issubclass() print() super() bin() file() iter() property() tuple() bool() filter() len() range() type() bytearray() float() list() raw_input() unichr() callable() format() locals() reduce() unicode() chr() frozenset() long() reload() vars() classmethod() getattr() map() repr() xrange() cmp() globals() max() reversed() zip() compile() hasattr() memoryview() round() __import__() complex() hash() min() set() apply() delattr() help() next() setattr() buffer() dict() hex() object() slice() coerce() dir() id() oct() sorted() intern()
Then you can use all the mathematical functions inside
math module as:
Alternatively, you can do the following changes
import math as mt mt.exp(1)
If you just want to import one or two functions from a module
from math import exp exp(3)
from math import exp as myexp myexp(1)
x = -5 if x < 0: x = 0 print('Negative changed to zero') elif x == 0: print('Zero') elif x == 1: print('Single') else: print('More')
Negative changed to zero
words = ['cat', 'window', 'defenestrate'] for j in words: print(j,len(j)) print("I am done!")
cat 3 window 6 defenestrate 12 I am done!
def fib(n = 200): # write Fibonacci series up to n """ Print a Fibonacci series up to n. Usage fib(n) """ # the function help a, b = 0, 1 while a < n: print(a, end=" ") a, b = b, a+b
We can create a function that writes the Fibonacci series to an arbitrary boundary.
The first line should always be a short, concise summary that ends with a period.
If there are more lines in the documentation string, the second line should be blank.
The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or docstring.
Help on function fib in module __main__: fib(n=200) Print a Fibonacci series up to n. Usage fib(n)
0 1 1 2 3 5 8 13 21 34 55 89 144
0 1 1 2 3 5 8 13 21 34 55 89 144
The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError('refusenik user') print(complaint)
ask_ok("Do you really want to go?")
Do you really want to go?hao Yes or no, please! Do you really want to go?shi Yes or no, please! Do you really want to go?yes
a = f(1, 2) + g(3, 4).
selfas the name for the first method argument (see A First Look at Classes for more on classes and methods).