0% found this document useful (0 votes)
51 views34 pages

Python Lecture 1: Basic Python Programs, Defining Functions

Python Lecture 1 provides an overview of the Python programming language. It discusses that Python was created in 1991 by Guido van Rossum and is an interpreted language commonly used for scripting and small to medium projects. The document also covers installing Python on different operating systems, how Python code is executed by an interpreter rather than compiled, basic Python syntax including print statements, comments, functions, and variables, and common operators and control structures in Python.

Uploaded by

Atul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views34 pages

Python Lecture 1: Basic Python Programs, Defining Functions

Python Lecture 1 provides an overview of the Python programming language. It discusses that Python was created in 1991 by Guido van Rossum and is an interpreted language commonly used for scripting and small to medium projects. The document also covers installing Python on different operating systems, how Python code is executed by an interpreter rather than compiled, basic Python syntax including print statements, comments, functions, and variables, and common operators and control structures in Python.

Uploaded by

Atul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Python Lecture 1

Basic Python programs,


defining functions
Python!
• Created in 1991 by Guido van Rossum (now at Google)
– Named for Monty Python

• Useful as a scripting language


– script: A small program meant for one-time use
– Targeted towards small to medium sized projects

• Used by:
– Google, Yahoo!, Youtube
– Many Linux distributions
– Games and apps (e.g. Eve Online)
Installing Python
Windows: Mac OS X:
• Download Python from • Python is already installed.
http://www.python.org • Open a terminal and run python
• Install Python. or run Idle from Finder.
• Run Idle from the Start Menu.
Linux:
• Chances are you already have
Python installed. To check, run
python from the terminal.
• If not, install from your
distribution's package system.
Note: For step by step installation
instructions, see the course web site.
Interpreted Languages
• interpreted
– Not compiled like Java
– Code is written and then directly executed by an interpreter
– Type commands into interpreter and see immediate results

Java: Runtime
Code Compiler Computer
Environment

Python: Code Interpreter Computer


