Intro to Python

August 09, 2020

Python Keywords

Keywords are the reserved words in Python.

We cannot use a keyword as a variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language.

🛑 In Python, keywords are case sensitive.

There are 33 keywords in Python 3.7. This number can vary slightly over the course of time.

All the keywords except True, False and None are in lowercase and they must be written as they are. The list of all the keywords is given below.

False | await | else | import |pass None | break | except | in raise True class finally is return and continue for lambda try as def from nonlocal while assert del global not with async elif if or yield

Python Identifiers

👉 An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another.

Rules for writing identifiers

Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _. Names like myClass, var1 and printthistoscreen, all are valid example. An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name. Keywords cannot be used as identifiers.

global = 1

Output

File "<interactive input>", line 1
    global = 1
           ^
SyntaxError: invalid syntax

We cannot use special symbols like !, @, #, $, % etc. in our identifier.

a@ = 0

basic python syntax

print('Irena')
name=input()
print('Irena   ' + name)

VARIABLES AND TYPES

Naming Variables

🛑 Python variables can’t start with with a number. In general, they’re named all lower case, separated by underscores. Unlike other languages, that name their variables with camelCase.

You don’t want to name your variables the same as the types that we’ll be working with. For example don’t name your variables int, list, dict. Etc.

Open The REPL

Open the REPL from VS Code by opening the command palette (ctrl + shift + P on Windows, or cmd + shift + P on Mac) and selecting Python: Start REPL

Any Python code that starts with the >>>symbols indicates that it was typed into a REPL.

You can then use ctrl + `(backtick) to open and close the VS Code terminal on Mac, or ctrl + ‘ (single quote) on Windows. You won’t lose your work in the REPL unless you close VS Code.

Variables

Variables in Python allow us to store information and give it a label that we can use to retrieve that information later. 👉 We can use variables to store numbers, strings (a sequence of characters), or even more complex data types like lists and dictionaries.

We assign values to variables by putting the value to the right of an equal sign.

👉 Because Python is a dynamic language, we don’t need to declare the type of the variables before we store data in them.

That means that this is valid Python code:

> > > x = 42
> > > Unlike typed languages, the type of what’s contained in Python variables can change at any time.

For example, the below is perfectly valid Python code:

 x = 42
 x = "hello"
 Here, the value of the variable x changed from a number to a string.

When creating variables, there are a few best practices you should follow.

Naming Variables

👉 Convention says that numbers should be named in lower case, with whole words separated by underscores.

If you want to learn more about Python naming conventions look at PEP8.

👉 Because Python is a dynamic language and you don’t have type hints to explain what’s stored inside a variable while reading code, you should do your best naming your variables to describe what is stored inside of them.

It’s ok to be verbose. For example, n is a poor variable name, while numbers is a better one. If you’re storing a collection of items, name your variable as a plural.

Learn more about great naming practices for dynamic types by watching this 30-minute talk by Brandon Rhodes.

Naming Gotchas

👉 There are some things that you can’t name your variables, such as and, if, True, or False. That’s because Python uses these names for program control structure.

🛑 You can’t start your variable name with a digit, although your variable name can end in a digit. Your variable name can’t contain special characters, such as !, @, #, $, %and more.

💣 Python will let you override built-in methods and types without a warning so don’t name your Python variables things like list, str, or int.

If you notice your program behaving oddly and you can’t find the source of the bug, double check the list of built-in functions and built-in types to make sure that your variable names don’t conflict.

Types

Python has a very easy way of determining the type of something. It’s the type() function.

 num = 42
  type(num)
class 'int'>

No-Value, None, or Null Value

There’s a special type in Python that signifies no value at all. In other languages, it might be called Null. In Python, it’s called None.

If you try to examine a variable on the REPL that’s been set to None, you won’t see any output. I will talk more about the None type in another post.

> > > x = None
> > > x

NUMBERS

First, open up the REPL.

Remember, you’ll learn best if you type.

👉 There are three different types of numbers in Python: int for Integer, Float, and Complex.

# These are all integers
x = 4
y = -193394
z = 0
# These are all floats
x = 5.0
y = -3983.2
z = 0.
# This is a complex number
x = 42j

In Python, Integers and other simple data types are just objects under the hood. That means that you can create new ones by calling methods. You can provide either a number, or a string.

x = int(4)
y = int('4')
z = float(5.0)

Python also provides a decimal library, which has certain benefits over the float datatype. For more information, refer to the Python documentation.

Mathematical Operations

Numbers can be added together. If you add a float and an int, the resulting type will be a float.

If you divide two ints (integers), the result will be of type float.

Boolean Types

In Python, Booleans are of type bool. Surprisingly, the boolean types True and False are also numbers under the hood.

True is 1 under the hood. False is 0 under the hood.

That means you can do silly things, like add two Boolean numbers together.

STRINGS

Representing Strings

👉 Strings in Python can be enclosed either with single quotes like 'hello' or double quotes, like "hello".

Strings can also be concatenated (added together) using the + operator to combine an arbitrary number of Strings. For example:

1334
salutation = "Hello "
name = "Irene"
greeting = salutation + name
# The value of greeting will be "Hello Irene"

To use the same type of quote within a string, that quote needs to be escaped with a \ - backwards slash.

greeting = 'Hello, it\'s Irene'

Alternately, mixed quotes can be present in a Python string without escaping.

# Notice that the single quote ' is surrounded by
# double quotes, ""
greeting = "Hello, it's Irene"

Long multi-line strings can be represented in between """ (triple quotes), but the whitespace will be part of the string.

long_greeting = """
                Greetings and salutations, dear Irene.
                I'm superfluous with my words,
                and require more space to say Hello!"
                """

Printing Strings

Strings can be printed out using the print() function in Python. While you’re working the REPL, you’ll see that variables are displayed for you. When you move on to writing standalone Python programs, that will no longer be the case.

To use the print() function, call it with a regular or formatted string.

>>> print("Hello")
Hello
>>> name = "Irene"
>>> print(name)
Irene

### String Formatting

There are several types of string formatting in Python.

If you’re using Python 3.7 and above (remember to check with python --version on the command line) you can use my favorite type of string formatting, and the one I’ll be using for the course called f-strings.

>>> name = "Irene"
>>> greeting = f"Hello, {name}"

>>> print(greeting)
Hello, Irene

f-strings allow you to simply and easily reference variables in your code, and as a bonus, they’re much faster.

Up next