Basics Flashcards
Variables
Do not need to be declared. Assigned by:
a=10
b=20
or
a,b=10,20
‘a’ + ‘a’
aa
‘a’ * 3
aaa
Length of strength ‘abc’?
len(‘abc’)
Get the letter ‘a’ from the string ‘abc’
‘abc’[0]
Get the letter ‘c’ from the string ‘abc’
‘abc’[2] or ‘abc’[-1]
From ‘hello world’, get the substring ‘world’
‘hello world’[6:]
From ‘hello world’, get the substring ‘ell’
‘hello world’[1:3]
Concatenate the strings ‘hello’ and ‘world’ together.
‘hello’ + ‘world’
If-else if-else statement
if(x
Sequence of numbers from 1 to 10
range(1,10)
Sequence of odd numbers from 1 to 10
range(1,10,2)
For loop
for i in range(1,10):
print i
While loop
while(x<10):
print x
x=x+1
Sequence of numbers from 0 to 100000000000
xrange(0, 100000000000)
xrange generates values only as they are needed, so it is faster than range for a large sequence of numbers
Delete a variable a
del a
Create a function called someFunction
def someFunction(): print 'I am a function'
Default function values
def someFunction(x=true): if(x=true): print 'default value' else: print 'changed value'
Passing parameters of a function in any order
power(x=4, num=2)
power(num=2, x=4)
Variable number of parameters in a function
def multi_add(*args): result=0 for x in args: result = result + x return result print multi_add(2,2,3,3,10) print multi_add(2,2)
Conditional statements
Lets you combine if-else statements into a single line.
x,y=1,2
print “x is less than y” if(x
Get the index and the value when enumerating over an array in a for loop.
days = [“M”,”T”,”W”,”R”]
for i,d in enumerate(days):
print i,d
# 0 M # 1 T # 2 W # 3 R
How you import modules into python?
#import the date class from the datetime module from datetime import date
#import everything in the module import calendar
Get the current date and time.
datetime. now()
date. today()
datetime. time(datetime.now())
Get the date and time a year from now.
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta
datetime.now() + timedelta(days=365)
Get the date and time a week ago.
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta
datetime.now() - timedelta(weeks=1)