0% found this document useful (0 votes)
5 views

L04 - Main Function, Arguments and Expressions

Uploaded by

Kevin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

L04 - Main Function, Arguments and Expressions

Uploaded by

Kevin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Introduction to Programming

Semester 1, 2021
Lecture 4,
Main Function, Arguments and Expressions

Slides based on material by John Stavrakakis and that provided for


Sedgewick . All rights reserved
Copyright Warning

COMMONWEALTH OF AUSTRALIA

Copyright Regulations 1969

WARNING

This material has been reproduced and communicated to you by or


on behalf of the University of Sydney pursuant to Part VB of the
Copyright Act 1968 (the Act).

The material in this communication may be subject to copyright


under the Act. Any further reproduction or communication of this
material by you may be the subject of copyright protection under
the Act.

Do not remove this notice.

2
Lecture 4: Main Function, Arguments
and Expressions

Getting input to your program and manipulating


information.
Main Function, Arguments

Getting information into your program


The main function
Different computer languages have different main function. The main
function is supposed to be the entry point to the program, where the
first computer instruction begins.

Python’s does not have a main function. Instead, the code always
begins from the beginning of the .py file.

In the spirit of tradition, programmers may have something like this


to allow other readers to see where they start doing useful things[1]

1 if __ name__ == "__ main__ ":


2 print(" Hello World !")

[1]Technically, there can be anything that executes before this. The programmer is not

changing the entry point of the program, just directing attention 5


Reading values in with input

Recall that we can use an input to read in values to make an


