User:Jrincayc/Who Goes There

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Who Goes There?[edit | edit source]

Input and Variables[edit | edit source]

Now I feel it is time for a really complicated program. Here it is:

print "Halt!"
s = raw_input("Who goes there? ")
print "You may pass,", s

When I ran it here is what my screen showed:

Halt!
Who goes there? Josh
You may pass, Josh

Of course when you run the program your screen will look different depending on what you enter after "Who goes there?". When you ran the program you probably noticed (you did run the program, right?) how you had to type in your name and then press Enter. Then the program printed out some more text and also your name. This is an example of input. The program reaches a certain point (in this case, the command raw_input) and then waits for the user to input some data that the program can use later.

Of course, getting information from the user would be useless if we didn't have anywhere to put that information and this is where variables come in. In the previous program s is a variable. Variables are like a box that can store some piece of data. Here is a program to show examples of variables:

a = 123.4
b23 = 'Spam'
first_name = "Bill"
b = 432
c = a + b
print "a + b is", c
print "first_name is", first_name
print "Sorted Parts, After Midnight or",b23

And here is the output:

a + b is 555.4
first_name is Bill
Sorted Parts, After Midnight or Spam

Variables store data. The variables in the above program are a, b23, first_name, b, and c. The two basic types of variables are strings and numbers.

Strings are a sequence of letters, numbers and other characters. "Spam", "Bill", "a + b is", and "first_name is" are strings that are used in this program. The characters are surrounded by single or double quotes (" or '). In this example b23 and first_name are variables that are storing strings.

'Numbers' are any sort of number, whether integers (whole numbers) or reals (numbers with fractional parts). The variables a, b and c are variables containing numbers.


Okay, so we have these boxes called variables and also data that can go into the variables. The computer will see a line like first_name = "Bill" and it reads it as Put the string Bill into the box (or variable) first_name. Later on it sees the statement c = a + b and it reads it as Put a + b into c. It then replaces the variabls a and b with their values, so this becomes Put 123.4 + 432 into c. It then performs the addition, so the end result of c = a + b is Put 555.4 into c.

Here is another example of variable usage:

a = 1
print a
a = a + 1
print a
a = a * 2
print a

And here is the output:

1
2
4

Note something interesting - even if it is the same variable on both sides the computer still reads it as: First find out the data to store and than find out where the data goes. So the equals sign (=) is a bit different to what you might expect. In programming terminology, = is known as assignment, because in the statement a = a + 1 the variable a is assigned the value of a plus 1.


How about we go back to the program at the start of this chapter:

print "Halt!"
s = raw_input("Who goes there? ")
print "You may pass,", s

With the output:

Halt!
Who goes there? Josh
You may pass, Josh

Now when you look at it, you may notice that the variable s is assigned the output of the command raw_input. So s equals what was typed after the prompt "Who goes there?" (in this example, the string "Josh"). Secondly, take a look at the print command. Note that it has two arguments, separated by a comma, but what is interesting is that the second argument is a variable. The print command is actually quite an interesting command, because not only can it take a variable number of arguments, but those arguments, in any order, could be a string, a number, an expression or a variable, and that an expression can include variables as well as numbers.


One more program before I end this chapter:

num = input("Type in a Number: ")
str = raw_input("Type in a String: ")
print "num =", num
print "num is a ",type(num)
print "num * 2 =",num*2
print "str =", str
print "str is a ",type(str)
print "str * 2 =",str*2

The output I got was:

Type in a Number: 12.34
Type in a String: Hello
num = 12.34
num is a  <type 'float'>
num * 2 = 24.68
str = Hello
str is a  <type 'string'>
str * 2 = HelloHello

Notice that the variable num was gotten with input while str was gotten with raw_input. raw_input returns a string while input returns a number. When you want the user to type in a number use input but if you want the user to type in a string use raw_input.

The second half of the program uses the type command, which tells what a variable is. Numbers are of type int or float (which are short for 'integer' and 'floating point' respectively). (In case you are wondering, a 'floating point' number is a number with a decimal point). Strings are of type string. Integers and floats can be worked on by mathematical functions, strings cannot. Notice how when python multiples a number by a integer the expected thing happens. However when a string is multiplied by a integer the string has that many copies of it added i.e. str * 2 = HelloHello.

The operations with strings do slightly different things than operations with numbers. Here are some interactive mode examples to show that some more.

>>> "This"+" "+"is"+" joined."
'This is joined.'
>>> "Ha, "*5
'Ha, Ha, Ha, Ha, Ha, '
>>> "Ha, "*5+"ha!"
'Ha, Ha, Ha, Ha, Ha, ha!'
>>>

Note how in interactive mode only, an expression is directly evaluated, and the result is printed to the screen (no need for the print command).

Here is the list of some string operations:

Operation Symbol Example
Repetition * "i"*5 == "iiiii"
Concatenation + "Hello, " + "World!" == "Hello, World!"

Examples[edit | edit source]

Rate_times.py

#This programs calculates rate and distance problems
print "Input a rate and a distance"
rate = input("Rate:")
distance = input("Distance:")
print "Time:",distance/rate

Sample runs:

> python rate_times.py
Input a rate and a distance
Rate:5
Distance:10
Time: 2
> python rate_times.py
Input a rate and a distance
Rate:3.52
Distance:45.6
Time: 12.9545454545

Area.py

#This program calculates the perimeter and area of a rectangle
print "Calculate information about a rectangle"
length = input("Length:")
width = input("Width:")
print "Area",length*width
print "Perimeter",2*length+2*width

Sample runs:

> python area.py
Calculate information about a rectangle
Length:4
Width:3
Area 12
Perimeter 14
> python area.py
Calculate information about a rectangle
Length:2.53
Width:5.2
Area 13.156
Perimeter 15.46

temperature.py

#Converts Fahrenheit to Celsius
temp = input("Farenheit temperature:")
print (temp-32.0)*5.0/9.0

Sample runs:

> python temperature.py
Farenheit temperature:32
0.0
> python temperature.py
Farenheit temperature:-40
-40.0
> python temperature.py
Farenheit temperature:212
100.0
> python temperature.py
Farenheit temperature:98.6
37.0

Exercises[edit | edit source]

Write a program that gets 2 string variables and 2 integer variables from the user, concatenates (joins them together with no spaces) and displays the strings, then multiplies the two numbers on a new line.

User:Jrincayc/Count to 10