89 views

Uploaded by DeepakPrabhu

python

- Python Programming for Biology_ - Tim J. Stevens
- (eBook) Introduction to Numerical Analysis - J.Stoer,R.Bulirsch
- Python
- Numerical Sim of Earth Dam
- Numerical Methods for Nonlinear Lumped Models
- Numerical Methods for Engineers 5E Chapra
- How Will It Move? (PS3) - Teacher Edition
- Python AOS
- The Fall of Israel in 2022 AD a Prophecy or a Numerical Coincidence by Bassam Nihad Jarrar
- Matlab Python
- 5118.Numerical Computing With IEEE Floating Point Arithmetic by Michael L. Overton
- Andrew Jason Penner- Numerical Analysis of the Ultrarelativistic and Magnetized Bondi–Hoyle Problem
- A Friendly Introduction to Numerical Analysis
- Python Programming by Example - Agus Kurniawan
- 4 Basic Python
- Mastering Weave Structures
- pycse
- Dahlquist G., Bjorck a. Numerical Methods
- A Billion Random Numerals - Nikolai Rumavlef
- Numerical Methods for Solving Elliptic Boundary Value Problems

You are on page 1of 75

Numbers & Variables

Why Python?

Easy to read

jeremykun.com

Fast

Versatile

Frets on Fire

fretsonre.sourceforge.net

>>>

This symbol points to the outcome

>>>

30.5

30.5

Mathematical Operators

addition

>>>

3 + 5

subtraction

>>>

multiplication

>>>

3 * 5

division

>>>

15

exponent

>>>

2 ** 3

8

10 - 5

30 / 6

5

negation

>>>

-2 + -3

-5

Heres a little Python terminology.

int

>>>

35

35

An int is a

whole number

oat

>>>

30.5

30.5

A float is a

decimal number

Order of Operations

These are the calculations happening rst.

>>>

Behind

the

scenes

( 5 + 7 )

12

* 3

* 3

36

>>>

5 + 7 * 3

5 + 21

26

Lets use some math to gure out if this swallow can carry this coconut!

What we know: A swallow weighs 60g and can carry 1/3 of its weight.

Swallows weight in grams

>>>

Divide by 3

60 / 3

20

but a coconut weighs 1450 grams

Lets try to gure out how many swallows it takes to carry 1 coconut.

What we know: A swallow weighs 60g and can carry 1/3 of its weight.

Coconut weight

>>>

Swallows weight

Divide by 3

1450 / 60 / 3

8.06

Lets look at what happened behind the scenes:

1450 / 60 / 3

24.17

/ 3

How many swallows does it take to carry 1 coconut?

What we know: A swallow weighs 60g and can carry 1/3 of its weight.

Coconut weight

>>>

Swallows weight

Divide by 3

1450 / ( 60 / 3 )

1450 / ( 20 )

72.5

Lets see if we can get closer to 1 swallow with other fruits.

>>>

1450 / ( 60 / 3 )

72.5

>>>

128 / ( 60 / 3 )

6.4

>>>

8 / ( 60 / 3 )

repeating this a lot

0.4

Great!

We found one that

works!

Use variables to store a value that can be used later in your program.

>>>

swallow_limit = 60 / 3

variable name

value to store

>>>

1450 / swallow_limit

>>>

128 / swallow_limit

6.4

>>>

8 / swallow_limit

0.4

More organized

72.5

Variables keep your code more readable and assign meaning to values.

>>>

swallow_limit = 60 / 3

>>>

swallows_per_cherry

num_per_cherry == 8 / swallow_limit

>>>

swallows_per_cherry

0.4

As long as youre not breaking these rules, you can name variables anything you want!

no spaces = 0

3mice, $mice

no digits or special characters in front

swallow_limit

swallowLimit

Step 1: Declare variables for each value and nd out the macaws carrying limit.

>>>

perc = 1/3

>>>

coco_wt = 1450

>>>

macaw_wt = 900

>>>

>>>

macaw_limit

300

are descriptive,

