Variables and User Input

5
Introduction to Programming: Python Playing with the interpreter (i.e. using the Python Shell) >>> print "Hello World" Hello World print is the basic text output command in Python. The interpreter runs the single command and displays the result on the screen. The code above is a statement (a line of python code that does something.) >>> "Hello World" 'Hello World' This is an example of an expression. An expression is anything that evaluates to a value. (2+2, "dog", 6*7+100 …) (Just like in Math class) If you give the interpreter an expression it will evaluate it and show you the value. >>> 2 + 2 4 >>> 2 * 5 10 >>> 2 * 10 20 >>> 10 / 2 5 Basic Types Every value in the computer has a "type." The type determines what kind of operations you can do with a value. Type What it is Examples int Integer 5, 12, -4 float Real number 5, 3.14, -54.7 str String "5", '5', "Dog" """You can make a multi-line string with three double quotes""" Note Due to the way real numbers are stored the fractional component is often a little off. >>> .2 0.20000000000000001 >>> 2 / 5 # int / int -> int 0 >>> 2.0 / 5 # float / int -> float 0.40000000000000002 Cool! One statement using a multi-line string: print “““ first line second line ”””

description

Computer Science. Explains how to input variables and user input for Python programming.

Transcript of Variables and User Input

Page 1: Variables and User Input

Introduction to Programming: Python

Playing with the interpreter (i.e. using the Python Shell)

>>> print "Hello World"

Hello World

print is the basic text output command in Python. The interpreter runs the single command and

displays the result on the screen. The code above is a statement (a line of python code that does

something.)

>>> "Hello World"

'Hello World'

This is an example of an expression. An expression is anything that evaluates to a value. (2+2,

"dog", 6*7+100 …) (Just like in Math class) If you give the interpreter an expression it will

evaluate it and show you the value.

>>> 2 + 2

4

>>> 2 * 5

10

>>> 2 * 10

20

>>> 10 / 2

5

Basic Types

Every value in the computer has a "type." The type determines what kind of operations you can

do with a value.

Type What it is Examples int Integer 5, 12, -4 float Real number 5, 3.14, -54.7 str String "5", '5', "Dog"

"""You can make

a multi-line string

with three double quotes"""

Note – Due to the way real numbers are stored the fractional component is often a little off. >>> .2

0.20000000000000001

>>> 2 / 5 # int / int -> int

0

>>> 2.0 / 5 # float / int -> float

0.40000000000000002

Cool! One

statement using a

multi-line string: print “““

first line

second line

”””

Page 2: Variables and User Input

Variables

(Just like in Math class) A variable is a name that holds a value. All you need to do to create a

variable is assign it a new value and Python will remember it.

>>> x = 25

>>> x * 20

500

NOTE

x * 20 is an expression. It has the value of 500. x does not become 500.

To do that we would use: >>> x = x * 20

Variable Names

Your variable names can consist of letters, numbers and underscores ( _ ) but must begin with a

letter. e.g.

Good Bad

name 4you

age more$

shipShields first name

ID_number

lock12

Choosing good variable names is extremely important to help the overall clarity of your

program.

Very simple programs

I know that it's 20 degrees Celsius outside, but I think in Fahrenheit so I want my Python to

convert it for me.

>>> temp = 20

>>> fahren = temp * 9/5 +32

>>> fahren

68

The "=" sign is not the same as the "=" in Math.

Read "=" as "becomes", so x becomes 25

= is called the assignment operator, when you give a variable a value you

are "assigning" it a value.

Cool! Python is dynamically-

typed. (i.e. it automatically assigns

a type to the variable depending on

what you store in it)

What type of variable

is x? Ask Python! >>> type(x)

Page 3: Variables and User Input

You'll notice that to see my answer I needed to type fahren again. Line 2 is a statement not an

expression.

>>> temp = 12

>>> fahren

68

If I change temp after the fact the value in fahren does not change. The assignment statement

happens when we type it. It does not set up a permanent relationship. Python looks on the right

side of the assignment, computes the value and stores the answer in the variable on the left hand

side.

I could cut out fahren altogether if I was sure I wasn't going to use it later.

>>> temp = 20

>>> temp * 9/5 +32

68

Real programs are more complicated, and you would not want to type them in each time you

want to run them.

File -> New Window

re-type your program, hit F5 <When prompted save as example1.py>

temp = 20

temp * 9/5 +32

You'll notice that it doesn't display anything. The interactive interpreter will show you the value

of an expression but when you run your programs unused values are just ignored. Add print:

temp = 20

print temp * 9/5 +32

Basic Input

There are two input commands:

input # for int and float

raw_input # for str (i.e. strings)

# This let’s us convert any temperature

temp = input()

print temp * 9/5 + 32

# A more user-friendly version

temp = input("What is the temperature in Celsius? ")

print temp * 9/5 + 32

# Let’s try it with strings

>>> name = input()

Ching

# We get this error

Traceback (most recent call last):

File "<pyshell#46>", line 1, in -toplevel-

name = input()

File "<string>", line 0, in -toplevel-

NameError: name 'Ching' is not defined

Page 4: Variables and User Input

# 2 solutions

# 1. put quotes around our input (less friendly for user)

>>> name = input()

"Ching"

# 2. use raw_input command

>>>name = raw_input('What is your name? ')

Ching

>>>print 'Hello',name

Some Basic Math

Use this To do this Example

+, -, * standard math operators a = x + 3

/ divides two numbers, answer based

on types. int / int -> int a = 5 / 2 (a 2)

float / float -> float a = 5.0 / 2.0 (a 2.5)

int / float -> float a = 5 / 2.0 (a 2.5)

float / int -> float a = 5.0 / 2 (a 2.5)

% remainder of integer division a = 58 % 10 (a 8)

** exponentiation operator a = 2**10 (a 1024)

abs find the absolute value of a number a = abs(-23) (a 23)

round rounds off a float number, answer a = round(3.1234) (a 3.0)

is still float. Can specify # of a = round(3.1254,2) (a 3.13)

decimals.

float converts an int to float (can be a = float(12) (a 12.0)

useful with division)

int converts a float to int by a = int(3.64) (a 3)

chopping off all decimals.

str converts anything to a string, allows a = str(3.64) (a '3.64')

us to use string formatting methods

Page 5: Variables and User Input

Variables and User Input Exercises

1. Computes the area of a circle with radius 123 cm. Save as introEx1.py

2. Gets the radius of a circle and computes the area. Save as introEx2.py

3. Go to xe.com and find how much a Canadian dollar is worth in Euros (EUR). Make a

program that allows the user to enter the amount of Canadian they have and tell them what it

is worth in Euros. Save as introEx3.py

4. Gets the user’s first and last name and outputs them in reverse order with a comma between

them. Save as introEx4.py

5. Gets the coordinates for two points from the user and computes the distance. Round your

answer to two decimal places. Save as introEx5.py

6. At Jenny’s birthday party she orders a 32 piece pizza. Have the user (probably Jenny) enter

the number of people at the party that will be eating pizza and output the number of slices

each one gets. As you know the pizza might not divide evenly. There are two ways to

handle this. The first is to ignore the extra pieces and give everyone the same amount. The

second way is to cut up the extra pieces so that everyone gets the same amount. Your

program must output both options. e.g.

Number of guests: 10

Option 1: 3 slices each, 2 left over

Option 2: 3.2 slices each

Save as introEx6.py