Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Python Visualizing your code

Python Visualizing your code

Visualizing Your Code

When you're first learning about data structures such as lists, it helps to visualize how python is working with the information in your program. pythontutor.com is a graet tool for seeing how python keeps track of the information in a list. Try running the following code on pythontutor.com and then run your own code.

#Build a list and print the items in the list
dogs = []

for dog in dogs:
 print("Hello " + dog + "!")
print("I love these dogs!")

print("\nThese were my first two dogs:")
old_dogs = dogs[:2]
for old_dog in old_dogs:

del dogs[0]



Python List

Python List

What are lists?

A list store a series of items in a particular order. Lists allows you to store sets of information in one place, whether you have just a few items or millions of items . Lists are one of python's most powerful features readily accessible to new programmers, and they tie together many important concepts in progamming.

Defining a List

Use square brackets to define a list, and use commas to separate individual items in the list. Use plural names for lists, to make your code easier to read.

#Making a list
users = ['val', 'bob', 'mia', 'ron', 'ned']

python list

Accessing elements

Individual elements in a list are accessed according to their position, called the index. The index of the first element is 0, the index of the second element is 1, and so forth. Negative indices refer to items at the end of the list. To get a particular element, write the name of the list and then the index of the element in square brackets.

#Getting the first element
first_user = users[0]
#Getting the second element
second_user = users[1]
#Getting the last element
newest_user = users[-1]

python accessing element

Modifying individual items

Once you've defined a list, you can change individual elements in a list. You do this by referring to the index of the item you want to modify.

#changing an element
users[0] = 'valerie'
users[-2] = 'ronald'

python modifying individual items

Adding elements

You can add elements to the end of a list, or you can insert them wherever you like in a list.
#Adding an element to the end of the list
#starting with an empty list
users = []
#Inserting elements at a particular position
users.insert(0, 'joe')
users.insert(3, 'bea')

python adding elements

Removing Elements

you can remove elements by their positions in a list, or by the value of the item. If you remove an item by its value. Python removes only the first item that has that value.

#Deleting an element by its  position
del users[-1]
#Removing an item by its value

python removing elements

Popping elements

If you want to work with an element that you're removing from the list, you can "pop" the element. If you think of the list as a stack of items. Pop() takes an item off the top of the stack. By default pop() returns the last element in the list, but you can also pop elements from any position in the list.

#Pop the last items from a list
most_recent_user = users.pop()
#Pop the first item in a list
first_user = users.pop(0)

python popping elements

List length

The len() function returns the number of items in a list.

#Find the length of a list
num_users = len(users)
print("we have " + str(num_users) + "users.")

List length

Sorting a list

The sort() method changes the order of a list permanently. The sorted() function returns a copy of the list, leaving the original list unchanged. You can sort the items in a list in alphabetical order, or reverse alphabetical order. You can also reverse the original order of the list. Keep in mind that lowercase and uppercase letters may affect the sort order.

#Sorting a list permanently
#sorting a list permanently in reverse alphabetical order
#sorting a list temporarily
print(sorted(users, reverse=True))
#Reversing the order of a list

python sorting list

Looping through a list

List can contain millions of item, so python provides an efficient way to loop through all the items in alist. When you set up a loop, python pulls each item from the list one at a time and stores it in a temporary variable, which you provide a name for. This name should be the singular version of the list name.

#Printing all items in a list
for user in users:
#Printing a message for each items, and a separate message afterwards
for user in users:
print("Welcome, " + user + "!")
	print("Welcome, we're glad to see you all!")

python looping list

Python Exception

Python Exceptions


Exceptions help you respond appropriately to errors that are likely to occur. You place code that might cause an  error in the try block. Code that should run in response to an error goes in the except block. Code that should run only if the try block was successful goes in the else block.

exception.py ( code )

#Catching an exception
prompt = "How many tickets do you need? "
num_tickets = input(prompt)

num_tickets = int(num_tickets)
except ValueError:
print("please try again.")
print("your tickets are printing.")

Example Screenshot 

Python Exception

Python Working With Files

Python Working With Files

Working With Files

