+ All Categories
Home > Documents > Python Key concepts in Python to help your progression through the coursework element. REMEMBER:...

Python Key concepts in Python to help your progression through the coursework element. REMEMBER:...

Date post: 29-Dec-2015
Category:
Upload: arline-douglas
View: 225 times
Download: 0 times
Share this document with a friend
28
Python Key concepts in Python to help your progression through the coursework element. REMEMBER: This PowerPoint is supposed to support your learning and all the exercises link to the exercises found on the website below. Use the study drills to cement your learning.: http://learnpythonthehardway.org/book / Next Page
Transcript

PythonKey concepts in Python to help your

progression through the coursework element.REMEMBER: This PowerPoint is supposed to

support your learning and all the exercises link to the exercises found on the website below. Use the study drills to cement your learning.:

http://learnpythonthehardway.org/book/

Next Page

Learning PythonLearn Python The Hard Way

1: Using Print 2: Using Comments 3: Numbers and Sums4: Variables and Names 5: More Variables, Making

Strings6: Strings and Text

7: Print Varieties 8: Complex Printing 9: Printing Again10a: New Line Characters and Escaping Quotations

10b: New Line Characters and Escaping Quotations

11: Asking Questions/User Input

12a: Prompting Users 12b: Prompting Users 13: Parameters and Variables

18: Functions: Defining and Naming

19: Functions and Variables 21: Functions and Returning

29a: IF Statements 29b: IF Statements 30a: ELSE and IF Statements

30b: ELSE and IF Statements

31a: Making Decisions 31b: Making Decisions

31a: While Loops 31b: While Loops

Contents

1: Using Print

• The print function is one of the most used functions in Python. It will basically print whatever you put in the speech marks in the IDLE. Give it a go:

–print(“Hello World”)

Contents

2: Using Comments

• Comments are use to tell you what something does in plain English. They help you track your program. Nothing after the hashtag will appear in your actual code or have any effect on your program. They are purely used to support people editing or writing the programs. Try this:

–#This shouldn’t appear in your program–print(“This should appear in your

program”)

Contents

3: Numbers and Sums

• You can perform basics operations in Python using the same commands as used on slide 1, the print function. If you try the following examples to see what happens:

–print(3+2)–print(“You can combine numbers with text”,3+2)–print(“What is 3+2?”,3+2)

Contents

4: Variables and Names

• Variables let you name reoccurring functions. This makes things quicker to write and easier to remember and write as it reads like standard English. You should always define your variables at the top before writing your program. REMEMBER, don’t use spaces_use_underscores.

–phones=50–tablets=100–print(phones+tablets)–print(tablets-phones)

Contents

5: More Variables, Making Strings.

• Making your variables and print functions more advanced will help you organise your program and structure your variables. Formatting variables using the % key helps your to better organise writing. Any string needs to finish %s, any decimal needs to finish %d like the examples below:

– my_age=25– my_height=185– my_name=“Mr Brown”– print(“Lets talk about my age, which is %d” %(my_age))– print(“My name is %s” %(my_name))– print(“What's my height %d multiplied by my age %d?, I believe

the answer is: %(my_height, my_age, my_height*my_age))

Contents

6: Strings and Text

• A string is a piece of text you want to display or “export” out of the program. Python knows the things you are writing are a string when you put “ or ‘ around the text. You can list lots of formatted strings together using () and , like this: (my_age, my_height)

– x=“There are %d people here.”%10– binary=“Binary”– do_not=“Don’t”– y=“Some people get %s and some people %s.”%(binary,

do_not)– print (x)– print (y)

Contents

7: Print Varieties

• Using *will copy whatever appears in your “” by the following number so:– print(“.”*20)#Should place twenty full stops in a row

• You can also use variables to create single words like this:– letter1=“L”– letter2=“o”– letter3=“o”– letter4=“k”– letter5=“N”– letter6=“o”– letter7=“w”– print(letter1+letter2+letter3+letter4,)– print(letter5+letter6+letter7)

Contents

8: Complex Printing

