[go: up one dir, main page]

0% found this document useful (0 votes)
1 views9 pages

MAC_py_1

The document provides an overview of Python 3, highlighting its simplicity, versatility, and wide-ranging applications in various fields such as data science and web development. It covers fundamental concepts including variable naming rules, data types (integers, floats, complex numbers), input/output methods, and basic mathematical operations. Additionally, it discusses Python's syntax for formatting output, commenting, and using the interpreter as a calculator.

Uploaded by

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

MAC_py_1

The document provides an overview of Python 3, highlighting its simplicity, versatility, and wide-ranging applications in various fields such as data science and web development. It covers fundamental concepts including variable naming rules, data types (integers, floats, complex numbers), input/output methods, and basic mathematical operations. Additionally, it discusses Python's syntax for formatting output, commenting, and using the interpreter as a calculator.

Uploaded by

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

Python 3 for students

Python is a high-level programming language that has become one of the world's most popular
languages today. Its syntax is simple and minimalistic, allowing developers to write clean and elegant
code. Python also offers several advantages over other high-level languages, which we will explore in
due course. Python has proven to be an exceptionally versatile language, with wide-ranging
applications in basic science, engineering, data science, data management, machine learning(ML),
deep learning, networking, web development, and more. A vast number of scientific modules and
libraries have been developed for Python.As an open-source language, it enjoys strong community
support worldwide.

Unlike FORTRAN, C, or C++, Python is an interpreted language. This means that code is executed line-
by-line directly in the Python interpreter or shell, rather than requiring the entire program to be
compiled first. However, when programs become longer and more complex, they are typically written
in files (known as Python scripts) and then executed as complete programs. Python supports both
functional programming and object-oriented programming (OOP) paradigms, making it highly flexible
for various types of software development.

Variables
A variable name (or any identifier such as a class, function, module, or object name) in Python can
consist of letters, numbers, and the underscore (_) symbol. However, special characters such as @, $,
%, *, and mathematical operators like +, -, /, etc., cannot be used in variable names.

Variable names must begin with a letter (either uppercase or lowercase, A–Z) and cannot start with a
number. Additionally, variable names are case-sensitive—for example, Xy, xy, and xY are all considered
different variables.

Importantly, variable names cannot be Python reserved words (also called keywords), which are
special words reserved for system commands and functions. These keywords are written in lowercase
and must not be used as variable names.

and, assert, break, class, continue, def, del, elif, except, exec,
finally, for, from, global, if, import, in, is, lambda, not, or, pass,
print, raise, return, try, while, with, yield

Numbers
There are three different kinds of numbers that a computer program usually handles: integer, float
(real numbers with decimal part) and complex (a+ bj, j=√−1). Python supports all three kinds. Integers
in Python 3 are of unlimited size. Python 2 has two integer types: - int and long. There is no 'long
integer' type in Python 3 anymore. In addition, Booleans are a subtype of plain integers.

Integer [Examples: 236, -123] Float (or floating point numbers)[Examples: 13.25, 0.0, -13.23] Complex [Examples: 5j, 9.8j, 3+2j, 1.2e-10j] Long
[Examples: Any integer that ends with ‘l’ or ‘L’. 123L will be treated as long in Python 2.] Boolean: True, False

In [ ]: # Mathematical Operators
#Consider two variables a and b. The following operations are with
# a=20, b=4
# Addition a+b=24
# Subtraction a-b=16
# Multiplication a*b=80
# Division a/b=5.0
# Modulo a%b=0
# Power or exponent (**) a**b=160000
#--------------------------------------------------------------
# Apart from math operators we have other kinds of operators too.
# Comparison Operators
# == Equal to
# != Not equal to
# <> Less than and Greater than < Less than
# > Greater than
# >= Greater than equal to <= Less than equal to

Input and Output (I/O):


In [3]: # Styles of taking input
# Style no 1
x = 15
y = 12.6
z = -10
# Here the value of the variable is fixed