interactive program:
1 print(" Enter your height in metres: ")
2 input_ variable = input ()
3 height = float( input_ variable ) # ASSIGNING the variable
4 print(" You entered " + str( height) + " m.")
5 print(" If you were 10% bigger you 'd be “ + str( height *1.1) + " m.")

~> python ReadADouble.py


Enter your height in metres:
1.82
You entered 1.82m.
If you were 10% bigger you’d be 2.0020000000000002m.
~>
Using the command–line arguments

If you don’t want to use input, such as if you want to run your program
like this:

~> python GrowMe.py 1.82


You entered a height of 1.82m.
If you grow by 10% then you’d be 2.002m.

. . . then you have to use the command-line arguments

7
The command-linearguments

When you run a python program from the command-line or terminal


you do something like this:
> python HelloWorld.py
Hello, World!

. . . but you can also give a program information directly, as soon as


you call it, like this:
> python Sum.py 4 5.5
The sum of 4 and 5.5 is 9.5

How does this work?

8
Program arguments

Now that we know the starting point, we can obtain the values we
provide at command line

1 import sys
print( sys. argv [0]) # print program name
9is / 36
2
INFO1110 2020 S2 Dr. John Stavrakak

3 print( sys. argv [1]) # print 1 st argument


4 print( sys. argv [2]) # print 2 nd argument

The variable sys.argv gives you a way to access the pieces of


information you provide, like 4 and 5.5 above.
Program arguments(cont.)

The way we do that is by referring to them using the square brackets,


also called the “index operator”, like this:

1 import sys
2
3 x = float( sys. argv [1])
4 y = float( sys. argv [2])
5
6 print(" The sum of " + str( x) + " and " + str( y) + " is " + str( x+ y));

The arguments are always Strings: they have to be converted


into numbers if you want to use them as numbers.

10
float()
float() is a way of converting a String into a float.

This is extremely useful if you need to read in floating-point numbers


to a program when you run it.

Use it like this:

1 x = f l o a t ( " 12.3 " )

now the String “12.3” has been parsed — that is, read and understood — as a
float value, and then stored in x.

(There is also int() : it parses a string like “123” as the integer number
123.)

11
Expression

How to do arithmetical calculations, comparisons, etc.


Simple expressions

13
Assignment

We assign values to variables using a single equals sign, like this:

1 x = 4
2 y = x

After this, y has the value 4.


1 x = 2* y

Now x has the value 8, and y still has the value 4.

14
We construct expressions using operators

An operator is a symbol or small set of symbols that let you perform


some kind of operation on the operands.
Here are some:
x = 5 assigns the value of x to be 5
a + b adds a and b
!sad negates the Boolean value of the variable sad
x++ most programming langauges: adds 1 to the variable x: this
is called incrementing. In Python, this is equivalent of +(+x),
where +x has no effect.
a < 23 compares the value of a to 23

15
Operator terminology

Operators work on operands. They may or may not modify the


operand.

An operator can be
unary operating on one operand;
binary operating on two operands
ternary operating on three operands

16
Assignment operator =

There are several operators in Python to make your life easier. The most
common you’ll probably use is the assignment operator:

=
We’ve seen this before: use = to assign the value on the left to take the
value on the right:

lvalue ← rvalue

lvalue = rvalue

And remember the equality operator is = =: it is used to compare


whether two primitive types are equal.

17
Operators +, - , *, /

The next set of operators are very straightforward: they are the standard
operators of mathematics:

+ − × ÷ (mathematical)
+ - * / (code)

For example:
1 x = 5
2 y = 3
3 z = x + y # z gets the value of ( x+ y), which is 8
4 x = -x # now x is -5
5 z = z + x # now z is 3
6 y = y* 2 # now y is 6

18
Warnings about operators
Integer division
1 x=3/2
2
print( x)
3
4 y=1/0
5 print( y)

Embedding shorthand operators is dangerous. What do you think


happens in the following?
1 x=4
2 matches = (++ x == 3)
3 y = ( x + 7) + ( --x )

i This is how bugs get introduced. This needs to be readable. It


should be expanded to show each calculation in a separate statement.
x = 4
y = 15
Simple Calculations

1 x =6
2 y = ++ x
3 z =( x + --y)
4 n =0
5 n += 1
6 print("x = " + str( x))
7 print("y = " + st r( y))
8 print("z = " + str( z))
9 print("n = " + str( n))
10 x =5
11 r = 1.2
12 s =x * r
13 print("x = " + str( x))
14 print("r = " + str( r))
15 print("s = " + str( s))
16 s = s - 1.1
17 print("s = " + str( s))

What does this print?

20
Simple Calculations

~> python SimpleOperators.py


x =6
y =6
z = 12
n =1
x =5
r = 1.2
s = 6.0
s = 4.9

21
+ and Strings
Above, in the lines
10 x =5
11 r = 1.2
12 s =x * r

and
14 print(" r =" +str( r)) 22is / 36
INFO1110 2020 S2 Dr. John Stavrakak

there is a “+” sign in arguments of the print method call. It’s there to
concatenate two Strings.

"x = " is a String, and print can only print String objects, so it converts the
whole expression to a single String.
+ and Strings(cont.)
What do you think this prints out:

1 print(" 5" + " 3")


2 p r i n t (5 + 3)

???

In general you can use the “+” to concatenate any two Strings, e.g.,
like this:
1 msg = " H e l l o , " + s y s . a r g v [ 1 ] + " , how a r e you ? "

23
Operators +=, -= , *= and / =
These operators are a very nice shorthand. They all operate in the same
way, by modifying the operand on the left, using the operand on the
right.
shorthand equivalent to
x += n x=x+n
x -= n x=x–n
x *= k x = x*k
x /= k x = x/k
In general,

x □= y

is equivalent to

x = x □ y,

for whatever □ is. 24


Equality operator= =

This binary operator should be very familiar by now: use = = to return


the value true when the two operands are equal:

left value == right value

is true if and only if the two


values are the same.

25
Comparing int and boolean

1 x = 4
2 y = 4
3 z = 2
4 xySame = ( x == y )
5 xzSame = ( x == z )
6 p r i n t ( " xy Same = " + s t r ( xy S a m e ) )
7 p r i n t ( " xzSame = " + s t r ( x z S a m e ) )
8 p r i n t ( " ( xy Same == xz S a me ) = " + s t r ( xySame == xzSame))

> python Equality.py


xySame = True
xzSame = False
(xySame == xzSame) = False

26
Comparing Strings: msg1 = = msg2 ?

Yes. The = = method will visit the area of memory of the two strings
and compare the content.

1 msg1 = " hello " 27is / 36


INFO1110 2020 S2 Dr. John Stavrakak

2 msg2 = " hello "


3 if msg1 = = msg2 :
4 # ...

Python will generalise the = = to apply to other kinds of objects


Comparing Strings: msg1 is msg2 ?
i Don’t use is to compare String content
is compares two single values. The value of the String variable is a
memory address. This has no information about the content of that area of
memory.

String msg1
char 0 char 1 char 2 char 3 char 4
0x00FA1100

H E L L O

String msg2
char 0 char 1 char 2 char 3 char 4
0x00100FF

H E L L O
not!
There are two ways to negate. There is the keyword not and the
negation operator: “!” — it’s the exclamation mark. In code you’ll see
this quite often, for example in expressions like
1 x = 1
2 y = 2
3 same = x != y
4 print( same)

which is true if x is not equal to y, or like this:


1 x = 1
2 y = 2
3 same = not ( x == y )
4 print( same)

which is true if the statement “x = = y” is False.


In mathematical symbols we use the “negate” symbol ¬ for
“not”.
The value of ¬x1 is true if, and only if, x1 is False.
Parentheses
I’ve been using expressions inside parentheses ( , ).
Expressions, when they are evaluated/executed, have a
value. That means if I write something like
1 x = 4
2 y = 4
then if the expression (x == y) is executed, it will give the result “True”.
Writing the expression in parentheses is usually a good idea. It avoids
confusion!
n o t ( x == y )

is equivalent to
( x != y )

but
( n o t x ) == y i s d i f f e r e n t
30
And and Or

Let’s think about a set of variables, called x1,... xk.


q The value of (x1 AND x2) is true if, and only if, both x1 and x2 are
true.
q The value of (x1 AND x2 AND . . . AND xk) is true if, and only if, all of
the xi are true.
q The value of (x1 OR x2) is true if, and only if, at least one of x1 and x2
is true.
q The value of (x1 OR x2 OR . . . OR xk) is true if, and only if, at least
one of the xi is true.
In Python we write and for logical AND, and or for logical OR.
[2]

[2]It is not obvious, but other languages will use other symbols
Operator Precedence
What is the result of:
1 x =1 +5 * 3 +2
2 y =8 / 4 - 1 / 1 - 1

This particular programming language has this order: Brackets,


Operators, Division / Multiplication, Addition / Subtraction
(BODMAS)

Always use parentheses to be clear.

1 x = (1 + 5) * (3 + 2)
2 y = 8 / (4 - (1 / 1) - 1)
Assignment

In Python, if we want to set the value of something, we use assignment


that looks like this:
1 x = -1/2

33
Assignment is not equality
Saying x = 3 in mathematics means “x is a variable whose value is
currently 3”.
In that sense the equivalent statement is 3 = x, but writing that in a
Python program doesn’t make sense: you would be attempting to
change the value of 3!

If you want to test whether x has the value 3, you would evaluate the
following expression:

1 ( x = = 3)

which has the Boolean value True if x really does equal 3 and the value
False otherwise.

Don’t confuse ‘=’ (assignment) with ‘= =’ (equality comparison)!

34
Comparison —warning!
Comparing floating point numbers for equality is a BAD IDEA .

1 f1 = 0.00015 + 0.00015
2 f2 = 0.0002 + 0.0001
3 matches = ( ( f1 == f2 ) )
4 print(" f1 = " + str( f1 ) )
5 print(" f2 = " + str( f2 ) )
6 print(" matches = " + str( matches))

prints out
f1 = 0.0003
f2 = 0.00030000000000000003
matches = False

This is a serious problem.


Recall
Do you understand what each step of this program is doing?
print(" Enter your height in metres: ")
1
2 input_ variable = input ()
3 height = float( input_ variable ) # ASSIGNING the variable
4 print(" You entered " + str( height) + " m.")
5 print(" If you were 10% bigger you 'd be “ + str( height *1.1) + " m.")

~> python ReadADouble.py


Enter your height in metres:
1.82
You entered 1.82m.
If you were 10% bigger you’d be 2.0020000000000002m.
~>

36

You might also like