• Complicated printing can be assisted by formatting strings. Try this code to see what happens. Break it down using comments so you can really understand it:– formatter=“%r%r%r%r”– print(formatter%(“one”,”two”,”three”,”four”))– print(formatter%(True,False,True,False))– print(formatter%(formatter,formatter,formatter,formatter))– print(formatter%(

“I Can”,“Write Code”,“Over Multiple”,“Lines”

))

Contents

9: Printing Again

• Here's as example of code. Run it and use comments to try and show your understanding:– days=“Mon, Tue, Wed, Thu, Fri, Sat, Sun”– months=“Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\

nSep\nOct\nNov\nDec”– print(“Here are the days of the week: “,days)– print(“Here are the months of the year: “,months)– print”””Using the three quotation marks letsYou write over multiple lines.You can write as much as you like.As many lines as you want.– “””

Contents

10a: New Line Characters and Escaping Quotations

• The \n helps Pyton understand that you want each word on a new line without being separated by lines.

• Another useful tool is how to escape or cheat your way out of quotations. If you need to use quotations when writing a string it might confuse Python so you’ll need to escape the quotes like use a backslash before the quote you are using, like this:– print("I am 6'2\" tall.“) # escape double-quote inside string – print('I am 6\'2" tall.‘) # escape single-quote inside string

• Another option is to use the “”” triple speech mark escape we say in tutorial number 9. (go to 10b to see some example code)

Contents

10b: New Line Characters and Escaping Quotations

• Example code from 10a:– tabbed_in_code=“\tI’m tabbed in.”– splitting_lines=“I’m split\non different lines.”– including_backslashes=“This\\lets\\you\\slash”– tabbed_listings=“””I’ll do a list:\t*Cheese\t*Eggs\t*Milk\t*Dignity“””– print(tabbed_in_code)– print(splitting_lines)– print(including_backslashes)– print(tabbed_listings)

• Feeling cocky, try this: – while True: for i in ["/","-","|","\\","|"]: print "%s\r" % i,

Contents

11: Asking Questions/User Input

• This helps you to use the print function with user inputs. Use this ask questions to your user.– print(“How old are you?”)– age=raw_input()– print(“How tall are you in centimetres?”)– height=raw_input()– print(“So, you’re %r years old and %r

centimetres tall.”%(age, height))

Contents

12a: Prompting Users

• You can prompt users to answer particular questions and record their answers as variables. This uses the () parenthesis to help structure the code like this:– y=raw_input(“Your name is? “)– print(y)

• This would then result in the question “Your name is?” and the variable y will be set by the users answers typed in.

In part 12b we will look at a longer example of this programming.

Contents

12b: Prompting Users

• Here is a more detailed example of an input code that prompts users:– age=raw_input(“How old are you? “)– height=raw_input(“How tall are you in

CM? “)– weight=raw_input(“How much do you

weigh in KG? “)– print(“So, you’re %r years old, %r

centimetres tall and %r Kilos in weight.”%(age, height, weight))

Contents13: Parameters and

Variables• Parameters, Unpacking and Hold Up

Features all have a different running focuses.

• Try to focus on the following tutorials to assist you with your understanding of this section:

Click here to visit the webpage

Contents

18: Functions: Defining and Naming

• Functions are descriptions. They work in much the same way as variables except variables work for strings and numbers and functions will work for pieces of code. To create a function you need to DEFine the object using a def tag. The top one requires arguments and the bottom should work without. Be careful to indent the code included in your function.– def(print_one()):print(“I aint got nothin!”)– def(print_two(*args)):arg1, arg2 = argsprint(“arg1:%r, arg2:%r”%(arg1, arg2)

• The symbol break downs can be found HERE.

Contents19: Functions and

Variables• There are many ways to give functions their values. The most

important things to remember are to indent the text when inside the function. Normal action like print won’t need to be indented otherwise.– def cheese_and_crackers(cheese_count, boxes_of_crackers):print ("You have %d cheeses!" % (cheese_count)) print ("You have %d boxes of crackers!" % (boxes_of_crackers)) print ("Man that's enough for a party!“) print ("Get a blanket.\n“) – print ("We can just give the function numbers directly:"

cheese_and_crackers(20))– print ("OR, we can use variables from our script:" amount_of_cheese =

10 amount_of_crackers = 50)– cheese_and_crackers(amount_of_cheese, amount_of_crackers) – print ("We can even do math inside too:" cheese_and_crackers(10 +

20, 5 + 6))– print ("And we can combine the two, variables and math:"

cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000))

