0% found this document useful (0 votes)
59 views13 pages

Introduction To Python

Python is a popular programming language created by Guido van Rossum in 1991. It is commonly used for web development, software development, mathematics, and system scripting. Key features of Python include variables, data types, comments, functions, classes, and modules. Control flow is achieved through conditional statements and loops. Lists, tuples, and dictionaries allow storing and organizing multiple values in a single variable.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views13 pages

Introduction To Python

Python is a popular programming language created by Guido van Rossum in 1991. It is commonly used for web development, software development, mathematics, and system scripting. Key features of Python include variables, data types, comments, functions, classes, and modules. Control flow is achieved through conditional statements and loops. Lists, tuples, and dictionaries allow storing and organizing multiple values in a single variable.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

What is Python?

Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.

It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

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

Get the Type


You can get the data type of a variable with the type() function.

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"

Many Values to Multiple Variables


Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

One Value to Multiple Variables


And you can assign the same value to multiple variables in one line:

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)

In the print() function, you output multiple variables, separated by a comma:

Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)

You can also use the + operator to output multiple variables:

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.

ExampleGet your own Python Server


Create a variable outside of a function, and use it inside the function

x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

The global Keyword


Normally, when you create a variable inside a function, that variable is local, and can only
be used inside that function.

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.

'hello' is the same as "hello".

You can display a string literal with the print() function:

print("Hello")
print('Hello')

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an
equal sign and the string:

a = "Hello"
print(a)

Multiline Strings
You can assign a multiline string to a variable by using three quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

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])

The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())

The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

String Concatenation
To concatenate, or combine, two strings you can use the + operator.

Merge variable a with variable b into variable c:

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:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]


print(thislist)

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))

List Items - Data Types


List items can be of any data type:

Example
String, int and boolean data types:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

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.

Lists are created using square brackets:

Create a List:

thislist = ["apple", "banana", "cherry"]


print(thislist)

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.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

ExampleGet your own Python Server


Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

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:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)

Dictionary
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow


duplicates.

Dictionaries are written with curly brackets, and have keys and values:

Create and print a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Python supports the usual logical conditions from mathematics:

 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

These conditions can be used in several ways, most commonly in "if


statements" and loops.
An "if statement" is written by using the if keyword.

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

The while Loop


With the while loop we can execute a set of statements as long as a
condition is true.

Print i as long as i is less than 6:

i = 1
while
i <
6:
prin
t(i)
i +=
1

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).

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)

You might also like