The Python Interpreter
• Allows you to type commands one-at-a-time and see results
• A great way to explore Python's syntax
– Repeat previous command: Alt+P
Basic Java code
• File name == class_name.java
• Console output: System.out.println
• Methods: public static void name() { ...
• main: function where the execution begins
• > javac Hello2.java
• >java Hello2

Hello2.java
1 public class Hello2 {
2 public static void main(String[] args) {
3 hello();
4 }
5
6 public static void hello() {
7 System.out.println("Hello, world!");
8 }
9 }
Our First Python Program
• Python does not have a main method like Java
– The program's main code is just written directly in the file
• Python statements do not end with semicolons

hello.py
1 print "Hello, world!"
The print Statement
print "text"
print (a blank line)
– Escape sequences such as \" are the same as in Java
– Strings can also start/end with '

swallows.py
1 print "Hello, world!"
2 print
3 print "Suppose two swallows \"carry\" it together."
4 print 'African or "European" swallows?'
Comments
• Syntax:
# comment text (one line)

swallows2.py
1 # Student, CS G523
2 # This program prints important messages.
3 print "Hello, world!"
4 print # blank line
5 print "Suppose two swallows \"carry\" it together."
6 print 'African or "European" swallows?'
Functions
• Function: Equivalent to a static method in Java.
• Syntax:
hello2.py
def name():
statement 1 # Prints a helpful message.
2 def hello():
statement 3 print "Hello, world!"
... 4
5 # main (calls hello twice)
statement 6 hello()
7 hello()

– Must be declared above the 'main' code


– Statements inside the function must be indented
Whitespace Significance
• Python uses indentation to indicate blocks, instead of {}
– Makes the code simpler and more readable
– In Java, indenting is optional. In Python, you must indent.

hello3.py
1 # Prints a helpful message.
2 def hello():
3 print "Hello, world!"
4 print "How are you?"
5
6 # main (calls hello twice)
7 hello()
8 hello()
Exercise
• Write a optimized program in Python (using function calls).
Its output should be:
______
/ \
/ \
\ /
\______/
\ /
\______/
+--------+
______
/ \
/ \
| STOP |
\ /
\______/
______
/ \
/ \
+--------+
Exercise Solution
def egg(): def top():
top() print " ______"
bottom() print " / \\"
print print "/ \\"

def cup(): def bottom():


bottom() print "\\ /"
line() print " \\______/"
print
def line():
def stop(): print "+--------+"
top()
print "| STOP |" # main
bottom() egg()
print cup()
stop()
def hat(): hat()
top()
line()
print
General Information
• Unlike C/C++ or Java, Python statements do not end in a
semicolon
• In Python, indentation is the way you indicate the scope of
a conditional, function, etc.
• Look, no braces!
• Python is interpretive, meaning you don’t have to write
programs.
• You can just enter statements into the Python environment
and they’ll execute
• For the most part, we’ll be writing programs

14
The Python Shell

• Because Python is interpretive, you can do simple


things with the shell
• At the prompt, type Python
• You should have a >>> prompt
• Type in:
print(“hello, world”)
• You have written your first Python program
• Keep the shell up; we’ll be using it

15
The Python Shell
• This is good for simple calculations but not for real
programming
• For programming, we’ll use Idle
• There are two versions: Idle for Python 2.7 and Idle3 for
Python 3.2
• For most of what we do, we’ll have to use 2.7 because
Bluetooth doesn’t seem to work with 3.2
• You’ll run as the “superuser” because otherwise you won’t
have access to the GPIO pins
• Idle will give you access to a shell but also to an IDE for
writing and saving programs

16
Python Modules
• In practice, only the simplest programs are run in the shell
• You can create a module by going to the File->New Window
menu option
• This brings up a text editor that lets you create a Python
program and run it
• Write your first “Hello World!” program thus:
print(“Hello, World!”)

17
Python Modules
• Press F5
• It will ask you to save the file before you run it
• Save it to your home directory as HelloWorld.py
• You must provide the .py extension
• If you want to run it outside of the development
environment simply type:
python HelloWorld.py
• Note that Linux is case sensitive

18
Variables
• As in every language, a variable is the name of a memory
location
• Python is weakly typed
• That is, you don’t declare variables to be a specific type
• A variable has the type that corresponds to the value you
assign to it
• Variable names begin with a letter or an underscore and can
contain letters, numbers, and underscores
• Python has reserved words that you can’t use as variable
names

19
Variables
• At the >>> prompt, do the following:
x=5
type(x)
x=“this is text”
type(x)
x=5.0
type(x)

20
Printing
• You’ve already seen the print statement
• You can also print numbers with formatting
• These are identical to Java or C format specifiers

21
Comments
• All code must contain comments that describe what it does
• In Python, lines beginning with a # sign are comment lines
You can also have comments on the same line as a statement
# This entire line is a comment
x=5 # Set up loop counter

22
Operators
• Arithmetic operators we will use:
– + - * / addition, subtraction/negation, multiplication,
division
– % modulus, a.k.a. remainder
– ** exponentiation
• precedence: Order in which operations are computed.
– * / % ** have a higher precedence than + -
1 + 3 * 4 is 13

– Parentheses can be used to force a certain order of


evaluation.
(1 + 3) * 4 is 16

23
Expressions
• When integers and reals are mixed, the result is a real
number.
– Example: 1 / 2.0 is 0.5
– The conversion occurs on a per-operator basis.
– 7 / 3 * 1.2 + 3 / 2
– 2 * 1.2 + 3 / 2
– 2.4 + 3 / 2
– 2.4 + 1
– 3.4

24
Math Functions
– Use this at the top of your program: from math import *

25
Relational Operators
• Many logical expressions use relational operators:

26
Logical Operators
• These operators return true or false

27
The if Statement
• Syntax:
if <condition>:
<statements>

x = 5
if x > 4:
print(“x is greater than 4”)
print(“This is not in the scope of the if”)

28
The if Statement
• The colon is required for the if
• Note that all statement indented one level in from the if
are within it scope:
x = 5
if x > 4:
print(“x is greater than 4”)
print(“This is also in the scope of the if”)

29
The if/else Statement
if <condition>:
<statements>
else:
<statements>

• Note the colon following the else


• This works exactly the way you would expect

30
The for Loop
• This is similar to what you’re used to from C or Java, but not the
same
• Syntax:
for variableName in groupOfValues:
<statements>
• variableName gives a name to each value, so you can refer to it
in the statements.
• groupOfValues can be a range of integers, specified with the
range function.

• Example:
for x in range(1, 6):
print x, "squared is", x * x

31
Range

• The range function specifies a range of integers:


range(start, stop) - the integers between start
(inclusive) and stop (exclusive)

• It can also accept a third value specifying the change


between values.
range(start, stop, step) - the integers between
start (inclusive) and stop (exclusive) by step

32
The while Loop
• Executes a group of statements as long as a condition is
True.
• Good for indefinite loops (repeat an unknown number of
times)
• Syntax:
while <condition>:
<statements>
• Example:
number = 1
while number < 200:
print number,
number = number * 2

33
Exercise
• Write a Python program to compute and display the first 16
powers of 2, starting with 1
• Do this in the Python shell

34

You might also like