>>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1 >>> while b < 10:... print b... a, b = b, a+b... 1 2 3 5 8 WHILE.

Slides:



Advertisements
Similar presentations
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
Advertisements

String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Title An Introduction to Python. What is Python exactly? Python is a modern rapid development language. Code is very clean and easy to read. Emphasizes.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Structured programming
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Intro to Python Paul Martin. History Designed by Guido van Rossum Goal: “Combine remarkable power with very clear syntax” Very popular in science labs.
Introduction to Python. What is Python? Interpreted object oriented high level programming language – No compiling or linking neccesary Extensible: add.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Python Control of Flow.
4. Python - Basic Operators
COMPUTER SCIENCE FEBRUARY 2011 Lists in Python. Introduction to Lists Lists (aka arrays): an ordered set of elements  A compound data type, like strings.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Chapter 2 Control. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Repetition, quick overview.
More Looping Structures
Programming for Linguists An Introduction to Python 24/11/2011.
Python Control Flow statements There are three control flow statements in Python - if, for and while.
Introduction to Programming Workshop 2 PHYS1101 Discovery Skills in Physics Dr. Nigel Dipper Room 125d
Programming for Engineers in Python Sawa 2015 Lecture 2: Lists and Loops 1.
Introduction to Computing Using Python Straight-line code  In chapter 2, code was “straight-line”; the Python statements in a file (or entered into the.
For. for loop The for loop in Python is more like a foreach iterative-type loop in a shell scripting language than a traditional for conditional loop.
If statements while loop for loop
Built-in Data Structures in Python An Introduction.
Python Tricks CMSC 201. Overview Today we are learning some new tricks to make our lives easier! Slicing and other tricks Multiple return values Global.
Python The tutorial
Chapter 05 (Part III) Control Statements: Part II.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
Python 101 Dr. Bernard Chen University of Central Arkansas PyArkansas.
Introduction to Strings Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg 1.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
Fortran: Control Structures Session Three ICoCSIS.
Introduction to Computing Using Python Repetition: the for loop  Execution control structures  for loop – iterating over a sequence  range() function.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Mr. Crone.  Use print() to print to the terminal window  print() is equivalent to println() in Java Example) print(“Hello1”) print(“Hello2”) # Prints:
PH2150 Scientific Computing Skills Control Structures in Python In general, statements are executed sequentially, top to bottom. There are many instances.
A thorough introduction to Python. What is Python exactly? Python is a modern rapid development language. – Emphasizes single, intuitive approach to most.
String and Lists Dr. José M. Reyes Álamo.
Topic: Iterative Statements – Part 1 -> for loop
Python: Control Structures
Repeating code We could repeat code we need more than once: i = 1 print (i) i += 1 print (i) #… stop when i == 9 But each line means an extra line we might.
CSCE 590 Web Scraping Topics Readings: Overview – Web scraping
Introduction To Python
An Introduction to Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
String and Lists Dr. José M. Reyes Álamo.
More Looping Structures
CSCE 590 Web Scraping Topics Readings: Overview – Web scraping
3. Decision Structures Rocky K. C. Chang 19 September 2018
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Statement-Level Control Structures
More Looping Structures
Class code for pythonroom.com cchsp2cs
Introduction to Strings
CMPT 120 Lecture 10 – Unit 2 – Cryptography and Encryption –
Hossain Shahriar CISC 101: Fall 2011 Hossain Shahriar
Selamat Datang di “Programming Essentials in Python”
Presentation transcript:

>>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1 >>> while b < 10:... print b... a, b = b, a+b WHILE

If Statements Perhaps the most well-known statement type is the if statement. For example: >>> x = int(raw_input("Please enter an integer: ")) >>> if x < 0:... x = 0... print 'Negative changed to zero'... elif x == 0:... print 'Zero'... elif x == 1:... print 'Single'... else:... print 'More'... There can be zero or more elif parts, and the else part is optional. The keyword `elif' is short for `else if', and is useful to avoid excessive indentation. An if... elif... elif... sequence is a substitute for the switch or case statements found in other languages

For Statements The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python's for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended): >>> # Measure some strings:... a = ['cat', 'window', 'defenestrate'] >>> for x in a:... print x, len(x)... cat 3 window 6 defenestrate 12 It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy. The slice notation makes this particularly convenient: >>> for x in a[:]: # make a slice copy of the entire list... if len(x) > 6: a.insert(0, x)... >>> a ['defenestrate', 'cat', 'window', 'defenestrate']

The range() Function If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates lists containing arithmetic progressions: >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] The given end point is never part of the generated list; range(10) generates a list of 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the `step'): >>> range(5, 10) [5, 6, 7, 8, 9] >>> range(0, 10, 3) [0, 3, 6, 9] >>> range(-10, -100, -30) [-10, -40, -70] To iterate over the indices of a sequence, combine range() and len() as follows: >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)):... print i, a[i]... 0 Mary 1 had 2 a 3 little 4 lamb

break and continue Statements, and else Clauses on Loops The break statement, like in C, breaks out of the smallest enclosing for or while loop. The continue statement, also borrowed from C, continues with the next iteration of the loop. Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers: >>> for n in range(2, 10):... for x in range(2, n):... if n % x == 0:... print n, 'equals', x, '*', n/x... break... else:... # loop fell through without finding a factor... print n, 'is a prime number'... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3

Defining Functions We can create a function that writes the Fibonacci series to an arbitrary boundary: >>> def fib(n): # write Fibonacci series up to n... """Print a Fibonacci series up to n."""... a, b = 0, 1... while b < n:... print b,... a, b = b, a+b... >>> # Now call the function we just defined:... fib(2000)