Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Organization of README.md and renomeation of programs name #31

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,23 @@
# Learn-Python
To make the users familiar with the syntax of Python.

Samples:

- [class](/Learn-Python/class.py)
- [dicts](/Learn-Python/dicts.py)
- [exceptions](/Learn-Python/exceptions.py)
- [factorial](/Learn-Python/factorial.py)
- [file](/Learn-Python/file.py)
- [func](/Learn-Python/func.py)
- [game](/Learn-Python/game.py)
- [generators](/Learn-Python/generators.py)
- [import](/Learn-Python/import.py)
- [input](/Learn-Python/input.py)
- [list](/Learn-Python/list.py)
- [comprehension lists](/Learn-Python/comprehension_lists.py)
- [loops](/Learn-Python/loops.py)
- [methods input](/Learn-Python/methods_input.py)
- [permutation](/Learn-Python/permutation.py)
- [print](/Learn-Python/print.py)
- [tuples](/Learn-Python/tuples.py)
- [while](/Learn-Python/while.py)
23 changes: 23 additions & 0 deletions class.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# SAMPLE CODE TO ILLUSTRATE CLASSES IN PYTHON



class TheThing(object):
def __init__(self):
self.number = 0
def some_function(self):
print "I got called."
def add_me_up(self, more):
self.number += more
return self.number
# two different things
a = TheThing()
b = TheThing()
a.some_function()
b.some_function()
print a.add_me_up(20)
print a.add_me_up(20)
print b.add_me_up(30)
print b.add_me_up(30)
print a.number
print b.number
23 changes: 23 additions & 0 deletions dicts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# SAMPLE CODE TO UNDERSTAND THE CONCEPT OF DICTIONARIES IN PYTHON