Contents21: Functions and

Returning• We have been assigning values to things within functions in previous

exercises, now we’re going to use a new keyword: return to create a value from a function, not for a function.– def add(a, b):

print ("ADDING %d + %d" % (a, b)) return a + b

– def subtract(a, b): print ("SUBTRACTING %d - %d" % (a, b))return a - b

– def multiply(a, b): print ("MULTIPLYING %d * %d" % (a, b))return a * b

– def divide(a, b): print ("DIVIDING %d / %d" % (a, b)) return a / b

– print ("Let's do some math with just functions!“) age = add(30, 5) height = subtract(78, 4) weight = multiply(90, 2) IQ = divide(100, 2)

– print ("Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, IQ))

Contents

29a: IF Statements

• IF statements help you to set up rules for your python to follow. IF statements are an easy way to make python select the correct information from set criteria. On the next page there is an example programme to run.

Contents

29b: IF Statements– people = 20 – cats = 30 – dogs = 15 – if people < cats:

print ("Too many cats! The world is doomed!“)– if people > cats:

print ("Not many cats! The world is saved!“)– if people < dogs:

print ("The world is drooled on!“)– if people > dogs:

print ("The world is dry!“)– dogs += 5 – if people >= dogs:

print ("People are greater than or equal to dogs.“) – if people <= dogs:

print ("People are less than or equal to dogs.“)– if people == dogs:

print ("People are dogs.“)

Contents30a: ELSE and IF

Statements• Sometimes writing IF statements

alone can be too long winded. You may need several if statements to cover all potential solutions. To restrict the effect of this we can use ELIF and ELSE statements which let us say: if this happens say this or ELSE say this other thing or even this final option.

Contents30b: ELSE and IF

Statements– people = 30 – cars = 40 – trucks = 15 – if cars > people:

print ("We should take the cars.“) – elif cars < people:

print ("We should not take the cars.“) – else:

print ("We can't decide.“) – if trucks > cars:

print ("That's too many trucks.“) – elif trucks < cars:

print ("Maybe we could take the trucks.“) – else:

print ("We still can't decide.“) – if people > trucks:

print ("Alright, let's just take the trucks.“) – else:

print ("Fine, let's stay home then.“)

Contents

31a: Making Decisions

• Remember the import thing about If, Else and Elif is the indenting. You need to make sure all actions inside each statement are indented. Returning to the original left alignment will start a new function.

• Some new symbols (==) are included in the next code. The full explanation of all these symbols can be found HERE.

Contents

31b: Making Decisionsprint ("You enter a dark room with two doors. Do you go through door #1 or door #2?“) door = raw_input("> ")if door == "1":

print ("There's a giant bear here eating a cheese cake. What do you do?“) print ("1. Take the cake.“) print ("2. Scream at the bear.“) bear = raw_input("> ") if bear == "1": print ("The bear eats your face off. Good job!“)

elif bear == "2": print ("The bear eats your legs off. Good job!“) else: print ("Well, doing %s is probably better. Bear runs away.“) % bear

elif door == "2": print ("You stare into the endless abyss at Cthulhu's retina.“) print ("1. Blueberries." print "2. Yellow jacket clothespins.“) print ("3. Understanding revolvers yelling melodies.“) insanity = raw_input("> ") if insanity == "1" or insanity == "2": print ("Your body survives powered by a mind of jello. Good job!“) else: print ("The insanity rots your eyes into a pool of muck. Good job!“)

else: print ("You stumble around and fall on a knife and die. Good job!“)

Contents

33a: While Loops

• While loops set rules that keep testing (looping) the programme until the logic test is matched for example if we did a test that said: while i<6: the loop will continue going until I is equal to or greater than 6.

Contents

33b: While Loops

– i = 0 – numbers = [] – while i < 6: • print "At the top i is %d" % I• numbers.append(i) • i = i + 1 • print "Numbers now: ", numbers • print "At the bottom i is %d" % i

– print "The numbers: " – for num in numbers: print num


Recommended