UNIT TWO
Python basic syntax and variable types
This unit helps you by covering the following objectives:
Basic syntax-comments
identifiers, keywords
line indentation, multi-line statements, quotations, blank lines.
print function and input function.
python variables- types.
assigning values to variables, multiple assignments.
Typical Python file structure.
Getting help and Zen of python.
summary
Exercises
Department of Computer Science, EIT Cosc142 Page 1 of 13
UNIT 2
Python basic syntax
The Python language has many similarities to Perl, C and Java. However, there are some
definite differences between the languages. This chapter is designed to quickly get you up to
speed on the syntax that is expected in Python.
Some rules and certain symbols are used with regard to statements in Python:
Hash mark ( # ) indicates Python comments
Newline ( \n ) is the standard line separator (one statement per line)
Backslash ( \ ) continues a line
Semicolon ( ; ) joins two statements on a line
Colon ( : ) separates a header line from its suite
Suites delimited via indentation
Python files organized as "modules"
Statements
A statement is a unit of code that the Python interpreter can execute. We have seen two kinds
of statements: print and assignment. When you type a statement in interactive mode, the
interpreter executes it and displays the result.
A script usually contains a sequence of statements. If there is more than one statement, the
results appear one at a time as the statements execute.
For example, the script
>>>print(1)
>>>x = 2
>>>print(x)
Produces the output
1
2
Controlling the print Function
We would prefer that the cursor remain at the end of the printed line so when the user types a
value it appears on the same line as the message prompting for the values. When the user
presses the enter key to complete the input, the cursor automatically will move down to the
next line.
The print function as we have seen so far always prints a line of text, and then the cursor
moves down to the next line so any future printing appears on the next line.
The print statement accepts an additional argument that allows the cursor to remain on the
same line as the printed text:
print('Please enter an integer value:', end=' ')
The expression end=’’ is known as a keyword argument. The term keyword here means
something different from the term keyword used to mean a reserved word.
Department of Computer Science, EIT Cosc142 Page 2 of 13
Example
print('A', end=' ')
print('B', end=' ')
print('C', end=' ')
print()
print('X')
print('Y')
print('Z')
Output
>>>
ABC
X
Y
Z
>>>
Another keyword argument allows us to control how the print function visually separates the
arguments it displays. By default, the print function places a single space in between the items
it prints. Print uses a keyword argument named sep to specify the string to use insert between
items. The name sep stands for separator. The default value of sep is the string ’ ’, a string
containing a single space. Shows the sep keyword customizes print’s behavior.
w, x, y, z = 10, 15, 20, 25
print(w, x, y, z)
print(w, x, y, z, sep=',')
print(w, x, y, z, sep='')
print(w, x, y, z, sep=':')
print(w, x, y, z, sep='-----')
output
>>>
10 15 20 25
10,15,20,25
10152025
10:15:20:25
10-----15-----20-----25
>>>
Keywords (reserved words):
Keywords are the reserved words in Python. These reserved words may not be used as variable
name, function name or any other identifier. They are used to define the syntax and structure of
the Python language. We must note that keywords are case sensitive. Foe example “if” is a
keyword but “If” is not a keyword. They are not the same.
There are 33 keywords in Python 3.x. This number can vary slightly in course of time. All the
keywords except True, False and None all are in lowercase and they must be written in
lowercase. The list of all python the keywords is given below.
Department of Computer Science, EIT Cosc142 Page 3 of 13
Keywords in Python programming language
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Identifiers:
An Identifier is a name used to identify a class, function, variable, module or other object. in
Python. It helps differentiating one entity from another.
Rules for writing identifiers in Python
1. 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 (_). For example we can use myClass, var_1 and
print_this_to_screen, all are valid identifiers.
2. An identifier cannot start with a digit. For example “1variable” is invalid identifier, but
“variable1” is valid identifier.
3. Keywords cannot be used as identifiers.
4. We cannot use special characters such as @, #, $, !, % etc. in our identifier.
5. Identifier can be of any length.
6. Python is a case-sensitive language. This means, Variable and variable are not the
same.
Identifier naming conventions for python
Class names start with an uppercase letter and all other identifiers with a lowercase
letter.
Starting an identifier with a single leading underscore indicates by convention that the
identifier is meant to
be private.
Starting an identifier with two leading underscores indicates a strongly private
identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.
Single Statement on Multiple Lines:
Statements in Python typically end with a new line. Python does, however, allow the use of the
line continuation character (\) to denote that the line should continue. For example:
total = 1 + \
2+\
3
Department of Computer Science, EIT Cosc142 Page 4 of 13
Statements contained within the [], {} or () brackets do not need to use the line continuation
character. For example:
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Multiple Statements on a Single Line:
In Python it is possible have multiple statements on one line by putting semicolon (;) at the end
of each statement. Here is an example:
y=60;x=50;c=y+x; print(c)
Note: In Python to print new line we can use the special character “\n”. For example:
X=input(“\n\n Enter your name from the keyboard”)
In the above example “\n\n” is being used to create two new lines before displaying the actual
line. Once the user presses the Enter key, the program ends. This is a nice trick to keep a
console window open until the user is done with an application.
Lines and Indentation in Python:
Python uses a different principle. Programs get structured
through indentation, this means that code blocks are defined
by their indentation.
The number of spaces in the indentation is variable, but all
statements within the block must be indented the same
amount. Both blocks in this example are fine:
if True:
print ("True")
else:
print("False")
However, the second block in this example will generate an error:
if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False")
Multiple Statement Groups as Suites:
A group of individual statements, which make a single code block are called suites in Python.
Compound or complex statements, such as: if, while, def, and class, are those which require a
header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a colon (:) and are
followed by one or more lines which make up the suite. For example:
Department of Computer Science, EIT Cosc142 Page 5 of 13
if expression :
suite
elif expression :
suite
else :
suite
Quotation in Python:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long
as the same type of quote starts and ends the string.
The triple quotes can be used to span the string across multiple lines. For example, all the
following are legal:
word = 'word'
sentence = "This is a sentence.".
paragraph =”“"This is a paragraph. It is
made up of multiple lines and sentences “””
Comments in Python:
A hash sign (#) that is not inside a string literal begins a comment. All characters after the #
and up to the physical line ends are part of the comment and the Python interpreter ignores
them.
#!/usr/bin/python
# First comment
Print ("Hello, Python!"); # second comment
This will produce the following result:
Hello, Python!
A comment may be on the same line after a statement or expression:
name = "Helen" # This is again comment
You can comment multiple lines as follows:
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
Using Blank Lines:
A line containing only white space, possibly with a comment, is known as a blank line and
Python totally ignores it.
In an interactive interpreter session, you must enter an empty physical line to terminate a
multiline statement.
The input Function:
The print function enables a Python program to display textual information to the user.
Programs may use the input function to obtain information from the user. The simplest use of
the input function assigns a string to a variable:
Department of Computer Science, EIT Cosc142 Page 6 of 13
x = input()
The parentheses are empty because, the input function does not require any information to do
its job. Demonstrates that the input function produces a string value.
Let's have a look at the following example:
>>> name = input("What's your name? ")
What's your name? Kidane
>>> print("Nice to meet you " + name + "!")
Nice to meet you Kidane!
>>> age = input("Your age? ")
Your age? 25
>>> print("So, you are are already " + age + " years old, " + name + "!")
So, you are are already 25 years old, Kidane!
Let's have a look at the following example:
name = input("What's your name? ")
print("Nice to meet you " + name + "!")
age = input("Your age? ")
print("So, you are already " + str(age) + " years old, " + name + "!")
We save the program as " [Link] " and run it and see the output
>>>
What's your name? bsr
Nice to meet you bsr!
Your age? 37
So, you are already 37 years old, bsr!
>>>
Quite often we want to perform calculations and need to get numbers from the user. The input
function produces only strings, but we can use the int function to convert a properly formed
string of digits into an integer.
Example1: Type the following code in python editor, save and run it.
print('Please enter an integer value:')
x = input()
print('Please enter another integer value:')
y = input()
num1 = int(x)
num2 = int(y)
print(num1, '+', num2, '=', num1 + num2)
Output
>>>
Please enter an integer value:
23
Please enter another integer value:
24
23 + 24 = 47
>>>
Department of Computer Science, EIT Cosc142 Page 7 of 13
Example2: Type the following code in python editor, save and run it.
num1 = int(input('Please enter an integer value: '))
num2 = int(input('Please enter another integer value: '))
print(num1, '+', num2, '=', num1 + num2)
output
>>>
Please enter an integer value: 12
Please enter another integer value: 34
12 + 34 = 46
>>>
The eval Function
The input function produces a string from the user’s keyboard input. If we wish to treat that
input as a number, we can use the int or float function to make the necessary conversion:
x = float(input('Please enter a number'))
Here, whether the user enters 2 or 2.0, x will be a variable with type floating point. What if we
wish x to be of type integer if the user enters 2 and x to be floating point if the user enters 2.0?
Python provides the eval function that attempts to evaluate a string in the same way that the
interactive shell would evaluate it.
Example1: Type the following code in python editor, save and run it.
x1 = eval(input('Entry x1? '))
print('x1 =', x1, ' type:', type(x1))
x2 = eval(input('Entry x2? '))
print('x2 =', x2, ' type:', type(x2))
Output
>>>
Entry x1? 2
x1 = 2 type: <class 'int'>
Entry x2? 5.9
x2 = 5.9 type: <class 'float'>
>>>
Python variable types
A variable is an identifier, which holds a value. In programming we say, that we assign a
value to a variable.
Technically speaking, a variable is a reference to a computer memory, where the value is
stored.
In Python language, a variable can hold a string, a number or various objects like a function or
a class.
Department of Computer Science, EIT Cosc142 Page 8 of 13
Variables can be assigned different values over time. Based on the data type of a variable, the
interpreter allocates memory and decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can store integers, decimals or
characters in these variables.
Variable names
There are just a couple of rules to follow when naming your variables.
Variable names can contain letters, numbers, and underscore.
Variable names cannot contain spaces.
Variable names cannot start with a number.
Case sensitive—for instance, temp and Temp are different
Assigning Values to Variables:
Python variables do not have to be explicitly declared to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal sign (=) is
used to assign values to variables (The equal sign (=) is Python assignment operator). The
operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable .
The simplest form of assignment statements in Python are of the form variable = value:
For example:
>>>counter = 100 # An integer assignment
>>>miles = 1000.0 # A floating point
>>>name = "John" # A string
>>>print (counter)
>>>print (miles)
>>>print (name)
Here, 100, 1000.0 and "John" are the values assigned to counter, miles and name variables,
respectively. While running this program, this will produce the following result:
100
1000.0
John
Multiple Assignments:
Python allows you to assign a single value to several variables simultaneously. For example:
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables. For
example:
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b, and one string
object with the value "john" is assigned to the variable c.
Department of Computer Science, EIT Cosc142 Page 9 of 13
Chaining together assignments is okay
>>> y = x = x + 1
>>> x, y
(2, 2)
One interesting side effect of Python's "multiple" assignment is that we no longer need a
temporary variable to swap the values of two variables. # swapping variables in Python
>>> x, y = 1, 2
>>> x
1
>>> y
2
>>> x, y = y, x
>>> x
2
>>> y
1
Typical Python file structure
1. Startup line
Generally used only in Unix environments, the start-up line allows for script execution by
name only (invoking the interpreter is not required).
2. Module documentation
Department of Computer Science, EIT Cosc142 Page 10 of 13
Summary of a module's functionality and significant global variables; accessible externally as
module.__doc__.
3. Module imports
Import all the modules necessary for all the code in current module; modules are imported
once (when this module is loaded); imports within functions are not invoked until those
functions are called.
4. Variable declarations
Declare (global) variables here which are used by multiple functions in this module (if not,
make them local variables for improved memory/performance).
5. Class declarations
Any classes should be declared here, along with any static member and method attributes; class
is defined when this module is imported and the class statement executed. Documentation
variable is class.__doc__.
6. Function declarations
Functions which are declared here are accessible externally as [Link](); function is
defined when this module is imported and the def statement executed. Documentation variable
is function.__doc__.
7. "main" body
All code at this level is executed, whether this module is imported or started as a script;
generally does not include much functional code; rather, gives direction depending on mode of
execution
Getting help
The help command provides some help about Python.
>>> help
Type help() for interactive help, or help(object) for help about object.
>>>
We can use the command in two ways. Either we can get some help about a specific object or
we enter a interactive help mode.
>>> help()
To leave the help mode and return to the interpreter, we use the quit command.
Finally, we want to exit the interpreter. We can exit the interpreter in two ways:
Ctrl + D quit ()
help> keywords # Displays list of keywords
The Zen of Python
The Zen of Python is a set of rules how to write good Python code. It reflects somehow the
philosophy of the language.
>>> import this # This displays the following output
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Department of Computer Science, EIT Cosc142 Page 11 of 13
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Summary
A variable name is an example of an identifier.
The name of a variable must follow the identifier naming rules.
All identifiers must consist of at least one character. The first symbol must be an alphabetic
letter or the underscore. Remaining symbols (if any) must be alphabetic letters, the
underscore, or digits.
Reserved words have special meaning within a Python program and cannot be used as
identifiers.
Descriptive variable names are preferred over one-letter names.
Python is case sensitive; the name X is not the same as the name x.
The = operator means assignment, not mathematical equality.
A variable can be reassigned at any time.
A variable must be assigned before it can be used within a program.
Multiple variables can be assigned in one statement.
A variable represents a location in memory capable of storing a value.
The statement a = b copies the value stored in variable b into variable a.
Python supports both integer and floating-point kinds of numeric values and variables
The input function reads in a string of text entered by the user from the keyboard during the
program’s execution.
The input function accepts an optional prompt string.
The eval function can be used to convert a string representing a numeric expression into its
evaluated numeric value.
Try the following
1. What is a keyword? and statement? Give 2 examples.
2. Why do we use comments? (what is their purpose)
3. How is a statement normally terminated in Python?
i. How can you make a single statement span multiple lines?
4. How can you code a compound statement on a single line?
5. Is there any valid reason to type a semicolon at the end of a statement in Python?
6. What is the most common coding mistake among Python beginners?
Department of Computer Science, EIT Cosc142 Page 12 of 13
Exercises
1. Identifiers. Why are variable type declarations not used in Python?
2. Identifiers. Why are variable name declarations not used in Python?
3. Statements. Can multiple Python statements be written on a single line?
4. Statements. Can a single Python statement be written over multiple lines?
5. Variable assignment.
(a) Given the assignment x, y, z = 1, 2, 3, what do x, y, and z contain?
(b) What do x, y, and z contain after executing: z, x, y = y, z, x?
6. Will the following lines of code print the same thing? Explain why or why not.
a) x = 6
print(6)
print("6")
b) x = 7
print(x)
print("x")
7. What happens if you attempt to use a variable within a program, and that variable has
not been assigned a value?
8. What is wrong with the following statement that attempts to assign the value ten to
variable x? 10 = x
9. What is the difference between the following two strings? ’n’ and ’\n’?
10. write a python program to swap two variables
# To take input from the user
# x = input('Enter value of x: ')
# y = input('Enter value of y: ')
x=5
y = 10
# create a temporary variable and swap the values
temp = x
x=y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Output
The value of x after swapping: 10
The value of y after swapping: 5
In this program, we use the temp variable to temporarily hold the value of x. We then put the
value of y in x and later temp in y. In this way, the values get exchanged.
----- End Of Chapter Two----
Department of Computer Science, EIT Cosc142 Page 13 of 13