Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

BASIC PYTHON:

Prerequisites

- Python must be installed.


+ If you're customizing your installation, be sure
to have IDLE installed as well, as that'll be your
starter script editor for this guide.
I. Introduction to Numbers

1.1 Numbers

- 2, 10, 3.14, 0.5, ...


- 2 types of numbers:
+ int: 1,5,8,-4,-40
+ float: 3.14, 0.5, -7.62, -6.9,
1.2. Number Operationsrs

- Addition (+): 10 + 5 = 15
- Subtraction (-): 10 - 5 = 5
- Multiplication (*): 10 * 5 = 50
- Power (**): 10**5 = 100000 (10*10*10*10*10)
- Division (/): 10 / 5 = 2.0, 14 / 5 = 2.8 (note: this always returns a float)
- Integer Division (//): 10 // 5 = 2, 14 // 5 = 2 (this always returns an int)
- Modular Division (%): 10 % 5 = 0 (the remainder of a division)
- Operations can be combined to make bigger operations.
+ Order of operations: () > ** > * > / > % > + -
Examples: 8-1+2+5 = 14, 8-(1+2)+5 = 10, 3*2**3 = 3*8 = 24
II. Introduction to String

2.1. Strings

- A string is a sequence of characters, surrounded by '' or "".


+ Example: 'this is a string', "this is also a string"
Note: The surrounding symbols (‘ or “) must match.
Example: ‘this is not a good string”, "nor is this'
2.2. Strings Operations

- Concatenation (+):
+ Example: "hey" + "there" = "heythere"
- Multiplication (*):
+ Example: "cool"*3 = "coolcoolcool"
+ Note: number to multiply must be an int.
- Indexing:
“string”[0] = “s”, “string”[2] = “r”, “string”[1:4] = "tri"
- Like numbers, operations can be combined together.
+ Order of operations: * > +
Examples: "a"*6 + "bcd" = "aaaaaabcd"
III. Introduction to Variables

3.1. Variables

- Like strings, but with some tweaks:


+ No starting with numbers: "2var" isn't a variable name
+ Does not contain ", ', or blank characters.
+ Examples: x, y, var, alongvariablestillworks, ...
3.2. Variable Operations

- Assign:
+ var='value', a=10, longvarname="a string", pi=3.14, ...
- Each variable must contain some value in order to be operated on.
+ Examples:
a=6, b=5: a + b = 6 + 5 = 11
a='its', b='fun': a + b = 'its' + 'fun' = 'itsfun'
a='nice', b=3: a*b = 'nicenicenice'
3.2. Variable Operations

- You can also assign a variable based on an output of an operation.


+ Examples:
x=10+3*6%4
var=20, y=var+30
nice=10, nice=nice+20 (new 'nice' variable = last 'nice' variable + 20)
+ Note: nice=nice+20 can also be written as nice+=20
(There are also many other shortcuts that works like this: -
=,*=,/=,%=,**=,...)
IV. Getting used to scripts

- In order to make a script file, you need to make sure file name
extensions are enabled.
+ Google "How to enable file name extensions" and do what the guide
says, it'll be handy later on.
4.1. Scripts

- Scripts are basically text files, with a .py extension.


(if you've enabled extensions, the extension is basically what's behind
that dot .)
+ Examples of script file names: "hey.py", "chicken.py",
"pythonisfun.py", ...
- Commands are executed in a top-bottom order.
+ Example of script file content: a=20
b =a+50
b-=20
Here, a=20 runs first, then b=a+50, then b-=20, in that order.
4.1. Scripts

- Comments: A comment start after the # symbol. Comments are ignored


by the code reader, and is mostly used to make code more readable.
Example:
# This code actually has comments.
a='this goes first'
# This line will be ignored
b='this still goes second'
# any commands you put behind a # becomes meaningless
# x='this will not be run, at all'
V. Your first command - print()

- Script files run from top to bottom, however, once you've run a script in
IDLE, you may notice that you're not seeing any output whatsoever.
- print() solves this issue by printing whatever you place in () so you can see.
+ For example: # This prints a string:
print('My Dog')
variable='nice'
# Also supports variables:
print(variable)
# Numbers work, too:
print(3.14)
V. Your first command - print()

- Using commas as separators, print() can also be used for printing more
complex combinations.
+ Examples: print('Pi is',3.14)
a=5
print('We have',a,'ice cubes')
a=8
print('We now have',a,'ice cubes')
V. Your first command - print()

+ Note: In between the commas there is always a ' '.


You can modify this by adding sep=<string> to print()
Example: # prints "coding_is_fun"
print('coding','is','fun',sep='_')
# prints "1<nice>2<nice>3<nice>4"
print(1,2,3,4,sep='<nice>')
a=' variables work'
# prints "yeah, variables work too"
print('yeah,','too',sep=a)
VI. The input() command

- The input() command writes a quote on the screen, and asks for your
input.
Example: input('write your thing here:')
- What you've inputted will be the input command's result, and can be
saved into variables or operated on.
VI. The input() command

Example:
# This code adds 'I say: ' to what you've written,
# and prints it:
x=input('Please add something here')
prints('I say: '+x)

Note: The result of input() will always be a string.


This can be changed, but more on that later.
VII. 'Block' of commands

- A block of command runs its commands in a group.


- To make a block of command: simply have the commands spaced out
evenly from the left side.
Example:
command1
command2
command3
Here, 'command2' and 'command3' run as a block.
Uses of this will be provided in later chapters.
VIII. Conditionals - the if command

8.1 . Introduction to Booleans

- Booleans are types of data that only has 2 values: True or False.
- Booleans are encountered when conditions are made.
- Linking Conditions: Conditions can be linked with and, or, not to
make better conditions.
8.2. The if command

- The if command runs commands based on a set of conditions.


General syntax:
if <condition>:
<block of command here>
Example:
a=input('say Hi')
if a='Hi!': print('Hey there!')
IX. Lists and Tuples

9.1 Lists

- List is basically a list of data. Syntax: [<any data, seperated by a colon (,)>]
Examples:
[1,2,3,4]
['this','is','a','list','of','strings']
['this','list','has','strings','and','numbers',101]
['list of lists work, too',['like this',20]]
9.2. List Operations

- Addition: ['list1'] + ['list2',101] = ['list1','list2',101]


- Repeat List: ['lol']*3 = ['lol','lol','lol']
- Indexing:
x=[1,2,3,4]
x[0]==1
x[2]==3
x[3]==4
x[-1]==4
x[-3]==2
x[1:3]==[2,3]
x[2:-1]==[3,4]
9.2. List Operations

- Editing in an index:
x=[1,2,3,4]
x[1] = 6
# x is now [1,6,3,4]
x[-1] = 3

- Append (adds to the right of a list):


x=[1,5,6,7,9]
x.append('newdata')
# x is now [1,5,6,7,9,'newdata']
9.2. List Operations

- Insert (inserts a value at the index, pushing everything else to the right)
x=[1,6,4]
# x.insert(index,value)
x.insert(2,5)
# x is now [1,6,5,4]
9.2. List Operations

- Pop (take a value with an index k from the list out of that list)
x=[10,20,30,40]
m=x.pop(2)
# 30 (x[2]) is now taken out of the list.
# assigning m as the operation
# actually stores the result into m
# which means m is now 30.
# and list after pop is [10,20,40]
9.3. Tuples

- Tuples are like lists, but:


+ Syntax uses () instead of []
+ Are more lightweight data-wise
+ Unlike lists, indexing operations does not work on tuples.
Note: to make a tuple with 1 entry, use (entry,), not (entry), as python does
not translate(entry) as a tuple.

Tuple examples: ("tuple with 1 entry",),("multiple entries",101), (["this tuple


had a list in it"],'still works fine',True)
X. Set

10.1. Set

- A Set is a collection of items. Unlike list and tuples, all items in a set must be
unique, and they are not ordered, which means indexing is not allowed in a set.
- Syntax: {<items go here>}
- Examples:
{1,2,4}
{'item',2,3,'another item'}
{{'a set can contain a set'},'this is true'}
Note: to make an empty set, use set(), not {}.
Reasons why will be mentioned in the Dictionaries section.
10.2. Set Operations

- Union (|): Combine 2 sets together:


{1,2,3}|{4,5,6}:{1,2,3,4,5,6}
# all duplicate values after merging will be removed.
{1,2,3}|{2,3,4}:{1,2,3,4}

- Intersection (&): Finds the set of common items between 2 sets:


# this returns {2,3}
{1,2,3}&{2,3,4}
# returns an empty set, as there's no common items
{1,2,3}&{4,5,6}
10.2. Set Operations

- Difference (-): For A-B: Finds the set in set A, but not in set B
# this returns {3,4}
{2,3,4,5}-{2,5}
# returns {1,2,3}
{1,2,3}-{4,5}

- Symmetric Difference(^): The set with items in one of the two sets, but not
both: # {1,2,4,5}
{1,2,3}^{3,4,5}
# {1,2,3,4,5,6}
{1,2,3}^{4,5,6}
XI. Dictionaries

11.1. Dictionary

- Dictionary is a type of data which follows a {key:value} format.


Note: key cannot be a dict, but value can.
Examples:
{"a key":'its value'}
{"one key":"one value","another key","another value"}
{1:"this works","this also works":True}
{"this value is a dict":{"indeed it is":True}}
XII . Type Conversions

- The act of changing a data from one type to another is considered a type
conversion.
- To do this: simply use the type's name, and cover the value you wish to
convert with curly brackets ().
Example:
# Converts 20 in string form into integer
int('20')
# Converts 40 in integer form to float:
float(40)
# the key difference between int and float
# float always have a dot in its value.
XII . Type Conversions

Note: if nothing is set as the convert value, it creates an empty value of that
type.
int() = 0, set() = {} (empty set), ...

type names:
int: Integer
float: Floating point values
str: String
dict: Dictionary
set: Set
XIII. Loops: for and while

13.1. for loop

- For loop will run within a range of values:


Example: for i in range (1,6):
print(i)
>>1
>>2
>>3
>>4
>>5
13.1. for loop

- For loop can run within a list or a string:


Example: t=’python’
For i in t:
print(i)
>>p
>>y
>>t
>>h
>>o
>>n
13.2. while loop

-While loop is similar to for loop, but it runs under a condition:


Example:
i=1
While i>0:
print(i)
>>1
>>1
>>1
>>......
And it will run as long as the condition is true.
13.3. loop operations: break and continue
- In any given loop (for or while):
- 'break' is used to stop a loop at any iteration
- 'continue' is used to skip to the next entry(iteration) of the loop
Examples: # Stop a for loop if entry is 5:
# if not, print the entry on the screen:
for entry in (2,6,8,4,2,5,7)
if entry ==5:
break
else:
print(entry)
print('Loop has ended.')
# Note that after the loop, all entries after (to the right of) 5 is not printed.
# Calculates the sum of all odd values in this list,
# skipping even values:
sum=0
for entry in [1,3,2,5,6,7,10,13,15]:
if entry%2==0:
# continue skips to the next entry
# so the lines below will not run.
continue
sum+=entry
# result after the sum is 44
print('loop has ended.')
# Note that after the loop,
# only the entries that are even got skipped.
XIV. Functions

14.1 Basic Function


- A function is a stored block of code, which can then be used to run
anywhere else.
Syntax:
# Creating a function:
def <functionname>():
<block of code to store>
# Calling a function:
<functionname>()
14.1 Basic Function
Example:
# Create a function to print alot of lines:
def massprint():
print('this is line 1')
print('this is another line')
print('and another one')

# do this again 3 times:


massprint()
massprint()
massprint()
14.2. Parameters
- Functions can be called with parameters.
Example: # This function has a parameter 'chicken'
# which prints out the value behind 'chicken'
def betterfunc(chicken):
print('chicken is:',chicken)
# Calling a function with parameters:
betterfunc(chicken='30')
betterfunc('this works too')
# This function has a parameter 'cost',
# with a default value: 20
def chicken(cost=20):
print('The cost of this chicken is:',cost)
14.2. Parameters

# When calling a function,


# if the parameter is not passed,
# the default one set when function is made gets used.
chicken()
chicken(369)
chicken(cost=42069)

# This function has many parameters:


def longfunc(param1='pork',param2='chicken')
print('First parameter is',param1)
print('Second parameter is',param2)
14.2. Parameters

longfunc()
# param1 is now 'bone', param2 is default
longfunc('bone')
# param2 is now 'doggo', param1 is default
longfunc(param2='doggo')
# param1 is 'cat', param2 is 'pig'
longfunc('cat','pig')
# mixed style:
longfunc('cat',param2='pig')
14.2. Parameters

longfunc()
# param1 is now 'bone', param2 is default
longfunc('bone')
# param2 is now 'doggo', param1 is default
longfunc(param2='doggo')
# param1 is 'cat', param2 is 'pig'
longfunc('cat','pig')
# mixed style:
longfunc('cat',param2='pig')
14.3. Return Value

- In Python, all operations have some form of return value, which is helpful if
the function is supposed to act as some part of a bigger operation.
- Note that when a function has returned its value,
the function stops running at the line which return is called.
- All functions that don't have a return command returns a None.
14.3. Return Value

- In Python, all operations have some form of return value, which is helpful if
the function is supposed to act as some part of a bigger operation.
- Note that when a function has returned its value,
the function stops running at the line which return is called.
- All functions that don't have a return command returns a None.
Example:
# This function returns a number, added by 20.
def raise(value=30)
return value+20
# This returns a 100, as raise(50) returns a 70
30+raise(50)

You might also like