In [5]: print(x,y,z)

15 12.6 -10

In [7]: # Style no 2
x, y, z = 15, 12.6, -10 # [Multiple inputs in one line]
print(x,y,z)

15 12.6 -10

In [52]: # Style no 3
a = eval(input("Enter value")) # output after entering 12
# The built-in function eval() is used to evaluate the input string.
# Thus, we get back the number from a string of number.

In [53]: b= eval(input("Enter value \t")) # output after entering 10, \t for tab space

In [55]: a = eval(input("Enter value \n")) # output after entering 12, \n for a new line

Output Styles
‘ \n’)The syntax: print(values, sep = ‘ ’, end =‘ \n’) It prints values with gap (if no separation is mentioned and the cursor stops on the new line
due to ‘\n’ as default.)

In [56]: x, y = 2, 3
print(x, y)

2 3

In [57]: print('values = ', x, y, sep = ',')

values = ,2,3
In [62]: print( x, y, sep = ',', end = ' ')

2,3

Formatted Output
Formatting is to write output strings/ data in predefined styles or formats. We can give any number of
spaces in between two elements, create new lines etc. as we represent the output data in a way we
wish. The formatting is done with strings and so it is called string formatting.

In [63]: x, y = 4, 5
print(x, y) # Unformatted

4 5

In [64]: print('{0} and {1}'.format(x, y)) # Positions: 0 & 1

4 and 5

In [65]: print('{1} and {0}'.format(x, y)) # Positions altered

5 and 4

In [81]: pi,e= 3.141592653589793,2.718281828459045

In [82]: print('{:.3f}'.format(pi)) # Fixing decimal places by f

3.142

In [83]: print('{0:.4f},{1:.5f}'.format(pi, e))

3.1416,2.71828

In [84]: print ('{1:.4f},{0:.5f}'.format(pi, e)) # wrong positio

2.7183,3.14159

In [85]: x, y, z = 35.8679, 12.6354, 123.7823

In [86]: print ('{0:.2f}, {1:.2f}, {2:0.2f}'.format(x, y, z))

35.87, 12.64, 123.78

In [88]: # Express a percentage


'Approx value ={:.2%}'.format(x)

Out[88]: 'Approx value =3586.79%'

Commenting
As we write standard Python scripts, we take care of the readability to others and, we make it easier
for our own reading later. For this purpose, we write documentation, title etc. inside a script.

Comment a Single Line We can comment a line if we put a # (hash) symbol in front of line. This means, the compiler will ignore this line, yet we
can keep this in a code.Comment a Block of Lines Also, we can comment a block of text or code with triple quotes. (On IDLE interpreter or
Python shells, this usually makes a change of text color of that block, to be identified easily.)

In [ ]:
Typing on Python Interpretor
Let us begin to type on Python IDLE interpreter (>>>) or command line [IDLE = Integrated
Development and Learning Environment]. We type some line or some instruction on the interpreter
and then‘Enter’ key to execute. The line that appears below is the output or some message that it
returns. Sometimes, nothing returns as output which indicates that the instruction is accepted
without error. Else, we may get an error message.] We must type anything from the start (from the
first column) on interpreter or inside any Python shell. We are not allowed to press ‘space bar’ before
we write. In the latter case, it will raise error. Each line is an instruction. A set of Python instructions
will form a Python code. We can write the lines in a file which is usually called Python script. Python
scripts (programs or codes) are automatically saved with extension .py. Example: somefile.py

In [1]: dir(list)
Out[1]: ['__add__',
'__class__',
'__class_getitem__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getstate__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']

In [2]: help(list.pop)

Help on method_descriptor:

pop(self, index=-1, /)
Remove and return item at index (default last).

Raises IndexError if list is empty or index is out of range.

In [17]: a=[3,34,64,12,-234,35,-24,0,245]
b =[3, 4,6 ,1 ,-234,35,-2 ,0,25,'a']
#print(type(a))
type(a)
print(a)
print(b)

