0% found this document useful (0 votes)
2 views29 pages

Python First Program

The document provides an introduction to Python programming using the IDLE environment, explaining the basics of running Python code, including the use of the print() function and the concept of the Read-Evaluate-Print Loop (REPL). It covers syntax and run-time errors, variable naming conventions, and the importance of comments in code. Additionally, it discusses data types, type conversion, and binary operations in Python.

Uploaded by

upeshpatel.ec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views29 pages

Python First Program

The document provides an introduction to Python programming using the IDLE environment, explaining the basics of running Python code, including the use of the print() function and the concept of the Read-Evaluate-Print Loop (REPL). It covers syntax and run-time errors, variable naming conventions, and the importance of comments in code. Additionally, it discusses data types, type conversion, and binary operations in Python.

Uploaded by

upeshpatel.ec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

The First Python Code

Dr. Upesh Patel & Dr. Trushit Upadhyaya


CHAROTAR UNIVERSITY OF SCIENCE & TECHNOLOGY
Integrated DeveLopment Environment

IDLE

Interactive Script
Python shell Window
Interactive Python Shell

The first line tells you what version of Python is running. In this case, IDLE is running
Python 3.9.13. The second and third lines give some information about the operating
system and some commands you can use to get more information about Python. The
>>> symbol in the last line is called the prompt.
Script Window
Interactive window - Sequence of events
1. First, Python reads the code entered at the prompt.
2. Then the code is evaluated.
3. The output is printed in the window and a new prompt is
displayed.

• For information:
• This loop is commonly referred to as a Read-Evaluate-Print Loop, or
REPL. Python programmers sometimes refer the Python shell as a
“Python REPL”, or just “the REPL” for short.
The “Hello World”
• Run the following command : Print (“Hello World”)

• To print text to the screen in Python, you use the print( ) function. A
function is a bit of code that typically takes some input, called an
argument, does something with that input, and produces some
output, called the return value.

• "Hello, world" is the argument that is being passed to print( ).

• "Hello, world" must be written with quotation marks so that Python


interprets it as text. We shall learn about string later.
Default Content Highlighting
• As you type code into the interactive window, you may notice
that the font color changes for certain parts of the code. IDLE
highlights parts of your code in different colors to help make
it easier for you to identify what the different parts are.

• By default, built-in functions, such as print() are displayed in


purple, and text is displayed in green.
Script Window
• The interactive window can execute only a single line of code at a time.
Alternatively, you can store some Python code in a text file and then
execute all of the code in the file with a single command. The code in the
file is called a script, and files containing Python scripts are called script
files.
• Enter File  New File.
• When the script window opens, the interactive window stays open. Any
output generated by code run in the script window is displayed in the
interactive window.
Running a Program in Script Window
• In the script window, type in the same code you used to print "Hello,
world" in the interactive window print("Hello, world")
• Before you can run your script, you must save it. From the menu at
the top of the window, select File  Save and save the script as
hello_world.py file. The .py file extension is the conventional
extension used to indicate that a file contains Python code.
• Note : In fact, if you save your script with any extension other
than .py, the code highlighting will disappear and all the text in the
file will be displayed in black. IDLE will only highlight Python code
when it is store in a .py file.
• Once the script is saved, all you have to do to run the program is
select Run  Run Module or alternatively press F5 to run the script.
Major Error
Types

Syntax Run-time
Error Error
Syntax Errors

• In loose terms, a syntax error occurs when you write some code that isn’t allowed in
the Python language. You can create a syntax error by changing the contents of the
hello_world.py script from the last section to the following :

• In this example, the double quotation mark at the end of "Hello, world“ has been
removed. Python won’t be able to tell where the string of text ends. Save the altered
script and then try to run it. What happens? The code won’t run! IDLE displays an alert
box with the following message:

• EOL stands for End Of Line, so this message tells you that Python read all the way to the
end of the line without finding the end of something called a string literal. A string
literal is text contained in-between two double quotation marks. The text "Hello,
world" is an example of a string literal.
• Back in the script window, notice that the line containing with "Hello, world is
highlighted in red. This handy features helps you quickly find which line of code caused
the syntax error
Run-time Errors
• IDLE catches syntax errors before a program starts running, but some
errors can’t be caught until a program is executed. These errors are known
as run-time errors because they only occur at the time that
a program is run.
• Let us generate a run-time error - change the code in hello_world.py to the
following: print(Hello, world)

Error?

• The text that gets displayed for an error is called a traceback


Elements of Python

• A Python program is a sequence of definitions and commands


(statements)
• Commands manipulate objects
• Each object is associated with a Type
• Type:
• A set of values
• A set of operations on these values
• Expressions: An operation (combination of objects and operators)
Types in Python
• int
• Bounded integers, e.g. 732 or -5
• float
• Real numbers, e.g. 3.14 or 2.0
• long
• Long integers with unlimited precision
• str
• Strings, e.g. ‘hello’ or ‘C’
Types in Python
• Scalar
• Indivisible objects that do not have internal structure
• int (signed integers), float (floating point), bool (Boolean),
NoneType
• NoneType is a special type with a single value
• The value is called None
• Non-Scalar
• Objects having internal structure
• str (strings)
Example of Types
Type Conversion (Type Cast)

• Conversion of value of one type to other


• We are used to int float conversion in Math
• Integer 3 is treated as float 3.0 when a real number is
expected
• Float 3.6 is truncated as 3, or rounded off as 4 for integer
contexts
• Type names are used as type converter functions
Type Conversion Examples
Note that float to int conversion
is truncation, not rounding off
Operators

• Arithmetic + - * // / % **
• Comparison == != > < >= <=
• Assignment = += -= *= //= /= %= **=
• Logical and or not
• Bitwise
& | ^ ~ >> <<
• Membership
in not in
• Identity
is is not
Variables
• Variables are names that can be assigned a value and used to reference that
value throughout your code. Variables are fundamental to programming for
two reasons
• Variables keep values accessible: the result of some time-consuming
operation can be assigned to a variable so that the operation does not need to
be performed each time you need to use the result.
• Variables give values context: The number 28 could mean lots of different
things, such as the number of students in a class, or the number of times a user
has accessed a website, and so on. Naming the value 28 something like
num_students makes the meaning of the value clear.
• Values are assigned to a variable using a special symbol = called the
assignment operator
• Variable names are case-sensitive, so a variable named phrase is distinct from
a variable named Phrase
Variables continued
• Rules for Valid Variable Names :
Variable names can be as long or as short as you like, but there are few rules. Variable names
can only contain uppercase and lowercase letters (A–Z, a–z), digits (0–9), and underscores (_).
However, variable names cannot begin with a digit .
• For example, phrase, string1, _a1p4a, and list_of_names are all valid variable names, but 9lives
is not.
• Descriptive Names Are Better Than Short Names For Clarity in Code
e.g. seconds_per_hour = 3600 is better than seconds = 3600 or s = 3600
• Python Variable Naming Conventions
In many programming languages, it is common to write variable names in camelCase like
numStudents and listOfNames
In Python, however, it is more common to write variable names in snake case like
num_students and list_of_names. Every letter is owercase, and each word is separated by an
underscore
• Note: The Style Guide for Python Code – PEP8 (Python Enhancement Proposals 8)
Assignment Statement

• A simple assignment statement


Variable = Expression;
• Computes the value (object) of the expression on the right hand
side expression (RHS)
• Associates the name (variable) on the left hand side (LHS) with the
RHS value
• = is known as the assignment operator.
Multiple Assignments
• Python allows multiple assignments
x, y = 10, 20 Binds x to 10 and y to 20
• Evaluation of multiple assignment statement:
• All the expressions on the RHS of the = are first evaluated before any
binding happens.
• Values of the expressions are bound to the corresponding variable on the
LHS.
x, y = 10, 20 x is bound to 21
x, y = y+1, x+1 and y to 11 at the
end of the program
Binary Operations
Op Meaning Example Remarks

+ Addition 9+2 is 11
9.1+2.0 is 11.1
- Subtraction 9-2 is 7
9.1-2.0 is 7.1
* Multiplication 9*2 is 18
9.1*2.0 is 18.2
/ Division 9/2 is 4.25 In Python3
9.1/2.0 is 4.55 Real div.
// Integer 9//2 is 4
Division
% Remainder 9%2 is 1
The // operator
• Also referred to as “integer division”
• Result is a whole integer (floor of real division)
• But the type need not be int
• the integral part of the real division
• rounded towards minus infinity
• Examples
9//4 is 2 (-1)//2 is -1 (-1)//(-2) is 0
1//2 is 0 1//(-2) is -1 9//4.5 is 2.0
The % operator
• The remainder operator % returns the
remainder of the result of dividing its first
operand by its second.

9%4 is 1 (-1)%2 is 1 (-1)//(-2) is 0


9%4.5 is 0.0 1%(-2) is 1 1%0.6 is 0.4

Ideally: x == (x//y)*y + x %y
Quick Recap – Hands on Exercises

1. Using the interactive window, display some text on the


screen by using the print() function.
2. Using the interactive window, display a string of text by
saving the string to a variable, then reference the string in
a print() function using the variable name.
3. Do each of the first two exercises again by first saving
your code in a script and running it
Comments in Script
• The most common way to write a comment is to begin a new line in
your code with the # character. When your code is run, any lines starting
with # are ignored. Comments that start on a new line are called block
comments.
• You can also write in-line comments, which are comments that appear
on the same line as some code. Just put a # at the end of the line of code,
followed by the text in your comment

Test Alt + 3 and Alt + 4 on your own…

You might also like