but were still using

abbreviations where

appropriate.

Step 2: Divide the coconuts weight by the limit.

>>>

perc = 1/3

>>>

coco_wt = 1450

>>>

macaw_wt = 900

>>>

>>>

num_macaws = coco_wt/macaw_limit

>>>

num_macaws

4.8

Occasionally, we will want to use modules containing functionality that is not built in to

the Python language.

This is importing extra math functions

>>>

import math

>>>

num_macaws = 4.8

>>>

math.ceil(num_macaws)

Step 3: Use the ceiling function to round up.

>>>

import math

>>>

perc = 1/3

>>>

coco_wt = 1450

>>>

macaw_wt = 900

>>>

>>>

num_macaws = coco_wt/macaw_limit

>>>

math.ceil(num_macaws)

5

Level 2

Strings

Creating Strings

Strings are a sequence of characters that can store letters, numbers, or a combination anything!

string

>>>

'Hello World'

'Hello World'

just be consistent

string

>>>

"SPAM83"

'SPAM83'

We can combine (or concatenate) strings by using the + operator.

>>>

first_name = 'Monty'

>>>

last_name = 'Python'

>>>

>>>

full_name

'MontyPython'

Concatenating a Space

We can

>>>

first_name = 'Monty'

>>>

last_name = 'Python'

>>>

>>>

full_name

'Monty Python'

concatenate a

space character

bet ween the words

>>>

first_name = 'Monty'

>>>

last_name = 'Python'

>>>

>>>

full_name

script.py

first_name = 'Monty'

last_name = 'Python'

full_name = first_name + ' ' + last_name

But how can we output the value of full_name?

on the command line

Everything in

1 script:

script.py

first_name = 'Monty'

last_name = 'Python'

full_name = first_name + ' ' + last_name

print(full_name)

Prints whatever is

inside the ()

Monty Python

print(first_name, last_name)

Monty Python

print() as many things as you want,

just separate them with commas

bet ween arguments

In Python 2,

print doesnt need ()

print full_name

script.py

first_name = 'Monty'

last_name = 'Python'

full_name = first_name + ' ' + last_name

print(full_name)

Put the name of your script file here

>>>

python script.py

Monty Python

scripts

Lets write a script to describe what Monty Python is.

script.py

name = 'Monty Python'

description = 'sketch comedy group'

year = 1969

i s a c omme

do e s nt ge t

r un

n t and

When we try to concatenate an int, year, with a string, we get an error.

script.py

name = 'Monty Python'

description = 'sketch comedy group'

year = 1969

Year is an int,

not a string

# Introduce them

sentence = name + ' is a ' + description + ' formed in ' + year

script.py

name = 'Monty Python'

description = 'sketch comedy group'

year = '1969'

and make the year a

string instead of an int

# Introduce them

sentence = name + ' is a ' + description + ' formed in ' + year

This will work, but it really makes sense to keep numbers as numbers.

script.py

name = 'Monty Python'

description = 'sketch comedy group'

year = 1969

Instead, convert

when we

concatenate

with str()

# Introduce them

sentence = name + ' is a ' + description + ' formed in ' + str( year)

print(sentence)

Monty Python is a sketch comedy group formed in 1969

script.py

name = 'Monty Python'

description = 'sketch comedy group'

year = 1969

conversions for us

# Introduce them

print(name, 'is a', description, 'formed in', year)

script.py

famous_sketch = 'Hell's Grannies'

quote has ended and

doesnt know what S is

script.py

famous_sketch1 = "Hell's Grannies"

print(famous_sketch1)

Hell's Grannies

Start with

''

instead

'

the end of the string

We want to add some more sketches and print them out

script.py

famous sketch

famous_sketch1 = "Hell's Grannies"

famous_sketch2 = 'The Dead Parrot'

print(famous_sketch1, famous_sketch2)

This works, but we want to format it better.

\n is a special character that means new line.

script.py

famous_sketch1 = "\nHell's Grannies"

famous_sketch2 = '\nThe Dead Parrot'

