Introduction to Python
Learning Python with virtual environment
[sudo] pip install virtualenv
source bin/activate
deactivate
Read Documentations Here Check my script collections Here
Python Basics
String concatenation
>>> 'Alice' + 'Bob'
'AliceBob'
>>> 'Alice' + 42 #Error
>>> 'Alice' * 5
'AliceAliceAliceAliceAlice'
>>> 'Alice' * 'Bob' #Error
>>> 'Alice' * 5.0 #Error
Common functions
print('what is your name?') # This is comment
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is: ')
print(len(myName))
str()
int()
float()
Flow control
Boolean values
Boolean Operators
If Statement
if name === 'Alice':
print('Hi, Alice')
elif age < 12:
print('You are not Alice, kiddo.')
else:
print('Hello, stranger.')
Loops
spam = 0
while spam < 5:
print('hello.')
spam = spam + 1 # break, continue, applies
for i in range(5) # range([start], end, [step])
print('Count (' + i + ')')
Functions
def hello():
print('Howdy!')
hello() # Function call
def hello(name):
print('Hello ' + name)
hello('Bob') # Function call with arguments
The None Value
>>> spam = print('Hello!')
Hello!
>>> None == spam
True
Keyword Arguments and print()
print('Hello')
print('World')
# output:
# Hello
# World
print('Hello', end='')
print('World')
# output:
# HelloWorld
>>> print('cats', 'dogs', 'mice')
cats dogs mice
>>> print('cats', 'dogs', 'mice', sep=',')
cats,dogs,mice
Local and Global scopes applies
def spam():
global eggs # global keyword to make changes in local scopes
eggs = 'spam'
def bacon():
eggs = 'bacon' # this is local var
eggs = 'global'
spam()
print(eggs)
Exception
def spam(divideBy):
try:
return 42/divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
Written on July 20, 2017