Python Basics Notes
Python Basics Notes
It is used for:
Python is Interactive − you can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be very
quick.
Python can be treated in a procedural way, an object-orientated way or a
functional way.
Python Install
Many PCs and Macs will have python already installed.
If you find that you do not have python installed on your computer, then
you can download it for free from the following
website: https://www.python.org/
The way to run a python file is like this on the command line:
C:\Users\Your Name>python helloworld.py
Our first Python file, called helloworld.py, which can be done in any text editor.
print("Hello, World!")
python helloworld.py
C:\Users\Namee>python
From there you can write any python, including our hello world example
Whenever you are done in the python command line, you can simply type the
following to quit the python command line interface:
exit()
Or by creating a python file on the server, using the .py file extension, and
running it in the Command Line:
C:\Users\Namee>python myfile.py
Python Indentations
Where in other programming languages the indentation in code is for readability
only, in Python the indentation is very important.
Example:
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
Python Variables
In Python variables are created the moment you assign a value to it:
Example
Variables in Python:
x = 5
y = "Hello, World!"
Output: 5
Hello, World
Python has no command for declaring a variable.
Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a
comment:
Example
Comments in Python:
#This is a comment.
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the rest of
the line:
Example:
Comments does not have to be text to explain the code, it can also be used to
prevent Python from executing code:
#print("Hello, World!")
print("Cheers, Mate!")
Output: Cheers, Mate!
Python does not really have syntax for multi line comments.
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Since Python will ignore string literals that are not assigned to a variable, you
can add a multiline string (triple quotes) in your code, and place you comment
inside it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Python Variables
Creating Variables
Variables are containers for storing data values.
x = 5
y = "John"
print(x)
print(y)
Output: 5
John
Variables do not need to be declared with any particular type and can even
change type after they have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Output: Sally
String variables can be declared either by using single or double quotes:
x = "John"
# is the same as
x = 'John'
Output: John
John
Variable Names
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). Rules for Python variables:
Output Variables
The Python print statement is often used to output variables.
x = "awesome"
print("Python is " + x)
Output: 15
If you try to combine a string and a number, Python will give you an error:
x = 5
y = "John"
print(x + y)
Python Numbers
There are three numeric types in Python:
int
float
complex
Variables of numeric types are created when you assign a value to them:
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'int'>
<class 'float'>
<class 'complex'>
Int
Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'int'>
<class 'int'>
<class 'int'>
Float
Float, or "floating point number" is a number, positive or negative, containing
one or more decimals.
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Output: <class 'float'>
<class 'float'>
<class 'float'>
Float can also be scientific numbers with an "e" to indicate the power of 10.
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output: <class 'float'>
<class 'float'>
<class 'float'>
Complex
Complex numbers are written with a "j" as the imaginary part:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods:
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Output:
1.0
2
(1+0j)
<class 'float'> <class 'int'> <class 'complex'>
Random Number
Python does not have a random() function to make a random number, but
Python has a built-in module calledrandom that can be used to make random
numbers:
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1,10))
Output: 8
Python Casting
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can
be done with casting. Python is an object-orientated language, and as such it
uses classes to define data types, including its primitive types.
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Output: 1
2
3
Floats:
Output: 1.0
2.8
3.0
4.2
Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Output: s1
2
3.0
Python Strings
String Literals
String literals in python are surrounded by either single quotation marks, or
double quotation marks.
print("Hello")
print('Hello')
Output:
Hello
Hello
a = "Hello"
print(a)
Output: Hello
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Output:
However, Python does not have a character data type, a single character is
simply a string with a length of 1. Square brackets can be used to access
elements of the string.
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
Output:e
b = "Hello, World!"
print(b[2:5])
Output: llo
The strip() method removes any whitespace from the beginning or the end:
a = "Hello, World!"
print(len(a))
Output: 13
a = "Hello, World!"
print(a.lower())
a = "Hello, World!"
print(a.upper())
a = "Hello, World!"
print(a.replace("H", "J"))
The split() method splits the string into substrings if it finds instances of the
separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Format
We cannot combine strings and numbers like this, But we can combine strings
and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places
them in the string where the placeholders {} are:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
The format() method takes unlimited number of arguments, and are placed into
the respective placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
Output: I want 3 pieces of item 567 for 49.95 dollars.
You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Python Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x <
not Reverse the result, returns False if the result is not(x < 5 and x
true
is not Returns true if both variables are not the same x is not y
object
not in Returns True if a sequence with the specified value is not x not i
present in the object
>> Signed right Shift right by pushing copies of the leftmost bit in from the le
shift rightmost bits fall off
Python Lists
Python Collections (Arrays)
There are four collection data types in the Python programming language:
List
A list is a collection which is ordered and changeable. In Python lists are written
with square brackets.
Create a List:
Access Items
You access the list items by referring to the index number:
Output: banana
Output:
apple
banana
cherry
Check if Item Exists
To determine if a specified item is present in a list use the in keyword:
List Length
To determine how many items a list has, use the len() method:
Output:3
Add Items
To add an item to the end of the list, use the append() method:
Remove Item
There are several methods to remove items from a list:
The pop() method removes the specified index, (or the last item if index is
not specified):
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will
only be a reference to list1, and changes made in list1 will automatically also
be made in list2.
There are ways to make a copy, one way is to use the built-in List
method copy().
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Python Tuples
Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.
Create a Tuple:
Output: banana
Output: apple
banana
cherry
Tuple Length
To determine how many items a tuple has, use the len() method:
Output:3
Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
You cannot add items to a tuple:
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can
delete the tuple completely:
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
index() Searches the tuple for a specified value and returns the position of w
Python Sets
Set
A set is a collection which is unordered and unindexed. In Python sets are
written with curly brackets.
Create a Set: