Boston Python Workshop 8/Friday/Tutorial: Difference between revisions

no edit summary
imported>Jesstess
No edit summary
imported>Jesstess
No edit summary
Line 227:
</pre>
 
How about printingconcatenating different data types together?
===Printing===
 
You can print strings using the <code>print</code> function:
 
<pre>
h = "Hello" + 1
w = "World"
print(h + w)
</pre>
 
<pre>
my_string = "Alpha " + "Beta " + "Gamma " + "Delta"
print(my_string)
</pre>
 
How about printing different data types together?
 
<pre>
print("Hello" + 1)
</pre>
 
Hey now! The output from the previous example was really different and interesting; let's break down exactly what happened:
 
<code>>>> print("Hello" + 1)</code><br />
<code>Traceback (most recent call last):</code><br />
<code> File "<stdin>", line 1, in <module></code><br />
Line 266 ⟶ 251:
 
<pre>
print("Hello" + "World")
</pre>
 
Line 274 ⟶ 259:
 
<pre>
print("Hello" + 1)
</pre>
 
Line 282 ⟶ 267:
 
<pre>
print("Hello" + str(1))
</pre>
 
Line 292 ⟶ 277:
 
<pre>
print(len("Hello"))
print(len(""))
fish = "humuhumunukunukuapuaʻa"
lengthname_length = str(len(fish))
print(fish + " is a Hawaiian fish whose name is " + lengthname_length + " characters long.")
</pre>
 
Line 304 ⟶ 289:
 
<pre>
print('Hello')
print("Hello")
</pre>
 
Line 313 ⟶ 298:
 
<pre>
print('I'm a happy camper')
</pre>
 
Line 325 ⟶ 310:
 
<pre>
print("I'm a happy camper")
</pre>
 
Line 331 ⟶ 316:
 
<pre>
print("A" * 40)
print("ABC" * 12)
h = "Happy"
b = "Birthday"
print((h + b) * 10)
</pre>
 
Line 347 ⟶ 332:
<pre>
total = 1.5 - 1/2
print(total)
print(type(total))
</pre>
 
Line 356 ⟶ 341:
b = "brown"
c = "fox jumps over the lazy dog"
print("The " + a * 3 + " " + b * 3 + " " + c)
</pre>
 
Line 364 ⟶ 349:
 
Take a break, stretch, meet some neighbors, and ask the staff if you have any questions about this material.
 
=== Part 2: Printing===
 
So far we've been learning at the interactive <b>Python interpreter</b>. When you are working at the interpreter, any work that you do gets printed to the screen. For example:
 
<pre>
h = "Hello"
w = "World"
h + w
</pre>
 
will display "HelloWorld".
 
Another place that we will be writing Python code is in a file. When we run Python code from a file instead of interactively, we don't get work printed to the screen for free. We have to tell Python to print the information to the screen. The way we do this is with the <b>print</b> function. Here's how it works:
 
<pre>
h = "Hello"
w = "World"
print(h + w)
</pre>
 
<pre>
my_string = "Alpha " + "Beta " + "Gamma " + "Delta"
print(my_string)
</pre>
 
The string manipulate is exactly the same as before. The only difference is that you need to use <b>print</b> to print results to the screen:
 
<code> h + w</code>
 
becomes
 
<code> print(h + w)</code>
 
We'll see more examples of the print function in the next section.
 
==Python scripts==
Anonymous user