print('Famous Work:', famous_sketch1, famous_sketch2)

Famous Work:

Hell's Grannies

The Dead Parrot

This works, but we want to indent the titles.

Add a newline

to make this look better

\t is a special character that means tab.

script.py

famous_sketch1 = "\n\tHell's Grannies"

famous_sketch2 = '\n\tThe Dead Parrot'

print('Famous Work:', famous_sketch1, famous_sketch2)

Famous Work:

Hell's Grannies

The Dead Parrot

make this look even

better

A string is a list of characters, and each character in this list has a position or an index.

greeting = 'H E L L O

W O R L D !'

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10][11]

Starts at 0

>>>

greeting[0]

'H'

calling its index with []

>>>

greeting[11]

'!'

>>>

greeting[12]

There are a few built-in string functions like len(), which returns the length of a string and is very useful.

'H E L L O

W O R L D !'

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

script.py

print( len(greeting) )

12

12

Go

od

Ev

en

ing

'G o o d'

'E v e n i n g'

script.py

od ning

word1 = 'Good'

end1 = word1[2] + word1[3]

print(end1)

characters at positions

[2] and [3]

od

Boundary

ends before

index 5

Boundary

starts before

index 2

word =

"P y t h o n"

[0] [1] [2] [3] [4] [5]

>>>

word[2:5]

Start

boundary

End

boundary

tho

slice formula: variable [start : end+1]

Go

Go

od

Go

od

od

>>>

Shortcuts:

>>>

word1[0:2]

Go

>>>

word1[:2]

Go

word1[2:4]

o

Gd

o

>>>

word1[2:]

od

Go

'G o o d'

'E v e n i n g'

script.py

od

od

word1 = 'Good'

end1 = word1[2] + word1[3] word1[2:4]

print(end1)

Replace this with a slice

od

Go

od

Ev

'G o o d'

'E v e n i n g'

script.py

en

ing

word1 = 'Good'

end1 = word1[2:]

od ning

word2 = 'Evening'

end2 = word2[3:]

shortcut

print(end1, end2)

od ning

It would be great if we didnt have to know the halfway points were at 2 and 3

The len() function will let us calculate the halfway index of our word.

Go

script.py

od

Ev

en

ing

word1 = 'Good'

half1 = len(word1)/2

word2 = 'Evening'

half2 = len(word2)/2

half1 is 2.0

half2 is 3.5

integers floats wont work!

od ning

'G o o d'

[0] [1] [2] [3]

'E v e n i n g'

[0] [1] [2] [3] [4] [5] [6]

division. Be consistent if

we cover in Level 1.

'G o o d'

script.py

half1 is

4//2 = 2

word1 = 'Good'

half1 = len(word1)//2

half2 is

7//2 = 3

word2 = 'Evening'

half2 = len(word2)//2

'E v e n i n g'

[0] [1] [2] [3] [4] [5] [6]

nearest integer

In Python 2,

single division /

is int division unless

there are floats involved

Calculating the halfway index makes our logic reusable.

script.py

half1 is

4//2 = 2

word1 = 'Good'

half1 = len(word1)//2

end1 = word1[2:]

word1[half1:]

half2 is

7//2 = 3

word2 = 'Evening'

half2 = len(word2)//2

end2 = word2[3:]

word2[half2:]

print(end1, end2)

Go

od

Ev

en

ing

od ning

'G o o d'

[0] [1] [2] [3]

'E v e n i n g'

od ning

Level 3

Conditionals & Input

if there's less than 3 knights

Retreat!

Trojan Rabbit!

otherwise

Comparison Operators

There are 6 comparators in Python:

<

<=

less than

equal to

less than

==

equal to

Is 5 less than 10 ??

>>>

5 < 10

5 == 10

greater than

equal to

>

greater than

True

Is 5 equal to 10 ??

>>>

>=

>>>

name = 'Pam'

>>>

name == 'Jim'

!=

not

equal to

Setting the name variable

equal to 'Pam'

False