cities = {'CA': 'San Francisco', 'MI': 'Detroit','FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def find_city(themap, state):
if state in themap:
return themap[state]
else:
return "Not found."
# ok pay attention!

cities['_find'] = find_city

while True:
print "State? (ENTER to quit)",
state = raw_input("> ")
if not state: break

# this line is the most important ever! study!

city_found = cities['_find'](cities, state)
print city_found
90 changes: 90 additions & 0 deletions exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# python sampleexceptions.py

# Minimal types of exceptions are used in this sample.
# For a list of built in python exceptions see https://docs.python.org/2/library/exceptions.html


# Expected Output:
#
# Basic exception raised.
# Basic exception with message: ERROR.
# Caught non basic exception: No module named badimport.
# Caught non basic exception: unsupported operand type(s) for +: 'int' and 'str'.
# Demonstrated how to handle multiple types of exceptions the same way.
# Demonstrated how to handle multiple types of exceptions the same way with a message: No module named badimport.
# Demonstrated how to handle exceptions differently.
# This should appear.
# Demonstrated how finally is run after exceptions.
# Demonstrated how else is run when no exceptions occur.
# Demonstrated how to use a basic custom exception: Custom Exception.


try:
raise Exception
except:
print "Basic exception raised."


try:
raise Exception("ERROR")
except Exception as e:
print "Basic exception with message: %s." % str(e)


try:
import badimport
except ImportError as e:
print "Caught non basic exception: %s." % str(e)


try:
test = 1 + '1'
except TypeError as e:
print "Caught non basic exception: %s." % str(e)


try:
import badimport
except ImportError, TypeError:
print "Demonstrated how to handle multiple types of exceptions the same way."


try:
import badimport
except (ImportError, TypeError) as e:
print "Demonstrated how to handle multiple types of exceptions the same way with a message: %s." % str(e)


try:
import badimport
except ImportError:
print "Demonstrated how to handle exceptions differently."
except TypeError:
print "This should not appear."


try:
import badimport
except ImportError:
print "This should appear."
finally:
print "Demonstrated how finally is run after exceptions."


try:
test = 1 + 1
except:
print "This should not appear."
else:
print "Demonstrated how else is run when no exceptions occur."


class CustomBasicError(Exception):
""" Custom Exception Type - Can be customised further """
pass


try:
raise CustomBasicError("Custom Exception")
except CustomBasicError as e:
print "Demonstrated how to use a basic custom exception: %s." % str(e)
9 changes: 9 additions & 0 deletions factorial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
def fatorial(n):
if(n == 0 or n == 1):
return 1
else:
return fatorial(n-1)*n

n = int(input("Please, enter the numb: "))
fatorial(n)
print(fatorial(n))
9 changes: 9 additions & 0 deletions file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from sys import argv
script , filename =argv
txt=open(filename)
print "here is your file %r" %filename
print txt.read()
print "i'll also ask you to type it again"
fi=raw_input("> ")
tx=open(fi)
print tx.read()
8 changes: 8 additions & 0 deletions func.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def multiply(a,b):
c=a*b
print "product is %r" %c
def add(a,b):
e=a+b
print "addition is %r" %e
multiply(3,4)
add(3,4)
66 changes: 66 additions & 0 deletions game.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# SAMPLE CODE TO ILLUTRATE THE CONCEPT OF BRANCHES AND FUNCTIONS IN PYTHON
# Users are advised to go through this piece of code and dry run it to get an understanding of function calls.

from sys import exit
def gold_room():
print "This room is full of gold.How much do you take?"
next = raw_input("> ")
if "0" in next or "1" in next:
how_much = int(next)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
def bear_room():
print "There is a bear here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
bear_moved = False
while True:
next = raw_input("> ")
if next == "take honey":
dead("The bear looks at you then slaps your face off.")
elif next == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved = True
elif next == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your leg off.")
elif next == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means."

def cthulu_room():
print "Here you see the great evil Cthulu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee for your life or eat your head?"
next = raw_input("> ")
if "flee" in next:
start()
elif "head" in next:
dead("Well that was tasty!")
else:
cthulu_room()

def dead(why):
print why, "Good job!"
exit(0)

def start():
print "You are in a dark room."
print "There is a door to your right and left."
print "Which one do you take?"
next = raw_input("> ")
if next == "left":
bear_room()
elif next == "right":
cthulu_room()
else:
dead("You stumble around the room until you starve.")

start()

47 changes: 47 additions & 0 deletions generators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Generators hold values that are fetched lazily.
# Meaning that the entire collection isn't stored
# in memory all at once, but rather retrieved when
# needed.

# This is best used when dealing with a large
# collection of items. Such as rows returned from
# a database call or looping over a large csv.

# Generators are intelligent enough to handle these
# large collections without running out of memory.
# They dispose of variables in memory that are no
# longer used and do not worry about variables
# that are not yet needed.

# Here's the syntax for a generator. It's just a
# function! Take note of the yield keyword. yield
# basically means 'return', but lets Python know
# we'll be coming back for more.
def color_generator():
yield 'blue'
yield 'orange'
yield 'yellow'
yield 'purple'

# One way to use generators is by calling `next()`
# on it's instance
g = color_generator() # create the instance
next(g) # 'blue'
next(g) # 'orange'
next(g) # 'yellow'
next(g) # 'purple'

# However, once a generator is exhausted, it will
# not start back at the beginning.
next(g) # Raises StopIteration error.

# They're also iterables. No StopIteration errors
# are thrown with this method.
for color in color_generator():
print(color)

# 'blue'
# 'orange'
# 'yellow'
# 'purple'

32 changes: 32 additions & 0 deletions import.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# import command line argument reader 'argv' from the 'sys' python module
from sys import argv

# takes the two arguments after the 'python' command,
# and assigns to the variables 'script' and 'user_name'
script, user_name = argv

# assigns the string with an arrow and space to the variable 'prompt'
prompt = '> '

# user_name, the second argument, and 'sampleimport.py' replace %s in the order listed
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."

# replaces %s with the variable user_name and prints
print "Do you like me %s?" % user_name

# prints '> ' and allows user to input a value, assigns user input to the 'likes' variable
likes = raw_input(prompt)

# repeats the process above two more times
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)

# takes the last three user inputs in order and inserts into the last print statement, replacing %r
print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)
12 changes: 12 additions & 0 deletions input.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# import command line argument reader 'argv' from the 'sys' python module
from sys import argv

# takes the four arguments after the 'python' command,
# and assigns to the variables 's', 'f', 'ss', and 't'
s,f,ss,t=argv

# prints the four arguments on separate lines with text
print "the script is" , s
print "var1 1 is" , f
print "var 2 is" , ss
print "var 3 is" , t
24 changes: 24 additions & 0 deletions listcomprehension.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Hi! Welcome to this mini tutorial on using list comprehensions in Python!
# Check out samplelists.py if you need help with lists.

# Starting off with list comprehensions!
# Syntax used to make an ordinary list:
my_list = ["apple", "banana", "pear", "peach"]

# To concisely make a new list of elements, use a list comprehension:
list_comp = [num for num in range(10)] # Notice how square brackets are
# used to create a list.
print list_comp

# List comprehension syntax can be understood as so:
# [num for num in range(5)]
# Make a new num for each num in given range

# The first expression (before the "for" keyword) can be altered to satisfy a
# given condition over an iterable.
doubled_list_comp = [num * 2 for num in list_comp]
print doubled_list_comp

# Furthermore, "if" statements can be used in list comprehensions as well.
even_num_list_comp = [num for num in list_comp if num % 2 == 0]
print even_num_list_comp
Loading