Introduction To Python
Introduction To Python
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
Python Comments
Creating a Comment
Comments starts with a #, and Python will ignore them:
Example
#This is a comment
print("Hello, World!")
Multiline Comments
Python does not really have a syntax for multiline comments.
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Python Variables
Variables are containers for storing data values.
Example
x = 5
y = "John"
print(x)
print(y)
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Example
x = 5
y = "John"
print(type(x))
print(type(y))
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a = 4
A = "Sally"
#A will not overwrite a
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Output Variables
The Python print() function is often used to output variables.
Example
x = "Python is awesome"
print(x)
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Global Variables
Variables that are created outside of a function (as in all of the examples above) are known
as global variables.
Global variables can be used by everyone, both inside of functions and outside.
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
To create a global variable inside a function, you can use the global keyword.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Strings
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
print("Hello")
print('Hello')
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part
of the string.
b = "Hello World!"
print(b[2:5])
Negative Indexing
Use negative indexes to start the slice from the end of the string:
b = "Hello, World!"
print(b[-5:-2])
a = "Hello, World!"
print(a.upper())
a = "Hello, World!"
print(a.lower())
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
a = "Hello"
b = "World"
c = a + b
print(c)
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined
order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the
list.
Changeable
The list is changeable, meaning that we can change, add, and remove items in
a list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Example
String, int and boolean data types:
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data,
the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Create a List:
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data,
the other 3 are List, Set, and Dictionary, all with different qualities and usage.
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined
order, and that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items
after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuples allow duplicate values:
Dictionary
Dictionaries are used to store data values in key:value pairs.
Dictionaries are written with curly brackets, and have keys and values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if
statement to test whether b is greater than a. As a is 33, and b is 200, we know
that 200 is greater than 33, and so we print to screen that "b is greater than a".
Elif
The elif keyword is Python's way of saying "if the previous conditions were not
true, then try this condition".
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Python Loops
Python has two primitive loop commands:
while loops
for loops
i = 1
while
i <
6:
prin
t(i)
i +=
1
This is less like the for keyword in other programming languages, and
works more like an iterator method as found in other object-orientated
programming languages.
With the for loop we can execute a set of statements, once for each
item in a list, tuple, set etc.
integers =
[2,3,4,5,6,7,5,4] for x
in integers:
print(x)