Your Programs  can read fram files and write to files. Files are opened in read mode ('r') by default, but can also be opened in write mode  ('w') and append mode ('a').


#Reading a file and storing its lines
filename = 'journal.txt'
with open(filename) as file_object:
 lines = file_object.readlines()

for line in lines:
#Writing  to a file
filename = 'journal.txt'
with open(filename, 'w') as file_object:
 file_object.write("I love programming.")
#Appending to a file
filename = 'journal.txt'
with open (filename, 'w')  as file_object:
 file_object.write("\nI love making games.")

Screenshot Example 

python file handling


python file handling

Python Classes

Python Classes


A class defines the behavior of  an object and  the kind of  information an object can store. The  information in a class is stored in attributes, and functions that belong to a class are called methods from its parent class.

#Creating a dog class 
class Dog():
 """Represent a dog."""

 def __init__(self, name):
  """Initialize dog object."""
  self.name = name

 def sit(self):
  """simullate sitting."""
  print(self.name + " is sitting.")

my_dog = Dog('peso')

print(my_dog.name + " is a great dog!")

class SARDog(Dog):
 """Represent a search dog."""
 def __init__(self, name):
  """Initialize the sardog."""

 def search(self):
  """Simulate searching."""
  print(self.name + " is searching.")

my_dog = SARDog('wiillie')

print(my_dog.name + " is a search dog.")


python class


Python Function

Python Function


Function are named blocks of code. designed to do one specific job. Information passed to a function is called an argument, and information received by a function is called a parameter.

#A simple function
def greet_user():
 """Dislay a simple greeting."""

#calling function

#Passing an argument
def greet_user(username):
 """Display a personalized greeting."""
 print("Hello, " + username + "!")

#calling function

#Default values for parameters
def make_pizza(topping='bacon'):
 """Make a single-topping pizza."""
 print("Have a " + topping + " pizza!")

#calling function

#calling function

#Returning a value
def add_numbers(x, y):
 """Add two numbers and return the sum."""
 return x + y

sum = add_numbers(3, 5)


python function


Python While loop

Python While loop

While Loop

A while loop repeats a block of code as long as a certain condition is true.
#A simple while loop
current_value = 1
while current_value <= 5:
 current_value += 1

#Letting the user choose when to quit
msg = ''
while msg != 'quit':
 msg = input("what's your message? ")


while loop

Python User Input

Python User Input



User Input

Your programs can prompt the user for  input. All input is stored as a string.

#Prompting for a value 
name = input ("what's your name? ")
print("Hello, " + name + "!")
#Prompting for numerical input
age = input ("how old are you? ")
age = int(age)

pi = input("what's the value of pi? ")
pi = float(pi) 


python input


Python Dictionaries

Python Dictionaries


Dictionaries store connections between pieces of information. Each item in a dictionary is a key-value pair.

 #A simple dictionary 
alien = {'color': 'green' , 'point': 5}

#Accessing a value
print("The alien's color is " + alien['color'])

#Adding a new key-value pairs
alien ['x_position'] = 0

#looping through all key- value pairs
fav_numbers = {' eric ': 17, 'ever':4}
for name, number in fav_numbers.items():
 print(name + 'loves' + str (number))

#looping through all keys
fav_numbers = {'eric': 17, 'ever' : 4}
for name in fav_numbers.keys():
 print(name  + ' loves a number')

#looping through all the values
fav_numbers = {'eric': 17, 'ever': 4}
for number in fav_numbers.values():
 print(str(number) + ' is a favorite')


python dictionary


Python If Statements

Python If Statements


If statements are used to test for particular conditions and respond approptiately.

#conditional tests

print(x == 42)

#not equal 
print(x != 42)

#greater than 
print(x > 42)

#or loss equal to 
print(x <= 42)

#less than  
print(x > 42)

#or equal to 

print(x >= 42)

#conditional test with lists
print('trek' in bikes)
print('surly' not in bikes)

#Assigning boolean values
game_active = True
can_edit = False

#A simple if test
if age >= 18:
 print("you can vote!")

#If-elif-else statements
if age < 4:
 ticket_price = 0
elif age < 18:
 ticket_price = 10
 ticket_price = 15



python if statement