False

>>>

name != 'Jim'

True

Heres the output of evaluating all 6 comparisons:

>>>

5 < 10

>>>

True

>>>

5 <= 10

True

5 == 10

>>>

False

>>>

5 != 10

True

5 > 10

False

>>>

5 >= 10

False

Booleans

In programming, a boolean is a type that can only be True or False.

booleans

True

False

>>>

is_raining = True

>>>

is_raining

True

An if statement lets us decide what to do: if True, then do this.

script.py

# Battle Rules

num_knights = 2

True

if num_knights < 3:

print('Retreat!')

print('Raise the white flag!')

comes after an if

statement is called a

code block

Retreat!

Raise the white flag!

If True:

Then do this

Then this

An if statement lets us decide what to do: if False, then dont do this.

script.py

# Battle Rules

num_knights = 4

False

if num_knights < 3:

print('Retreat!')

print('Raise the white flag!')

Because the

conditional is False,

this block doesnt run

s

n

e

p

p

a

h

g

n

i

h

t

o

N

*

s

t

e

k

*c r i c

The code continues to run as usual, line by line, after the conditional block.

script.py

# Battle Rules

num_knights = 4

False

if num_knights < 3:

print('Retreat!')

print('Raise the white flag!')

print('Knights of the Round Table!')

but the code right

outside of the block

still does

Always this

In Python, indent with 4 spaces. However, anything will work as long as youre consistent.

Irregular spacing is

a no-no!

2 spaces

4 spaces

if num_knights == 1:

# Block start

print('Do this')

print('And this')

print('Always this')

Retreat!

otherwise

Conditional if False

else

script.py

# Battle Rules

num_knights = 4

if num_knights < 3:

print('Retreat!')

else:

print('Truce?')

Truce?

then run the indented code below

Otherwise,

then run the indented code below

script.py

# Battle Rules

num_knights = 10

if num_knights < 3:

print('Retreat!')

else:

print('Truce?')

Truce?

then Trojan Rabbit

script.py

Else sequences

will exit

as soon as a

statement is True

# Battle Rules

num_knights = 10

day = 'Wednesday'

if num_knights < 3:

print('Retreat!')

elif num_knights >= 10:

print('Trojan Rabbit')

and continue

the program after

print('Taco Night')

else:

print('Truce?')

We can have multiple elifs

Trojan Rabbit

King Arthur has decided:

(were renting it out on other days)

if num_knights < 3:

print('Retreat!')

print('Trojan Rabbit!')

OR

AND

if its a Monday

its Wednesday

Retreat!

Trojan Rabbit!

On all Mondays, or if we have less than 3 knights, we retreat.

OR

If its a Monday

print('Retreat!')

Wednesday on the next

slide.

We can only use the Trojan Rabbit if we have at least 10 knights AND its Wednesday.

AND

If its a Wednesday

print('Trojan Rabbit!')

Make it possible to combine comparisons or booleans.

If 1 is False

and result will be False

If 1 is True

or result will be True

True

and

True

True

True

and

False

False

False

and

False

False

True

or

True

True

True

or

False

True

False

or

False

False

script.py

# Battle Rules

num_knights = 10

day = 'Wednesday'

if num_knights < 3 or day == 'Monday':

print('Retreat!')

elif num_knights >= 10 and day == 'Wednesday':

print('Trojan Rabbit!')

else:

print('Truce?')

script.py

day = input('Enter the day of the week')

and waits for user input

In Python 2,

raw_input() is used

instead of input()

Just like we can print() text to the console, we can also get user input from the console.

script.py

num_knights = int(input('Enter the number of knights'))

if num_knights < 3 or day == 'Monday':

print('Retreat!')

You entered: 10

10

User enters 10

script.py

Different user input

causes different

program flow:

# Battle Rules

num_knights = int(input('How many knights?'))

day = input('What day is it?'))

1st run

print('Retreat!')

elif num_knights >= 10 and day == 'Wednesday':

print('Trojan Rabbit!')

else:

print('Truce?')

2nd run

1st run

Tuesday

Retreat

2nd run

12 2

Wednesday

Trojan Rabbit!

num_knights < 3

killer bunny

Holy

Hand Grenade

num_knights >= 10

otherwise

script.py

# Battle Rules

num_knights = int(input('Enter number of knights')

day = input('Enter day of the week')

enemy = input('Enter type of enemy')

is the killer bunny

print('Holy Hand Grenade!')

else:

Do the original battle rules here

If not,

then use the

original battle rules

print('Retreat!')

if num_knights >= 10 and day == 'Wednesday':

print('Trojan Rabbit!')

else:

print('Truce?')

Nested Conditionals

script.py

# Battle Rules

num_knights = int(input('Enter number of knights')

day = input('Enter day of the week')

enemy = input('Enter type of enemy')

if enemy == 'killer bunny':

print('Holy Hand Grenade!')

else:

# Original Battle Rules

if num_knights < 3 or day == 'Monday':

print('Retreat!')

if num_knights >= 10 and day == 'Wednesday':

print('Trojan Rabbit!')

else:

print('Truce?')

Our final

Rules of Engagement

- Python Programming for Biology_ - Tim J. StevensUploaded byphyaravi
- (eBook) Introduction to Numerical Analysis - J.Stoer,R.BulirschUploaded byshtorosean
- PythonUploaded byHedyeDarman
- Numerical Sim of Earth DamUploaded byravimohaniitr
- Numerical Methods for Nonlinear Lumped ModelsUploaded byvignanaraj
- Numerical Methods for Engineers 5E ChapraUploaded byJoana Araújo
- How Will It Move? (PS3) - Teacher EditionUploaded bySangari Active Science
- Python AOSUploaded byVivek Singh
- The Fall of Israel in 2022 AD a Prophecy or a Numerical Coincidence by Bassam Nihad JarrarUploaded bySelma Jordamović
- Matlab PythonUploaded byjuantik
- 5118.Numerical Computing With IEEE Floating Point Arithmetic by Michael L. OvertonUploaded byMsegade2
- Andrew Jason Penner- Numerical Analysis of the Ultrarelativistic and Magnetized Bondi–Hoyle ProblemUploaded byJuaxmaw
- A Friendly Introduction to Numerical AnalysisUploaded byWilliam Cheng
- Python Programming by Example - Agus KurniawanUploaded byJan Garcia
- 4 Basic PythonUploaded bynogauravno
- Mastering Weave StructuresUploaded byCatalina Wachtler
- pycseUploaded byRadovan Omorjan
- Dahlquist G., Bjorck a. Numerical MethodsUploaded byJeicoff
- A Billion Random Numerals - Nikolai RumavlefUploaded bypaoki01
- Numerical Methods for Solving Elliptic Boundary Value ProblemsUploaded byJuanParedesCasas
- 21861887 Introduction to Numerical Analysis 2nd EdUploaded byAndres Alva Justo
- Sketching as a Tool for Numerical Linear Algebra - David P. Woodruff (Webedition, 2014)Uploaded byfrans_smid
- Development of the Weaving Machine and 3D WovenUploaded byGarmentLearner
- Numerical Solutions of PDE by the FEMUploaded byParthapratim Mali
- Practical Parallel Algorithms for Graph Coloring Problems in Numerical Optimization.pdfUploaded byMinhNguyenTran
- R Numeric ProgrammingUploaded byvsuarezf2732
- Application of Numerical Models for Improvement of Flood PreparedUploaded bybycm
- Numerical Modelling of Welding Induced StressesUploaded byChristian Ammitzbøll
- Control Perspectives on Numerical Algorithms and Matrix Problems Advances in Design and ControlUploaded byAltin Bogdani
- [Mordini] 3D Numerical Modeling RC BehaviorUploaded byRitesh Kumar

- Tsm Sip FormatUploaded byDeepakPrabhu
- ErrorsUploaded byDeepakPrabhu
- Snapshot Auto DealershipsUploaded bykim
- LeaveUploaded byDeepakPrabhu
- QualityUploaded byDeepakPrabhu
- Total JobsUploaded byDeepakPrabhu
- Power Pack-Auto dealerships.pdfUploaded byDeepakPrabhu
- Wrigley ProjectUploaded byDeepakPrabhu
- Chi-square-table.pdfUploaded byJazel Porciuncula
- Measures of DispersionUploaded byDeepakPrabhu
- EfficiencyUploaded byDeepakPrabhu
- Emp NameUploaded byDeepakPrabhu
- 2.Sbi Po Exam 28-4-13.Text.marked.text.MarkedUploaded byamitukumar
- English Grammar NotesUploaded byminushastri33
- OT or PTUploaded byDeepakPrabhu
- Mock Aptitude Test 2Uploaded byDeepakPrabhu
- Mock AptitudeTest 6.docUploaded byDeepakPrabhu
- Mock Aptitude Test 11.docUploaded byDeepakPrabhu
- Mock Aptitude test 5.docUploaded byDeepakPrabhu
- HR SO SetUploaded bySnigdha Mohanty
- Mock Aptitude Test 7.docUploaded byDeepakPrabhu
- Mock Aptitude test 9.docUploaded byDeepakPrabhu
- Mock Aptitude test 8.docUploaded byDeepakPrabhu
- bank qpsUploaded bySheerin Sulthana
- Mock Aptitude Test 4.docUploaded byDeepakPrabhu
- Mock Aptitude Test 13.docUploaded byDeepakPrabhu
- Mock Aptitude test 10.docUploaded byDeepakPrabhu
- Mock Aptitude Test 3.docUploaded byDeepakPrabhu
- Mock Aptitude Test 12.docUploaded byDeepakPrabhu
- Mock Aptitude test 1.docUploaded byDeepakPrabhu

- Introduction to Cisco Router ConfigurationUploaded byDave Williams
- CatalogoUploaded byLougan Luz
- HMC SecurityUploaded byaksmsaid
- Model-3631_GWS2_C1410Uploaded bywsoruco
- ReadmeUploaded byKarim Ha
- HY-C-2014-2Uploaded byRanggaWarsito
- CourseOutline IT 101Uploaded byNoman Ali
- Component - UART V2.50Uploaded bySanjay Lungare
- Build a PIC Beacon Clock Pt1Uploaded byRastekHI
- 701P48936 FreeFlow Accxes System and Web PMT Setup GuideUploaded byChenna Vijay
- Kusadasi techno Market 2015 BroshureUploaded byErolYıldız
- VSTDGPProgrammersGuide.pdfUploaded byLucas Green
- Um Tron Unidec VhUploaded bygadirtano
- Diagnose the Cause Errors PCsUploaded byMorpheu
- Ug Nios2 Custom InstructionUploaded byimora014
- DSF MANUAL ToPrint 27july2017 MarginupdatedUploaded byNithin YM
- Chip Dec11Uploaded byMukesh Kumar
- InformationOnResourceAallocationWithinNetBackupSeptember2011.docUploaded byAbhishek Pondicherry
- Simulate ONTAP ® 9.5 Installation and Setup GuideUploaded byjmerejoc
- H.264 Network DVR User ManualUploaded byafkae
- vldb09-861Uploaded bymuttfarf
- WC5225-5230Uploaded byaaditya01
- QUIZ GAME.pdfUploaded byjayanand sidar
- Lab - Configuring IPv6 Static and Default RoutesUploaded bySergio Andres Rodriguez Rodriguez
- eztlrefUploaded bySuneetha Pampana
- How to Bypass BIOS PasswordUploaded byapi-26502404
- e1067testUploaded bypandi007
- OracleUploaded bysainath_kota2032
- ZSU2 Quick Guide Telesoft, Grabador de llamadas Telefonicas TelesoftUploaded byGlenn
- An Improved De-Duplication Technique for Small Files in HadoopUploaded byAnonymous kw8Yrp0R5r