Python Syntax - Part 1

Lesson Notes:

Hello World!

If programming is the act of teaching a computer to have a conversation with a user, it would be most useful to first teach the computer how to speak.

In Python, this is accomplished with the print statement.

Syntax

print ("Hello, world!")

A print statement is the easiest way to get your Python program to communicate with you.

Being able to command this communication will be one of the most valuable tools in your programming toolbox.


Strings

Text in Python is considered a specific type of data called a string.

A string, so named because they’re a series of letters, numbers, or symbols connected in order — as if threaded together by string. Strings can be defined in different ways:

Code Snippet 1

print "Learning Python is easy!"

We can combine multiple strings using +, like so:

Code Snippet 2

print "I Will " + "ace at python"

Common Errors:

Mismatched quotes

Without quotes



Variables

We need to build systems for dealing with data that changes over time.

That data could be the location of a plane, or the time of day, or the Netflix show you’re currently watching.

The only important thing is that it may be different at different times. Python uses variables to define things that are subject to change.

Code Snippet 1

greeting_message = "Namaste, from pixeltests!"
current_lesson = 3
todays_date = ________

Arithmetic

Addition, subtraction, multiplication, division, and other numeric calculations are easy to do in most programming languages, and Python is no exception. Some examples:

mangoes = 2+5
oranges = 2*5
apples = 25-8
Vegetables = 2*2+5-3

The variable will hold the final result of each operation.

  • The modulo operator %

In Python Modulo returns the remainder after division is performed.

remainder = 151 % 2
is_this_number_divisible_by_seven = 133 % 7

Comments

Code should be written in such a way that it is easy to understand on its own, if you want to include a piece of information to explain a part of your code, you can use the # sign.

The machine does not run this code — it is only for humans to read. When you look back at your code later, comments may help you figure out what it was intended to do.

Code Snippet

# this variable holds the population of the city
city_pop = 13