[3, 34, 64, 12, -234, 35, -24, 0, 245]


[3, 4, 6, 1, -234, 35, -2, 0, 25, 'a']

In [23]: print(list(range(5)))
print(list())

[0, 1, 2, 3, 4]
[]

In [25]: print(a)

[3, 34, 64, 12, -234, 35, -24, 0, 245]

Python as Calculator
Python interpreter or Python shell can be used as a calculator.

In [3]: # Operations with Real Numbers :Mathematical Operations


5 + 3.4 # Sum of int and float

Out[3]: 8.4

In [5]: 19 - 6 # Subtraction

Out[5]: 13

In [6]: 2 * 9 # Multiplication

Out[6]: 18

In [10]: 58/2 # Division 29.0

Out[10]: 29.0

In [11]: 13.5//2 # Floor division 6.0

Out[11]: 6.0

In [12]: (52*5 - 6.1)/4 # Simplification 63.475

Out[12]: 63.475

In [13]: 2**4 # Power

Out[13]: 16

In [14]: 13%5 # Modulo: It returns the remainder

Out[14]: 3

In [16]: # Operations with Complex Numbers


3 + 9j

Out[16]: (3+9j)

In [18]: (3+9j)+(3+2.4j)
Out[18]: (6+11.4j)

In [19]: (3 + 2j) * (4 + 5j)

Out[19]: (2+23j)

Note: Python computes in the mixed mode. For mathematical operations involving integer, float, and
complex numbers, Python returns the output in complex. We can think of complex as broader than a
float and a float as broader than an integer. Python will return in the broadest of all.

Operations with Boolean Numbers


The Boolean objects, True = 1, False = 0.

In [20]: True + True

Out[20]: 2

In [21]: True + False

Out[21]: 1

In [22]: True - False

Out[22]: 1

In [23]: True * False

Out[23]: 0

Comparison of Numbers
In [24]: 2 > 3

Out[24]: False

In [25]: 3 < 9

Out[25]: True

In [26]: 5 == 6

Out[26]: False

In [27]: 6 != 8 # Not equal to True

Out[27]: True

In [28]: 5.0 >= 4.99 # Greater than equal True

Out[28]: True

In [29]: 10%3 == 1
Out[29]: True

Type()
The built-in function type() determines the type of an object.

In [31]: type(89) # Integer

Out[31]: int

In [32]: type(15.67) # Floating point number

Out[32]: float

In [33]: type(3 + 5j) # Complex number

Out[33]: complex

In [34]: type('Python')

Out[34]: str

In [35]: type(True)

Out[35]: bool

In [37]: type(False)

Out[37]: bool

Numbers: integer, float, complex


In [38]: float(23) # Decimal fraction 23.0

Out[38]: 23.0

In [39]: int(23.58) # The integer part 23

Out[39]: 23

In [40]: complex(2) # Complex number (2+0j)

Out[40]: (2+0j)

In [41]: complex(2, 3)

Out[41]: (2+3j)

Absolute values
In [42]: abs(-23.56) # Absolute value 23.56

Out[42]: 23.56
In [43]: int(abs(-23.56))

Out[43]: 23

In [44]: abs(3 + 4j)

Out[44]: 5.0

In [45]: pow(2, 4) # 2^4

Out[45]: 16

In [46]: min(0, -2, 1, 10)

Out[46]: -2

In [47]: max(0, -2, 1, 10)

Out[47]: 10

Rounding off
In [48]: round(13.145) # [Rounding off to nearest integer]

Out[48]: 13

In [49]: round(23.9237, 2) # [Round off to 2 decimal digits]

Out[49]: 23.92

In [50]: round(23.9237, 3) # [Round off to 3 decimal digits]

Out[50]: 23.924

In [51]: round(1/3, 3)

Out[51]: 0.333

Note: If nothing is specified, round()function rounds off the decimal number to the nearest integer
(ceiling or floor of the number)

In [ ]:

You might also like