0% found this document useful (0 votes)
27 views23 pages

ITP313 115s

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)
27 views23 pages

ITP313 115s

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/ 23

ITP 313

Python Fundamentals and Data Types

*rga/2020
Python Fundamentals
 Program structure
 Comments and Whitespace
 Statements and Expressions
 Variables
 Data Types
 Operators
 Math functions
Python Fundamentals
Program structure
The complete classic “Hello World” program, Pythonic style.
print(“Hello World!”) #That’s it!
 No header!
 No semi-colon!
 No braces!
 One line!
 Simple!
Python Fundamentals
Whitespace
 whitespace is meaningful in python:
especially indentation and placement of newlines.
• Use a newline to end a line of code (press ENTER)
• Use \ when you must go to next line prematurely.
• No braces { } to mark blocks of code in python…
use consistent indentation instead.
• The first line with less indentation is outside of the block.
• The first line with more indentation starts a nested block
• a colon (:) appears at the start of a new block.
Python Fundamentals
Comments
• Start comments with # – the rest of line is ignored.
• Can include a “documentation string” as the first line of
any new function or class that you define.

Def myFunction(x, y):


“““this is the docstring. This
function does blah blah blah.”””
# The comment would go here...
Python Fundamentals
Primitive Data Types
int - The integer numbers (e.g. 2, 4, 20)
Float - the ones with a fractional part (e.g. 5.0, 1.6)
Complex

In addition to int and float, Python supports other types of numbers, such as
Decimal and Fraction. Python also has built-in support for complex numbers,
and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j).
Primitive Data Types
STRING
Besides numbers, Python can also manipulate strings, which can be expressed in
several ways. They can be enclosed in single quotes ('...') or double quotes ("...") with the same
result [2]. \ can be used to escape quotes:

>>> 'spam eggs' # single quotes


'spam eggs’
.

>>> 'doesn\'t' # use \' to escape the single quote...


"doesn’t”

>>> "doesn't" # ...or use double quotes instead


"doesn't"

>>> '"Yes," he said.'


‘“Yes," he said.'

>>> "\"Yes,\" he said.“ >>> '"Isn\'t," she said.'


'"Yes," he said.‘ '"Isn\'t," she said.'
Sample numeric values
int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEL 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
Type Casting In Python
Sometimes in our program, it is necessary for us to convert
from one data type to another, such as from an integer to a
string. This is known as type casting.

There are three built-in functions in Python that allow us to do


type
casting. These are the int(), float(), and str()
To change a float to an To change a string to an
functions.
integer integer
>>>int(5.712987) >>>int(“4”)
5 4

To change integer or integer or a float to a string


string to float >>>str(2.1)
>>>float(2) ‘2.1’
2.0 >>>str(2)
>>>float(“2”) ‘2’
2.0
Python Fundamentals
Math Functions some requires import math
# Math Function & Returns ( Description )
1 abs(x): The absolute value of x: the (positive) distance between x and zero.
2 ceil(x): The ceiling of x: the smallest integer not less than x.
3 exp(x): The exponential of x: e
4 floor(x): The floor of x: the largest integer not greater than x.
5 log(x): The natural logarithm of x, for x > 0.
6 log10(x): The base-10 logarithm of x for x > 0.
7 max(x1, x2,...): The largest of its arguments: the value closest to positive infinity
8 min(x1, x2,...): The smallest of its arguments: the value closest to negative infinity.
9 pow(x, y): The value of x**y.
round(x [,n]): x rounded to n digits from the decimal point. Python rounds away
10
from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
11 sqrt(x): The square root of x for x > 0.
Python Fundamentals
Type casting Functions
# Function & Description
1 int(x [,base]): Converts x to an integer. The base specifies if x is a string.
2 float(x): Converts x to a floating-point number.
3 complex(real [,imag]): Creates a complex number.
4 str(x): Converts object x to a string representation.
5 repr(x): Converts object x to an expression string.
6 eval(str): Evaluates a string and returns an object.
7 chr(x): Converts an integer to a character.
8 unichr(x): Converts an integer to a Unicode character.
9 ord(x): Converts a single character to its integer value.
What are variables?
Variables are names given to data that we need to store and manipulate in our
programs.

