0% found this document useful (0 votes)
6 views43 pages

Python basics

A beginners guide to code

Uploaded by

hamdhafowzan06
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
6 views43 pages

Python basics

A beginners guide to code

Uploaded by

hamdhafowzan06
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 43

PYTHON

Python Getting Started


Python Install
Many PCs and Macs will have python already installed.
To check if you have python installed on a Windows PC, search in the start bar
for Python or run the following on the Command Line (cmd.exe):
C:\Users\Your Name>python --version

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/
Python Quickstart
Python is an interpreted programming language, this means that as a developer you write
Python (.py) files in a text editor and then put those files into the python interpreter to be
executed.
(if you don’t have a text editor download Notepad++)
The way to run a python file is like this on the command line:
C:\Users\Your Name>python helloworld.py

Where "helloworld.py" is the name of your python file.


Let's write our first Python file, called helloworld.py, which can be done in any text
editor.
print(“Hello, World!”)
Simple as that. Save your file. Open your command line, navigate to the directory
where you saved your file, and run:

C:\Users\Your Name>python helloworld.py


C:\Users\Your Name>python helloworld.py
The output should read:
Hello, World!
Congratulations, you have written and executed your first Python
program.
Worksheet (given worksheet)
Execute Python Syntax
As we learned in the previous page, Python syntax can be executed by writing
directly in the Command Line:

>>> print("Hello, World!")


Hello, World!

Or by creating a python file on the server, using the .py file extension, and
running it in the Command Line:

C:\Users\Your Name>python myfile.py


Python Indentation
Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability


only, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

if 5 > 2:

print("Five is greater than two!" )

Python will give you an error if you skip the indentation:

if 5 > 2:

print("Five is greater than two!" )


The number of spaces is up to you as a programmer, the most common use is four, but it has to
be at least one.
Python Variables
In Python, variables are created when you assign a value to it:

x = 5

y = "Hello, World!"
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:

#This is a comment.
print("Hello, World!" )

Comments can be used to explain Python code.

Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

A comment does not have to be text that explains the code, it can also be
used to prevent Python from executing code:
Multiline Comments
add a multiline string (triple quotes) in your code, and place your
comment inside it:

"""

This is a comment

written in

more than just one line

"""

print("Hello, World!")
Python Va riables
Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

Example 1
x = 5

y = "Harry"

print(x)

print(y)

Variables do not need to be declared with any particular type, and can even change type after they have been set.

Example 2
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
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:

● A variable name must start with a letter or the underscore character


● A variable name cannot start with a number
● A variable name can only contain alphanumeric characters and underscores (A-z, 0-9, and _ )
● Variable names are case-sensitive (age, Age and AGE are three different variables)
● A variable name cannot be any of the Python keywords.
Python Data Types

In programming, data type is an important concept.


Variables can store data of different types, and different types can do
different things.
Python has the following data types built-in by default, in these
categories:
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:
Python Operators
Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:
Python Type
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.

Example

x = 1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))
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))
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:

Convert from one type to another:

x = 1 # int

y = 2.8 # float

z = 1j # complex

#convert from int to float:

a = float(x)

#convert from float to int:

b = int(y)
#convert from int to complex:

c = complex(x)

print(a)

print(b)

print(c)

print(type(a))

print(type(b))

print(type(c))
Python 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:

Example:

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)
Python Booleans
Booleans represent one of two values: True or False.

print(10 > 9)

print(10 == 9)

print(10 < 9)
Example
Print a message based on whether the condition is True or False:

a = 200

b = 33

if b > a:

print("b is greater than a")

else:

print("b is not greater than a")


Python Lists
mylist = ["apple", "banana", "cherry"]
Lists are used to store multiple items in a single variable.
Lists are created using square brackets:
Create a List:
thislist = ["apple", "banana", "cherry"]
print(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]


type()
mylist = ["apple", "banana", "cherry"]

print(type(mylist))

The list() Constructor


Using the list() constructor to make a List:

thislist = list(( "apple", "banana", "cherry")) # note the double


round-brackets

print(thislist)
Access Items
List items are indexed and you can access them by referring to the index
number:
Example:
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Negative Indexing

Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.

Example
Print the last item of the list:

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

print(thislist[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end
the range.
When specifying a range, the return value will be a new list with the specified
items.
Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Change Item Value

To change the value of a specific item, refer to the index number:

Example

Change the second item:

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

thislist[1] = "blackcurrant"

print(thislist)
Append Items
To add an item to the end of the list, use the append() method:

Using the append() method to append an item:

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

thislist.append( "orange")

print(thislist)
Insert Items
To insert a list item at a specified index, use the insert() method.

The insert() method inserts an item at the specified index:

Example

Insert an item as the second position:

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

thislist.insert(1, "orange")

print(thislist)
Extend List
To append elements from another list to the current list, use the extend() method.

Example

Add the elements of tropical to thislist :

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

tropical = ["mango", "pineapple", "papaya"]

thislist.extend(tropical)

print(thislist)
Remove Specific Item
The remove() method removes the specified item.

Example:
Remove "banana":

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

thislist.remove( "banana")

print(thislist)
Remove Specified Index

The pop() method removes the specified index.

Example

Remove the second item:

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

thislist.pop(1)

print(thislist)
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes representing
unicode characters.

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.

Example

Get the character at position 1 (remember that the first character has the position
0):

a = "Hello, World!"

print(a[1])
Looping Through a String

Since strings are arrays, we can loop through the characters in a string, with a for loop.

Example
Loop through the letters in the word "banana":

for x in "banana":

print(x)

You might also like