- Details
- Category: Learn Python The Hard Way
- Hits: 10819
- Details
- Category: Learn Python The Hard Way
- Hits: 1655
{article Learn Python The Hard Way}{text}{/article}
You will need:
Notepad
Notepad++ is a free source code editor and Notepad replacement that supports several languages. Running in the MS Windows environment, its use is governed by GPL License.
Windows PowerShell
Windows PowerShell® is a task-based command-line shell and scripting language designed especially for system administration. Built on the .NET Framework, Windows PowerShell helps IT professionals and power users control and automate the administration of the Windows operating system and applications that run on Windows.
Python
Python is a remarkably powerful dynamic programming language that is used in a wide variety of application domains. Python is often compared to Tcl, Perl, Ruby, Scheme or Java. Some of its key distinguishing features include:
Notepad and Windows PowerShell was already installed.
Python I had to install.
To find out if you need to install Python.
Open powershell. In your Terminal program, run python. Just type python in terminal and hit enter.
If it is not recognized. Install it from http://python.org/download.
After install run python in Terminal again. Mine was not recognized, I had to type in terminal
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
Close powershell and then start it again to make sure python now runs. If it doesn't restart your computer.
After restart mine worked.
- Details
- Category: Learn Python The Hard Way
- Hits: 1673
{article Learn Python The Hard Way}{text}{/article}
My Note for Python
On the following page are My note on Python.
I use Zed A. Shaw
Learn Python The Hard Way
Zed A. Shaw, the author of Learn Python The Hard Way, Learn Ruby The Hard Way, and Learn C The Hard Way
- Details
- Category: Learn Python The Hard Way
- Hits: 1680
{article Learn Python The Hard Way}{text}{/article}
Type in Notepad++
and save as File: ex1.py.
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print 'Yay! Printing.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
Run in Window PowerShell
PS C:\> cd mystuff
PS C:\mystuff> python ex1.py
Hello World!
Hello Again
I like typing this.
This is fun.
Yay! Printing.
I'd much rather you 'not'.
I "said" do not touch this.
Study Drill 1:
Make your script print another line.
#Script print another line
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print 'Yay! Printing.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
print "Print another line."
PS C:\\mystuff> python ex1sd1.py
Hello World!
Hello Again
I like typing this.
This is fun.
Yay! Printing.
I'd much rather you 'not'.
I "said" do not touch this.
Print another line.
Study Drill 2:
Make your script print only one of the lines.
# Use octothorpe (comment) on all line but one to print only one line
# print "Hello World!"
# print "Hello Again"
# print "I like typing this."
# print "This is fun."
# print 'Yay! Printing.'
# print "I'd much rather you 'not'."
# print 'I "said" do not touch this.'
# print "Print another line."
print " Print only one line."
PS C:\mystuff> python ex1sd2.py
Only one line.
Study Drill 3
Put a '#' (octothorpe) character at the beginning of a line. What did it do? Try to find out what this character does?
It case the line no to print.
- Details
- Category: Learn Python The Hard Way
- Hits: 1555
{article Learn Python The Hard Way}{text}{/article}
Notepad++
File ex2.py
# A comment, this is so you can read your program later.
# Anything after the # is ignored by python
print "I could have code like this." # and the comment after is ignored
# You can also use a comment to "disable" or comment out a piece of code:
# print "This won't run."
print "This will run."
Window PowerShell
PS C:\mystuff> python ex2.py
I could have code like this.
This will run.
Study Drill 1
Find out if you were right about what the # character does and make sure you know what it's called (octothorpe or pound character).
Comments
As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.
For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and they are marked with the # symbol:
Everything from the # to the end of the line is ignored — it has no effect on the program. The message is intended for the programmer or for future programmers who might use this code. In this case, it reminds the reader about the ever-surprising behavior of integer division.
Study Drill 2
Take your ex2.py file and review each line going backwards. Start at the last line, and check each word in reverse against what you should have typed.
Done
Study Drill 3
Did you find more mistakes? Fix them.
No more mistakes
Study Drill 4
Read what you typed above out loud, including saying each character by its name. Did you find more mistakes? Fix them.
Did not find any more mistakes
- Common Student Questions
- 1:Are you sure # is called the pound character?
- I call it the octothorpe and that is the only name that no country uses and that works in every country. Every country thinks their way to call this one character is both the most important way to do it, and also the only way it's done. To me this is simply arrogance and really, y'all should just chill out and focus on more important things like learning to code.
- 2:If # is for comments, then how come # -*- coding: utf-8 -*- works?
- Python still ignores that as code, but it's used as a kind of "hack" or workaround for problems with setting and detecting the format of a file. You also find a similar kind of comment for editor settings.
- 3:Why does the # in print "Hi # there." not get ignored?
- The # in that code is inside a string, so it will be put into the string until the ending " character is hit. These pound characters are just considered characters and aren't considered comments.
- 4:How do I comment out multiple lines?
- Put a # in front of each one.
- 5:I can't figure out how to type a # character on my country's keyboard?
- Some countries use the Alt key and combinations of those to print characters foreign to their language. You'll have to look online in a search engine to see how to type it.
- 6:Why do I have to read code backwards?
- It's a trick to make your brain not attach meaning to each part of the code, and doing that makes you process each piece exactly. This catches errors and is a handy error checking technique.
- Details
- Category: Learn Python The Hard Way
- Hits: 1692
{article Learn Python The Hard Way}{text}{/article}
File ex3.py
Notepad++
print "I will now count my chickens:"
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh, that's why it's False.."
print "How about some more."
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
Windows PowerShell
PS C:\Users\Tom\mystuff> python ex3.py
I will now count my chickens:
Hens 30
Roosters 97
Now I will count the eggs:
7
Is it true that 3 + 2 < 5 - 7?
False
What is 3 + 2? 5
What is 5 - 7? -2
Oh, that's why it's False..
How about some more.
Is it greater? True
Is it greater or equal? True
Is it less or equal? False
Study Drills #1
Above each line, use the # to write a comment to yourself explaining what the line does.
# Prints I will now count my chickens: ##Statement
print "I will now count my chickens:"
# Prints number of Hens 30 ### 25 + (30/6) = 30
print "Hens", 25 + 30 / 6
# Prints Roosters 97 #### 100 - ((25 * 3)modulo4) = 97
print "Roosters", 100 - 25 * 3 % 4
# Prints Now I will count the eggs ###Statement
print "Now I will count the eggs:"
# Prints answer 7 ### 3 + 2 + 1 - 5 + (4 % 2) - (1 / 4) + 6 = 6.75 round off displays 7
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# Prints Is it true that 3 + 2 < 5 - 7? ###Statement
print "Is it true that 3 + 2 < 5 - 7?"
# Prints answers false
print 3 + 2 < 5 - 7
# Prints What is 3 + 2? 5 ### 3 + 2 = 5
print "What is 3 + 2?", 3 + 2
# Prints What is 5 - 7? -2 ### 5 - 7 = -2
print "What is 5 - 7?", 5 - 7
# Prints Oh, that's why it's False..
print "Oh, that's why it's False.."
# Prints How about some more.
print "How about some more."
# Prints Is it greater? True
print "Is it greater?", 5 > -2
# Prints Is it greater or equal? True
print "Is it greater or equal?", 5 >= -2
# Prints Is it less or equal? False
print "Is it less or equal?", 5 <= -2
Study Drills #2
Remember in Exercise 0 when you started Python? Start Python this way again and using the above characters and what you know, use Python as a calculator.
PS C:\> 2+2
4
PS C:\> 15-20
-5
PS C:\> 20/4
5
PS C:\> 4/20
0.2
PS C:\> 5*5
25
Study Drills #3
Find something you need to calculate and write a new .py file that does it.
ex3sd3.py
Starting_mileage = 140274
Ending_mileage = 140572
gallons = 20
dif = Ending_mileage - Starting_mileage
print "Starting Mileage::", Starting_mileage
print "Ending Mileage::", Ending_mileage
print "Different::", dif
print "Gallons::", gallons
print "MPG::", dif / gallons
PS C:\mystuff> python ex3sd3.py
Starting Mileage:: 140274
Ending Mileage:: 140572
Different:: 298
Gallons:: 20
MPG:: 14
Study Drills #4
Notice the math seems "wrong"? There are no fractions, only whole numbers. Find out why by researching what a "floating point" number is.
Floating point numbers are numbers which have a decimal component.
Floating Point Python
[Tutor] Floating point exercise 3 from Learn python the hard way
If you tell Python to divide 2 integers (whole numbers) by default it
will use integer arithmetic. So in your calculation on line 5 you get
a result of 7 as Python does not switch to floating point arithmetic.
You can ask Python to use floating point arithmetic a couple of ways.
For example if you want 2 divided by 3 you can tell Python to use
floating point arithmetic by:
--1--
>>> float(2) / 3
0.6666666666666666
>>> float(20) / 7
2.857142857142857
--2--
>>> 2.0 / 3
0.6666666666666666
>>> 20.0 / 7
2.857142857142857
Floating-point cheat sheet for Python
Floating-point cheat sheet for Python
Floating-Point Types
Almost all platforms map Python floats to IEEE 754 double precision.
f = 0.1
Decimal Types
Python has an arbitrary-precision decimal type named Decimal in the decimal module, which also allows to choose the rounding mode.
a = Decimal('0.1')
b = Decimal('0.2')
c = a + b # returns a Decimal representing exactly 0.3
How to Round
To get a string:
"%.2f" % 1.2399 # returns "1.24"
"%.3f" % 1.2399 # returns "1.240"
"%.2f" % 1.2 # returns "1.20"
To print to standard output:
print "%.2f" % 1.2399 # just use print and string formatting
Specific rounding modes and other parameters can be defined in a Context object:
getcontext().prec = 7
Study Drill #5
Rewrite ex3.py to use floating point numbers so it's more accurate (hint: 20.0 is floating point).
print "I will now count my chickens:"
print "Hens", 25.0 + 30.0 / 6
print "Roosters", 100 - 25.0 * 3.0 % 4.0
print "Now I will count the eggs:"
print 3.0 + 2 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0
print "Is it true that 3 + 2 < 5 - 7?"
print 3.0 + 2.0 < 5.0 - 7.0
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh, that's why it's False.."
print "How about some more."
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
PS C:\mystuff> python ex3sd5.py
I will now count my chickens:
Hens 30.0
Roosters 97.0
Now I will count the eggs:
6.75
Is it true that 3 + 2 < 5 - 7?
False
What is 3 + 2? 5
What is 5 - 7? -2
Oh, that's why it's False..
How about some more.
Is it greater? True
Is it greater or equal? True
Is it less or equal? False
Math symbols.
- + plus
- - minus
- / slash
- * asterisk
- % percent
- < less-than
- > greater-than
- <= less-than-equal
- >= greater-than-equal
Common Student Questions
Why is the % character a "modulus" and not a "percent"?
Mostly that's just how the designers chose to use that symbol. In normal writing you are correct to read it as a "percent", as in
"100%" is "one hundred percent". In programming this calculation is typically done with simple division and the / operator.
The % modulus is a different operation that just happens to use the % symbol.
How does % work?
Another way to say it is, "X divided by Y with J remaining." As in, "100 divided by 16 with 4 remaining."
The result of % is the J part, or the remaining part.
What is the order of operations?
In the US we use an acronym called PEMDAS which stands for Parentheses Exponents Multiplication Division Addition Subtraction.
That's the order Python follows as well.
Why does / (divide) round down?
It's not really rounding down, it's just dropping the fractional part after the decimal.
Try doing 7.0 / 4.0 and compare it to 7 / 4 and you'll see the difference.
- Details
- Category: Learn Python The Hard Way
- Hits: 1647
{article Learn Python The Hard Way}{text}{/article}
Notepad++
# ex4.py
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars available."
print "There are only", drivers, "drivers available."
print "There will be", cars_not_driven, " empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
Window PowerShell
PS C:\\mystuff> python ex4.py
There are 100 cars available.
There are only 30 drivers available.
There will be 70 empty cars today.
We can transport 120 people today.
We have 90 to carpool today.
We need to put about 3 in each car.
Study Drill 1
- I used 4.0 for space_in_a_car, but is that necessary? NO.
- What happens if it's just 4? You would get a whole number as the answer.
Study Drill 2
Remember that 4.0 is a "floating point" number. Find out what that means.
- Floating point numbers are numbers which have a decimal component.
Study Drill 3
Write comments above each of the variable assignments.
# ex4.py
cars = 100 # Number of car available.
space_in_a_car = 4.0 # Number of space in a car
drivers = 30 # Number of Drivers
passengers = 90 # How many passengers
cars_not_driven = cars - drivers # How many cars not driven
cars_driven = drivers # How many cars you have and drivers needed
carpool_capacity = cars_driven * space_in_a_car # How many you can transport.
average_passengers_per_car = passengers / cars_driven # How many passengers in a car.
Study Drill 4
Make sure you know what = is called (equals) and that it's making names for things.
- Assigns the value on the right to a variable on the left.
Study Drill 5
Remember that _ is an underscore character.
- We use this character a lot to put an imaginary space between words in variable names.
Study Drill 6
Try running python as a calculator like you did before and use variable names to do your calculations. Popular variable names are also i, x, and j.
i = 4
x = 8
j = 2
j = i + x
print "Total", j
>>>
Total 12
Names to Avoid
Never use the characters 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character variable names.
In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use 'l', use 'L' instead.
The equal sign ('=') is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:
width = 20
height = 5*9
width * height
print width * height
900
A value can be assigned to several variables simultaneously:
x = y = z = 0 # Zero x, y and z
print x
0
print y
0
print z
0
Variables must be “defined” (assigned a value) before they can be used, or an error will occur:
python : Traceback (most recent call last):
At line:1 char:1
+ python test4.py
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Traceback (most recent call last)::String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
File "test4.py", line 1, in <module>
n
NameError: name 'n' is not defined
There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:
PS > 3 * 3.75 / 1.5
7.5
PS > 7.0 / 2
3.5
- Details
- Category: Learn Python The Hard Way
- Hits: 1637
{article Learn Python The Hard Way}{text}{/article}
More Variables And Printing
When I google search I found this about %
Old string formatting
The % operator can also be used for string formatting. It interprets the left argument much like a sprintf()-style format string to be applied to the right argument, and returns the string resulting from this formatting operation.
String Formatting Operations
String and Unicode objects have one unique built-in operation: the %
operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values
(where format is a string or Unicode object), %
conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language. If format is a Unicode object, or if any of the objects being converted using the %s
conversion are Unicode objects, the result will also be a Unicode object.
ex5.py
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes ='Blue'
my_teeth = 'White'
my_hair = 'Brown'
print "Let's talk about %s." % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print "His teeth are usually %s depending on the coffee." % my_teeth
#this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight)
PS C:> python ex5.py
Let's talk about Zed A. Shaw.
He's 74 inches tall.
He's 180 pounds heavy.
Actually that's not too heavy.
He's got Blue eyes and Brown hair.
His teeth are usually White depending on the coffee.
If I add 35, 74, and 180 I get 289.
Study Drills
1: Change all the variables so there isn't the my_ in front.
Make sure you change the name everywhere, not just where you used = to set them.
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes ='Blue'
my_teeth = 'White'
my_hair = 'Brown'
name = my_name
age = my_age
height = my_height
weight = my_weight
eyes = my_eyes
teeth = my_teeth
hair = my_hair
print "Let's talk about %s." % name
print "He's %d inches tall." % height
print "He's %d pounds heavy." % weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (eyes, hair)
print "His teeth are usually %s depending on the coffee." % teeth
#this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight)
PS C:> python ex5_1.py
Let's talk about Zed A. Shaw.
He's 74 inches tall.
He's 180 pounds heavy.
Actually that's not too heavy.
He's got Blue eyes and Brown hair.
His teeth are usually White depending on the coffee.
If I add 35, 74, and 180 I get 289.
2: Try more format characters. %r is a very useful one. It's like saying "print this no matter what".
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes ='Blue'
my_teeth = 'White'
my_hair = 'Brown'
print "Let's talk about %r." % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print "His teeth are usually %s depending on the coffee." % my_teeth
#this line is tricky, try to get it exactly right
print "If I add %r, %r, and %r I get %r." % (my_age, my_height, my_weight, my_age + my_height + my_weight)
PS C:\mystuff> python ex5q2.py
Let's talk about 'Zed A. Shaw'.
He's 74 inches tall.
He's 180 pounds heavy.
Actually that's not too heavy.
He's got Blue eyes and Brown hair.
His teeth are usually White depending on the coffee.
If I add 35, 74, and 180 I get 289.
3: Search online for all of the Python format characters.
Conversion |
Meaning |
'd' |
Signed integer decimal. |
'i' |
Signed integer decimal. |
'o' |
Signed octal value. |
'u' |
Obsolete type – it is identical to 'd'. |
'x' |
Signed hexadecimal (lowercase). |
'X' |
Signed hexadecimal (uppercase). |
'e' |
Floating point exponential format (lowercase). |
'E' |
Floating point exponential format (uppercase). |
'f' |
Floating point decimal format. |
'F' |
Floating point decimal format. |
'g' |
Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. |
'G' |
Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. |
'c' |
Single character (accepts integer or single character string). |
'r' |
String (converts any Python object using repr()). |
's' |
String (converts any Python object using str()). |
'%' |
No argument is converted, results in a '%' character in the result. |
4: Try to write some variables that convert the inches and pounds to centimeters and kilos.
Do not just type in the measurements. Work out the math in Python
inches = 1
centimeters = inches * 2.54 # 1 inch = 2.54 centimeter
print "%r inches equals %r centimeters." % (inches, centimeters)
pounds = 1
kilos = pounds * 0.453592 # 1 pounds = 0.453592 kilos
print "%r pounds equals %r kilos." % (pounds, kilos)
PS C:\mystuff> python ex5q4.py
1 inches equals 2.54 centimeters.
1 pounds equals 0.453592 kilos.
inches = 1
centimeters = inches * 2.54 # 1 inches equals 2.54 centimeters.
print "%r inches equals %r centimeters." % (inches, centimeters)
pounds = 1
kilos = pounds * 0.453592 # 1 pounds equals 0.453592 kilos.
print "%r pounds equals %r kilos." % (pounds, kilos)
inches = 12
centimeters = inches * 2.54
print "%r inches equals %r centimeters." % (inches, centimeters)
pounds = 100
kilos = pounds * 0.453592
print "%r pounds equals %r kilos." % (pounds, kilos)
PS C:\mystuff> python ex5q4.py
1 inches equals 2.54 centimeters.
1 pounds equals 0.453592 kilos.
12 inches equals 30.48 centimeters.
100 pounds equals 45.3592 kilos.
{source}
<!-- You can place html anywhere within the source tags -->
<style>
<link href="http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css" rel="stylesheet" type="text/css" />
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js" type="text/javascript"></script>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shAutoloader.js" type="text/javascript"></script>
div {width:100%;}
.success {background-color:#E4E9EE;}
</style>
<div class="success"
style="width:100%;height:250px;overflow:auto;border:3px solid black; margin:0px"
>
my_name = 'Zed A. Shaw' </br>
my_age = 35 # not a lie </br>
my_height = 74 # inches </br>
my_weight = 180 # lbs </br>
my_eyes ='Blue' </br>
my_teeth = 'White' </br>
my_hair = 'Brown' </br>
</br>
</br>
name = my_name </br>
age = my_age </br>
height = my_height </br>
weight = my_weight </br>
eyes = my_eyes </br>
teeth = my_teeth </br>
hair = my_hair </br>
</br>
</br>
print "Let's talk about %s." % name</br>
print "He's %d inches tall." % height</br>
print "He's %d pounds heavy." % weight</br>
print "Actually that's not too heavy."</br>
print "He's got %s eyes and %s hair." % (eyes, hair)</br>
print "His teeth are usually %s depending on the coffee." % teeth</br>
#this line is tricky, try to get it exactly right</br>
print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight)</br>
</BR></BR></BR>
*** Python 2.7.6 (default, Nov 10 2013, 19:24:24) [MSC v.1500 64 bit (AMD64)] on win32. ***</BR>
>>> </BR>
Let's talk about Zed A. Shaw.</BR>
He's 74 inches tall.</BR>
He's 180 pounds heavy.
Actually that's not too heavy.</BR>
He's got Blue eyes and Brown hair.</BR>
His teeth are usually White depending on the coffee.</BR>
If I add 35, 74, and 180 I get 289.</BR>
>>> </BR>
</div>
<script language="javascript" type="text/javascript">
// You can place JavaScript like this
</script>
<?php
// You can place PHP like this
?>
{/source}
- Details
- Category: Learn Python The Hard Way
- Hits: 1744
{article Learn Python The Hard Way}{text}{/article}
Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable.
Python Strings:
Strings in Python are identified as a contiguous set of characters in between quotation marks. Python allows for either pairs of single or double quotes
tutorialspoint Simply Easy Learning
Strings and Text. Exercise 6:
#ex6.py Notepad ++
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print x
print y
print "I said: %r" % x
print "I also said: '%s'. " % y
hilarious = False
joke_evaluation = "Isn't that a joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
print w + e
Window PowerShell
PS C:\mystuff> python ex6.py
There are 10 types of people.
Those who know binary and those who don't.
I said: 'There are 10 types of people.'
I also said: 'Those who know binary and those who don't.'.
Isn't that a joke so funny?! False
This is the left side of...a string with a right side.
Study Drill 1:
Go through this program and write a comment above each line explaining it.
#%d is the formatting character, inserting 10 into the string, resulting in the string::
#There are 10 types of people.
x = "There are %d types of people." % 10
#Assigns the string "binary" on the right to a variable binary on the left.
binary = "binary"
#Assigns the string "don't" on the right to a variable do_not on the left.
do_not = "don't"
#%s is the formatting character, inserting binary and don't into the string, resulting in the string::
#Those who know binary and those who don't.
y = "Those who know %s and those who %s." % (binary, do_not)
# prints: There are 10 types of people
print x
# prints: Those who know binary and those who don't.
print y
#%r is the formatting character, inserting variable x into the string, resulting in the string::
#There are 10 types of people.
print "I said: %r" % x
#%s is the formatting character, inserting variable y into the string, resulting in the string::
#I also said: 'Those who know binary and those who don't.
print "I also said: '%s'. " % y
#Assigns the string False on the right to a variable hilarious on the left.
hilarious = False
#Assigns the string "Isn't that a joke so funny?! %r"" on the right to a variable joke_evaluation on the left.
joke_evaluation = "Isn't that a joke so funny?! %r"
# prints: Isn't that a joke so funny?! False
print joke_evaluation % hilarious
#Assigns the string "This is the left side of..." on the right to a variable w on the left.
w = "This is the left side of..."
#Assigns the string "a string with a right side." on the right to a variable e on the left.
e = "a string with a right side."
# Concatenates two strings w + e puts one after the other.
print w + e
Study Drill 2:
Find all the places where a string is put inside a string. There are four places.
# 2 strings inside a string total 2
y = "Those who know %s and those who %s." % (binary, do_not)
# 1 string inside a string total 3
print "I said: %r." % x
# 1 string inside a string total 4
print "I also said: '%s'." % y
Study Drill 3:
Are you sure there are only four places? Yes
How do you know? A string is usually a bit of text you want to display to someone, or "export" out of the program you are writing. Python knows you want something to be a string when you put either " (double-quotes) or ' (single-quotes) around the text. Strings may contain the format characters you have discovered so far. You simply put the formatted variables in the string, and then a % (percent) character, followed by the variable.
Maybe I like lying. Maybe not.
Study Drill 4:
Explain why adding the two strings w and e with + makes a longer string.
Concatenates two strings w + e puts one after the other.
- Details
- Category: Learn Python The Hard Way
- Hits: 1599
{article Learn Python The Hard Way}{text}{/article}
More Printing Exercise 7:
# ex7 Notepad++ More Printing
print "Mary has a little lamb."
print "Its fleece was white as %s." % 'snow'
print "And everywhere that Mary went."
print "." *10 # what'd that do?
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch that comma at the end. try removing it to see what happens
print end1 + end2 + end3 + end4 + end5 + end6,
print end7 + end8 + end9 + end10 + end11 + end12
Window PowerShell
PS C:\mystuff> python ex7.py
Mary has a little lamb.
Its fleece was white as snow.
And everywhere that Mary went.
..........
Cheese Burger
Study Drill 1:
Go back through and write a comment on what each line does.
Study Drill 2:
Study Drill 3:
Study Drill 4:
Study Drill 5:
- Details
- Category: Learn Python The Hard Way
- Hits: 1655
{article Learn Python The Hard Way}{text}{/article}
- Inculcate.Me
- Learn Python The Hard Way, 3rd Edition
- Python Programming/Basic Math
- Floating Point Python
- [Tutor] Floating point exercise 3 from Learn python the hard way
- Floating-point cheat sheet for Python
- Python Programming Language – Official Website