For instance, suppose your program needs to store the age of a user. To do that, we
can name this data userAge and define the variable age using the following
statement.

age = 0
We can also define multiple variables at one go. To do that simply write

userAge, userName = 30, ‘Peter’


Naming a Variable

1. A variable name in Python can only contain letters (a - z, A -


Z), numbers or underscores (_).
2. First character cannot be a number.

3. Cannot use reserved words.

4. Variable names are case sensitive

There are two conventions when naming a variable in Python. We


can
either use the Camel case notation or use underscores.

1. thisIsAVariableName

2. this_is_a_variable_name
Python Fundamentals
Variables
follows same naming convention as C, C++, Java
Primitive Data Types
bool, int, long, float, complex, string

Variable Declaration
Data typing is implicit and automatic upon
assignment
a=0 integer
b = 123L long integer
x = 1.23 float
s = “abc” string
s = ‘abc’ string
isEven = (n % 2 == 0) Boolean
The Assignment Sign
Note that the = sign in the statement userAge = 0 has a different
meaning from the = sign we learned in Math. In programming, the = sign
is known as an assignment sign. It means we are assigning the value on
the right side of the = sign to the variable on the left. A good way to
understand the statement userAge = 0 is to think of it as userAge <-
0.
The statements x = y and y = x have very different meanings in
programming.

Assignment Operator
a=b=c=0 multiple assignments
j, k = 0, 1 multiple assignments
x, y = y, x one-step variable swap
Type the following code into your IDLE
editor.

?
x = 5
y = 10
x = y
print ("x = ", x)
print ("y = ", y)

You should get this output:


x = 10
y = 10
Arithmetic Operators

Integer: + - * // %
2%3 = 2
2//3 = 0

Float: + - * / **
2/3 = 0.6666 as expected
2**3 = 8 means 2^3
Relational Operators

<, >, <=, >=, ==, != <> not supported in ver. 3.x
x % 2 <> 0 test for odd
x % 2 !== 0 test for odd
1<x<5 x is between 1 and 5
1<=x<=5 x is within 1 through 5

Logical Operators

not, and, or
not(1<x and x<5) same as not(1<x<5)
ans ==‘y’ or ans==‘n’
More Assignment Operators
Besides the = sign, there are a few more assignment operators in Python
(and most programming languages).

These include operators like +=, -= and *=.

Suppose we have the variable x, with an initial value of 10. If we want


to
increment x by 2, we can write
x = x + 2
we can also write x += 2 to express the same
meaning.
The += sign is actually a shorthand that
combines the assignment sign with the addition
operator.
Similarly, if we want to do a
subtraction, we can write x = x -
2 or x -= 2.

*The same works for all the 7


operators mentioned in the section
above.
Errors and Exceptions

There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.

Syntax Errors
Syntax errors, also known as parsing errors, are perhaps the most common kind of
complaint you get while you are still learning Python:

>>> print('Hello")
SyntaxError: EOL while scanning string literal

The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest
point in the line where the error was detected. The error is caused by (or at least
detected at) the token preceding the arrow: in the example, the error is detected at the
function print(), since a colon (') is missing before it. File name and line number are
printed so you know where to look in case the input came from a script.
Exceptions
Even if a statement or expression is syntactically correct, it may cause an error when an attempt
is made to execute it. Errors detected during execution are called exceptions and are not
unconditionally fatal: you will soon learn how to handle them in Python programs. Most
exceptions are not handled by programs, however, and result in error messages as shown here:

>>> 10 * (1/0)

>>> 4 + spam*3

>>> '2' + 2
References:

Python 3.7.4 Documentation – Python Tutorial

Copyright
Python and this documentation is:
Copyright © 2001-2019 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives.
All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights
reserved.

© Copyright 2001-2019, Python Software Foundation

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy