print("hello, world!")
hello, world!
Welcome to the world of Python.
Python is very simple language to learn, yet it is quite powerful.
Let’s get a taste of Python by looking at a couple of examples.
Python is a very simple programming language and it is quite easy to learn.
Writing a hello-world program just takes a single line of code.
print("hello, world!")
hello, world!
It is very handy to use Python as a calculator.
print(1 + 2)
3
Python is a dynamically typed programming language, so you don’t need to declare type of variables.
= 1
x = 2
y print(x + y)
3
It is perfectly fine to reassign a variable to a value of a different type.
= 1
x print(x)
= "foo"
x print(x)
1
foo
While the variables do not have types associated with them, the values do have types. Python is strict about them and it doesn’t allow operations on incompatible datatypes.
1 + "2"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
People often assume that a dynamically-typed language is also weekly-typed, which is the case for languages like Perl, PHP and even Javascript. Python is dynamically-typed, but also strongly-typed.
Python uses indentation to identify the code that is part of a block.
= 50
marks
if marks > 35:
print("pass")
else:
print("fail")
pass
Notice that Python doesn’t use the usual {
and }
characters to identify code blocks. It just uses indentation to identify the block of code that is part of compound statements like if
, else
, etc.
Here is another example:
= [1, 2, 3, 4]
numbers
for n in numbers:
print(n)
print("done")
1
2
3
4
done
Python has elegant data strucutres and many built-in functions.
Using them the right way leads to very elegant code.
For example, the following example computes the sum of squares of all even numbers below one million.
# sum of squares of all even numbers below one million
sum([n*n for n in range(1000000) if n % 2 == 0])
166666166667000000
Isn’t that almost like restating the problem?
Not impressed yet? Here is another gem to find the longest word in the english dictionary1.
# what is the lonest word in the dictioanary
max(open("/usr/share/dict/words"), key=len)
"electroencephalograph's\n"
Python has an extensive standard library and many third-party libraries.
The following example find the most popular repositories on github.
import requests
= "https://api.github.com/search/repositories"
url = {
params "q": "language:python"
}
= requests.get(url, params=params).json()
data
for repo in data['items'][:10]:
print(repo['full_name'])
floodsung/Deep-Learning-Papers-Reading-Roadmap
microsoft/TaskMatrix
shadowsocks/shadowsocks
PaddlePaddle/PaddleOCR
fxsjy/jieba
streamlit/streamlit
tatsu-lab/stanford_alpaca
OpenBB-finance/OpenBBTerminal
luong-komorebi/Awesome-Linux-Software
AtsushiSakai/PythonRobotics
On unix machines, the words in the dictionary are usually available in the file /usr/share/dict/words
.↩︎