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 = []
dogs.append('willie')
dogs.append('hootz')
dogs.append('peso')
dogs.append('goblin')

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:
 print(old_dog)

del dogs[0]
dogs.remove('peso')
print(dogs)

Screenshot 

 

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
users.append('amy')
#starting with an empty list
users = []
users.append('val')
users.append('bob')
users.append('mia')
#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
users.remove('mia')




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()
print(most_recent_user)
#Pop the first item in a list
first_user = users.pop(0)
print(first_user)




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
users.sort()
#sorting a list permanently in reverse alphabetical order
users.sort(reverse=True)
#sorting a list temporarily
print(sorted(users))
print(sorted(users, reverse=True))
#Reversing the order of a list
users.reverse()



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:
print(user)
#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

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)

try:
num_tickets = int(num_tickets)
except ValueError:
print("please try again.")
else:
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').

python_file.py


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

for line in lines:
 print(line)
#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

journal.txt 


python file handling

Python Classes

Python Classes


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!")
my_dog.sit()

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

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

my_dog = SARDog('wiillie')

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

Screenshot

python class

 

Python Function

Python Function


Functions

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."""
 print("Hello!")

#calling function
greet_user()

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

#calling function
greet_user('jesse')



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

#calling function
make_pizza()

#calling function
make_pizza('pepperoni')

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

sum = add_numbers(3, 5)
print(sum)

Screenshot

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:
 print(current_value)
 current_value += 1


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

Screenshot

while loop
 

Python User Input

Python User Input

python

 


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) 

Screenshot

python input

 

Python Dictionaries

Python Dictionaries



Introduction

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

Screenshot 

python dictionary

 

Python If Statements

Python If Statements



Introduction

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

#conditional tests
x=10
bikes=['ok','lo','trek']
age=11


#equal
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
else:
 ticket_price = 15

print(ticket_price)

Screenshot

 
python if statement