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

Learn Python

1) The document introduces comments in Python code, which allow programmers to provide context and explanations for code without the computer executing that text. Comments start with a # symbol. 2) It demonstrates how to use the print() function to output text, and shows storing text in a variable called a string that can then be printed. 3) Variables are introduced as a way to store and reuse data in a program, like storing a greeting message in a variable and printing it out. Variables are assigned with the = symbol.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
270 views

Learn Python

1) The document introduces comments in Python code, which allow programmers to provide context and explanations for code without the computer executing that text. Comments start with a # symbol. 2) It demonstrates how to use the print() function to output text, and shows storing text in a variable called a string that can then be printed. 3) Variables are introduced as a way to store and reuse data in a program, like storing a greeting message in a variable and printing it out. Variables are assigned with the = symbol.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

LEARN PYTHON: SYNTAX Ironically, the first thing we’re

going to do is show how to tell


Welcome a computer to ignore a part of a
program. Text written in a
Python is a programming program but not run by the
language. Like other languages, computer is called a comment.
it gives us a way to Python interprets anything after
communicate ideas. In the case a # as a comment.
of a programming language,
Comments can:
these ideas are “commands”
that people use to communicate Provide context for why
with a computer! something is written the
way it is:
We convey our commands to  # This variable will
the computer by writing them in be used to count the
a text file using a programming number of times
language. These files are anyone tweets the
called programs. Running a word persnickety
program means telling a persnickety_count = 0
computer to read the text file,  Help other people reading

translate it to the set of the code understand it


operations that it understands, faster:
 # This code will
and perform those actions.
calculate the
Instructions likelihood that it
Change Codecademy to your name will rain tomorrow
in the script to the right. Run the complicated_rain_calc
code to see what it does! As ulation_for_tomorrow(
soon as you’re ready, move on )
to the next exercise to begin  Ignore a line of code and
learning to write your own see how a program will
Python programs! run without it:
 # useful_value =
my_name = "Codecademy" old_sloppy_code()
useful_value =
print("Hello and welcome " + my_name +
new_clean_code()
"!")
Instructions

Comments 1.
Documentation is an important 1.
step in programming. Write a
Print the distinguished greeting
comment describing the first
“Hello world!”
program you want to write!

print("Hello world")
#I want to write a hello world program

Print Strings
Computer programmers refer to
Now what we’re going to do is
blocks of text as strings. In our
teach our computer to
last exercise, we created the
communicate. The gift of speech
string “Hello world!”. In Python a
is valuable: a computer can
string is either surrounded by
answer many questions we have
double quotes ("Hello world") or
about “how” or “why” or “what”
single quotes ('Hello world'). It
it is doing. In Python,
doesn’t matter which kind you
the print() function is used to
use, just be consistent.
tell a computer to talk. The
Instructions
message to be printed should
be surrounded by quotes: 1.

# from Mary Shelley's Print your name using


Frankenstein the print()command.
print("There is something Stuck? Get a hint
at work in my soul, which
I do not understand.") 2.
In the above example, we direct
If your print statement uses
our program to print() an
double-quotes ", change them
excerpt from a notable book.
to single-quotes '. If it uses
The printed words that appear
single-quotes ', change them to
as a result of the print() function
double-quotes ".
are referred to as output. The
output of this example program Try running your code again
would be: after switching the type of
quote-marks. Is anything
There is something at work
in my soul, which I do not different about the output?
understand.
Instructions print('Darien')
Variables
# Farewell
message_string = "Hasta la
vista"
Programming languages offer a print(message_string)
method of storing data for Above, we create the
reuse. If there is a greeting we variable message_string, assign a
want to present, a date we need welcome message, and print the
to reuse, or a user ID we need to greeting. After we greet the
remember we can create user, we want to wish them
a variable which can store a goodbye. We then
value. In Python, update message_string to a
we assign variables by using the departure message and print
equals sign (=). that out.
Instructions
message_string = "Hello
there" 1.
# Prints "Hello there"
print(message_string) Update the variable meal to
In the above example, we store reflect each meal of the day
the message “Hello there” in a before we print it.
variable called message_string.
Variables can’t have spaces or # We've defined the variable "meal" here
to the name of the food we ate for
symbols in their names other breakfast!
than an underscore (_). They
meal = "An english muffin"
can’t begin with numbers but
they can have numbers after the
first letter (e.g., cool_variable_5 is # Printing out breakfast
OK). print("Breakfast:")

It’s no coincidence we call these print(meal)


creatures “variables”. If the
context of a program changes, # Now update meal to be lunch!
we can update a variable but
meal = "Ceviche"
perform the same logical
process on it.
# Printing out lunch
# Greeting
message_string = "Hello print("Lunch:")
there" print(meal)
print(message_string)
# Now update "meal" to be dinner that does not belong, a
meal = "Pollo a la brasa" command where it is not
# Printing out dinner expected, or a missing
parenthesis can all trigger
print("Dinner:")
a SyntaxError.
print(meal)  A NameError occurs when
the Python interpreter
Errors sees a word it does not
recognize. Code that
Humans are prone to making contains something that
mistakes. Humans are also looks like a variable but
typically in charge of creating was never defined will
computer programs. To throw a NameError.
compensate, programming Instructions
languages attempt to 1.
understand and explain You might encounter
mistakes made in their a SyntaxErrorif you open a string
programs. with double quotes and end it
with a single quote. Update the
Python refers to these mistakes string so that it starts and ends
as errorsand will point to the with the same punctuation.
location where an error occurred
with a ^ character. When You might encounter
programs throw errors that we a NameError if you try to print a
didn’t expect to encounter we single word string but fail to put
call those errors bugs. any quotes around it. Python
Programmers call the process of expects the word of your string
updating the program so that it to be defined elsewhere but
no longer produces unexpected can’t find where it’s defined.
errors debugging. Add quotes to either side of the
string to squash this bug.
Two common errors that we
encounter while writing Python Update the malformed strings in
are SyntaxError and NameError. the workspace to all be strings.

 means there is
SyntaxError print('This message has mismatched quote
something wrong with the marks!')
way your program is print("Abracadabra")
written — punctuation
Numbers can be assigned to
Numbers variables or used literally in a
program:
Computers can understand
much more than just strings of an_int = 2
text. Python has a few a_float = 2.1
numeric data types. It has
multiple ways of storing print(an_int + 3)
numbers. Which one you use # prints 5
depends on your intended Above we defined an integer
and a float as the
purpose for the number you are
saving. variables an_int and a_float. We
printed out the sum of the
An integer, or int, is a whole variable an_intwith the number 3.
number. It has no decimal point We call the number 3 here
and contains all counting a literal, meaning it’s actually
numbers (1, 2, 3, …) as well as the number 3 and not a variable
their negative counterparts and with the number 3 assigned to
the number 0. If you were it.
counting the number of people
in a room, the number of Floating-point numbers can
behave in some unexpected
jellybeans in a jar, or the number
of keys on a keyboard you ways due to how computers
would likely use an integer. store them. For more
information on floating-point
A floating-point number, or numbers and Python,
a float, is a decimal number. It review Python’s documentation
can be used to represent on floating-point limitations.
fractional quantities as well as Instructions
precise measurements. If you 1.
were measuring the length of
your bedroom wall, calculating A recent movie-going
the average test score of a experience has you excited to
seventh-grade class, or storing a publish a review. You rush out of
baseball player’s batting the cinema and hastily begin
average for the 1998 season you programming to create your
would likely use a float. movie-review website: The Big
Screen’s Greatest Scenes Decided
By A Machine.
Create the following variables # Prints "2.0"
and assign integer numbers to print(10 / 5)
them: release_year and runtime. Notice that when we perform
Stuck? Get a hint division, the result has a decimal
place. This is because Python
2. converts all ints to floats before
Now, create the performing division. In older
variable rating_out_of_10 and versions of Python (2.7 and
assign it a float number earlier) this conversion did not
between one and ten. happen, and integer division
would always round down to the
# Define the release and runtime integer
nearest integer.
variables below:
Division can throw its own
release_year = 2010
special error: ZeroDivisionError.
runtime = 2012 Python will raise this error when
attempting to divide by 0.
# Define the rating_out_of_10 float
Mathematical operations in
variable below:
Python follow the standard
rating_out_of_10 = 9.5
mathematical order of
operations.
Calculations Instructions

1.
Computers absolutely excel at
performing calculations. The Print out the result of this
“compute” in their name comes equation: 25 * 68 + 13 / 28
from their historical association
with providing answers to print(25*68+13/28)
mathematical questions. Python
performs addition, subtraction,
multiplication, and division
with +, -, *, and /. Changing
# Prints "500" Numbers
print(573 - 74 + 1)
Variables that are assigned
# Prints "50" numeric values can be treated
print(25 * 2) the same as the numbers
themselves. Two variables can
be added together, divided by 2, Instructions
and multiplied by a third
1.
variable without Python
distinguishing between the You’ve decided to get into
variables and literals (like the quilting! To calculate the
number 2 in this example). number of squares you’ll need
Performing arithmetic on for your first quilt let’s create
variables does not change the two
variable — you can only update variables: quilt_width and quilt_le
a variable using the = sign. ngth. Let’s make this first quilt 8
squares wide and 12 squares
coffee_price = 1.50
long. Print out the number of
number_of_coffees = 4
squares you’ll need to create the
# Prints "6.0" quilt!
print(coffee_price * 2.
number_of_coffees)
# Prints "1.5" It turns out that quilt required a
print(coffee_price) little more material than you
# Prints "4" have on hand! Let’s only make
print(number_of_coffees) the quilt 8 squares long. How
many squares will you need for
# Updating the price this quilt instead?
coffee_price = 2.00
quilt_width = 8
# Prints "8.0"
print(coffee_price * quilt_length = 12
number_of_coffees) print(quilt_width*quilt_length)
# Prints "2.0"
print(coffee_price) quilt_length = 8
# Prints "4" print(quilt_width*quilt_length)
print(number_of_coffees)
We create two variables and
assign numeric values to them.
Then we perform a calculation Exponents
on them. This doesn’t update
the variables! When we update Python can also perform
the coffee_price variable and exponentiation. In written math,
perform the calculations again, you might see an exponent as a
they use the updated values for superscript number, but typing
the variable! superscript numbers isn’t always
easy on modern keyboards. Your 6x6 quilts have taken off so
Since this operation is so related well, 6 people have each
to multiplication, we use the requested 6 quilts. Print out how
notation **. many tiles you would need to
make 6 quilts apiece for 6
# 2 to the 10th power, or people.
1024
print(2 ** 10)
print(6 ** 2)
# 8 squared, or 64 print(7 ** 2)
print(8 ** 2)
print(8 ** 2)

# 9 * 9 * 9, 9 cubed, or
729 print(6 ** 4)
print(9 ** 3)

# We can even perform Modulo


fractional exponents
# 4 to the half power, or Python offers a companion to
2
the division operator called the
print(4 ** 0.5)
modulo operator. The modulo
Here, we compute some simple
operator is indicated by % and
exponents. We calculate 2 to the
gives the remainder of a division
10th power, 8 to the 2nd power,
calculation. If the number is
9 to the 3rd power, and 4 to the
divisible, then the result of the
0.5th power.
modulo operator will be 0.
Instructions

1. # Prints 4 because 29 / 5
is 5 with a remainder of 4
You really like how the square print(29 % 5)
quilts from last exercise came
out, and decide that all quilts # Prints 2 because 32 / 3
is 10 with a remainder of
that you make will be square
2
from now on. print(32 % 3)
Using the exponent operator, # Modulo by 2 returns 0
print out how many squares for even numbers and 1 for
you’ll need for a 6x6 quilt, a 7x7 odd numbers
quilt, and an 8x8 quilt. # Prints 0
2. print(44 % 2)
Here, we use the modulo The + operator doesn’t just add
operator to find the remainder two numbers, it can also “add”
of division operations. We see two strings! The process of
that 29 % 5 equals 4, 32 % combining two strings is
3 equals 2, and 44 % 2 equals 0. called string concatenation.
Performing string concatenation
The modulo operator is useful in creates a brand new string
programming when we want to comprised of the first string’s
perform an action every nth- contents followed by the second
time the code is run. Can the string’s contents (without any
result of a modulo operation be added space in-between).
larger than the divisor? Why or
why not? greeting_text = "Hey
Instructions there!"
question_text = "How are
1. you doing?"
full_text = greeting_text
You’re trying to divide a group + question_text
into four teams. All of you count
off, and you get number 27. # Prints "Hey there!How
are you doing?"
Find out your team by print(full_text)
computing 27 modulo 4. Save In this sample of code, we create
the value to my_team. two variables that hold strings
2. and then concatenate them. But
we notice that the result was
Print out my_team. What number
missing a space between the
team are you on?
two, let’s add the space in-
3.
between using the same
Food for thought: what number concatenation operator!
team are the two people next to
full_text = greeting_text
you (26 and 28) on? What are
+ " " + question_text
the numbers for all 4 teams?
# Prints "Hey there! How
my_team = 28 % 4 are you doing?"
print(my_team) print(full_text)
Now the code prints the
message we expected.
Concatenation
If you want to concatenate a strings and then concatenate
string with a number you will them. But we don’t need to
need to make the number a convert a number to a string for
string first, using it to be an argument to a print
the str()function. If you’re trying statement.
to print() a numeric variable you Instructions
can use commas to pass it as a
1.
different argument rather than
converting it to a string. Concatenate the strings and
save the message they form in
birthday_string = "I am "
the variable message.
age = 10
birthday_string_2 = "
Now uncomment the print
years old today!"
statement and run your code to
# Concatenating an integer see the result in the terminal!
with strings is possible
if we turn the integer
into a string first
full_birthday_string =
birthday_string + str(age)
+ birthday_string_2

# Prints "I am 10 years


old today!"
print(full_birthday_string
)

# If we just want to print


an integer
# we can pass a variable
as an argument to
# print() regardless of
whether
# it is a string.

# This also prints "I am


10 years old today!"
print(birthday_string,
age, birthday_string_2)
Using str() we can convert
variables that are not strings to

You might also like