Lesson 2 - Python - Basic - Syntax
Lesson 2 - Python - Basic - Syntax
a. b.
Note: Python programming is case sensitive. All commands must be written in small
letter or lowercase.
Using print command – it is use to display something on screen.
Old version: (Python 2.7.1 or below)
Syntax: print "<any text or statement you want to display>", <expression>
New version: (Python 3.7.1 or higher)
Syntax: print("<any text or statement you want to display>", <expression>)
Note:
Comma or , = it suppresses newline.
= (avoid, connect the result of expression within the same line of print command)
Expression = a number, variable, formula.
<> = you have to give the content.
"" or ' ' = any text or statements inside the double quote or single quote will literally be displayed
on screen.
Backslash (\) = If the word or sentence you want to display will include the quotation (single or
double). You have to type the backslash before the word or sentence with a quotation.
Ex. print ("Welcome to \"Python\'s World\"")
4
Output: Welcome to "Python's World"
Example 1 :
Type the following code inside the python command line:
>>> print "The answer is ", 2*2
>>>print ("The answer is ", 2*2)
OUTPUT:
Exiting Python
- You can type any of these commands:
a. quit() b. exit() c. Control-Z
- then press enter key to exit command line prompt.
IDLE DEVELOPMENT ENVIRONMENT
- Acronym for IDLE stands for Integrated Development and Learning Environment.
- It was specifically use for Python.
- It has a number of features to help you develop your Python programs including
Powerful syntax highlighting.
- The IDLE tool offers a more efficient platform to write your code and work
interactively with Python.
USING WINDOWS
a. Search for IDLE Python GUI. Once you find it then Click the icon to activate.
c. The IDLE Development Environment will display.
d. To Open New File, Go to File menu Select New File or press CTRL+N Option images
below.
a. b. c.
5
- Is an interactive interpreter with colorizing of code input-output and error
messages.
a. Multi-Window Text Editor With Multiple Undo.
b. Search Within Any Window.
c. Debugger With Persistent Breakpoints.
d. Configuration, Browsers, And Other Dialogs
- It has dropdown menus and a >>> prompt command line window.
- You can type and enter statements or expressions for evaluation in the same
way that you used the command line earlier.
- It has an editing menu that allows you / user to scroll back to your previous
commands.
- You can use the following commands: cut, copy, and paste previous statements
and make modifications.
PYTHON SHELL WINDOW HAS THE FOLLOWING MENU ITEMS:
a. File c. Shell e. Options g. Help
b. Edit d. Debug f. Windows
FILE MENU - it allows you to create a new file, open an old file, open a module, and/or
save your session.
- New File option - a new/blank window will be displayed.
- A simple and standard text editor where you can type or edit your code.
- It named “untitled” but its name will soon change as you save your
code.
SHELL MENU and DEBUG MENU – it provides capabilities you would find useful when
creating larger programs.
SHELL MENU - it allows you to restart the shell or search the shell’s log to find the most
recent reset.
DEBUG MENU – it has useful menu items for tracing the source file of an exception and
highlighting the erring (error) line.
OPTIONS MENU - allows you to configure IDLE to suit your Python working references.
HELP OPTION – It opens Python Help and documentation.
- It enters a help functionality to explore all the stuff python lets you do right
from the interpreter.
- Press q to close the help window and return to the Python prompt.
6
PYTHON - BASIC SYNTAX
PYTHON SYNTAX - it refers to the set of rules that defines how human users and the
system should write and interpret a Python program.
- If you want to write and run your program in Python, you must familiarize
yourself with its syntax.
TWO PROGRAMMING MODE OF EXECUTING PYTHON PROGRAMS:
1. INTERACTIVE MODE PROGRAMMING - Invoking the interpreter without passing a
script file as a parameter brings up the following prompt.
- It is a command line shell which gives immediate feedback for each statement
while running previously fed statements in active memory.
- Using the command line prompt.
- Ex.
2. SCRIPT MODE PROGRAMMING - Invoking the interpreter with a script parameter
begins execution of the script and continues until the script is finished.
- When the script is finished, the interpreter is no longer active.
- Python files have extension .py
- Ex. Create a Script mode programming file:
- Open an IDLE Python GUI, Go to File Menu select New File
- Write the following code:
7
2. Go to the directory where the file is Save: then double click the filename:
hello.py
OUTPUT 2:
Note:
print statement version 2.x (old version) – it can be used without parentheses, it
prints everything until the end of line.
print function version 3.x (new version) – it print a proper function expecting its
arguments inside parentheses.
Input() function - it will pause the program execution at the end until you press
anything.
- If the input function is called, the program flow will stopped until the user
has given an input and has ended the input with the return key.
- The text inside the parentheses is optional parameter, i.e. the prompt, will
be printed on the screen.
Ex. Edit your source code:
input(“Thank You”)
NEW OUTPUT:
8
PYTHON IDENTIFIERS - is a name used to identify a variable, function, class, module or
other object.
- Is a name given to a function, class, variable, module, or other objects that you’ll
be using in your Python program.
- An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores and digits (0 to 9).
- Python does not allow punctuation characters such as @, $, and % within
identifiers.
- is a case sensitive programming language.
- Ex: Manpower and manpower are two different identifiers in Python.
HERE ARE NAMING CONVENTIONS FOR PYTHON IDENTIFIERS:
1. Class names start with an uppercase letter.
- Class name property – it sets or return the class name of an element (the
value of an element’s class attribute).
- All other identifiers start with a lowercase letter.
2. Starting an identifier with a single leading underscore indicates that the identifier
is private.
3. Starting an identifier with two leading underscores indicates a strongly private
identifier.
4. If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name.
Examples:
Valid identifiers Invalid identifiers
_Name Car>Class
Student_Class %interest
Student1_ 1Student_Test
RESERVED WORDS / KEYWORDS – are terms or phrases appropriate for special use that may not
be utilized in the creation of variable names.
- It cannot be used as variable name, function name, or any other identifier.
- It is used to define the syntax and structure of the Python language.
- In Python, keywords are case sensitive.
The following list shows the Python keywords. These are reserved words and you
cannot use them as constant or variable or any other identifier names. All the
Python keywords contain lowercase letters only.
9
and exec not except
elif in while
LINES AND INDENTATION – it does not provide braces to indicate blocks of code for class
and function definitions or flow control.
- Blocks of code are denoted by line indentation, which is rigidly enforced.
- The number of spaces in the indentation is variable, but all statements within the
block must be indented the same amount.
MULTI-LINE STATEMENTS – It is typically end with a new line.
- It allow the use of the line continuation character (\) to denote that the line should
continue.
Example: (filename: multi_line.py)
item_one = 10
item_two = 25
item_three = 15
print ("Total =", item_one + \
item_two + \
item_three)
Result: Total = 50
Statements contained within the [], {}, or () brackets do not need to use the line
continuation character.
For example –
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
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.
10
- The triple quotes are used to span the string across multiple lines.
- It also display the content including double quotes or single quotes
For example:
a. word = 'word' b. sentence = "This is a sentence."
c. paragraph = """This is a paragraph. "It is made up of multiple line's and sentences"."""
SAMPLE PROGRAM
PROGRAM FILENAME: Quotes_backslash_n.py
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. "It is made up of multiple line's and sentences"."""
print(word +"\n" + sentence + "\n" + paragraph)
input()
OUTPUT:
COMMENTS IN PYTHON - A hash sign (#) that is not inside a string literal begins a comment.
- All characters after the # and up to the end of the physical line are part of the comment
and the Python interpreter ignores them.
# First comment
print "Hello, Python!" # second comment
Note:
You can type a comment on the same line after a statement or expression.
name = "Madisetti" # 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 whitespace, 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.
11
MULTIPLE STATEMENTS ON A SINGLE LINE
SEMICOLON ( ; ) – it allows multiple statements on the single line given that neither
statement starts a new code block.
Example:
import sys; x = 'foo'; sys.stdout.write(x + '\n')
Note: Please read in advance Python Variables and Data Types for our next topic.
12