0 ratings0% found this document useful (0 votes) 45 views10 pagesComplex Numbers
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
rogramming,
Problem Solving with Python P;
>>> float(13) aa
13.0
>>> float(1.23)
1.23
>>> float(".12")
-12.0
>>> float("-2.71")
-2.71
>>> float("3.14")
3.14
2.12 Complex Numbers
Numbers with both real and imaginary part are known as complex number
‘An imaginary number is the square root of 1. In mathematics, they are ofter
denoted using i. However, in engineering, i is often used to denote elcctne
current. Hence it is customary to use j to denote the imaginary number
To create a complex number we can use either literals or cospler
constructor
2.12.1 Complex Literals
The literals are specified using the x + yj notation. For numbers with negative
imaginary part, use x - yj notation. The real part cnn be exchided to create
a fully imaginary number. Both j and J can be used for itmaginary part
>>> 1 - 3)
(1-3j)
o> 1 + 25
(1425)
>>> 3.2 - 53
(3.2-5j)
>>> 73
7j
2.12.2 complex(real=0, imag=0)
The constructor is another way used to create a complex number. It takes two
arguments which if not given has 0 as the default. We can also puss a string
as an argument to construct a complex number from it.Problem Solving with Python Programming Q%
+ Free and open source - Python is freely available and can be downloade
from the official website. Anyone can download it, change it, use it ang
distribute it.
+ Interpreted Innguage - In Python, code is executed line by line. This
makes the debugging process easy.
Large standard library - It contains a rich set of modules and functions
that helps in rapid application development.
* GUI support - Graphical user interface applications can be developed
using Python.
* Dynamically typed - In Python, there is no need to specify the data type
of a variable. The type of variable is decided during runtime
2.4 Applications
Web - Python contains libraries that can handle Internet protocol. It can
be used to develop web applications.
© GUI - Using Python builtin modules and libraries, we can create GUL
applications. Python offers many options for developing GUI, out of
which tkinter is the most commonly used method.
© Software development - Professional software can be developed using
Python.
* Business - Management software use Python for plotting and creating
charts.
© Games and 3D graphics - We can create games in Python using modules
like pygame.
© Scientific usage - Python supports a huge variety of libraries for scientific
and numeric computing.
Database integration - Python can connect to various databases for
exchange of information.
© Education - Python is taught in schools and colleges in programming
courses.7 Data Types
2.5 Python Interpreter
When we write a code in Python, it is converted into structured code objects
which can be understood by the interpreter. When the interpreter understands
the code, it executes them to produce the output
There are 2 basic modes in Python:
1. Senpt mode
2. Interactive mode
{
ee ee oe
2.5.1 Interactive Mode
In interactive mode, as the name suggests, the user can interact with the
interpreter. The Python console is used for interactive mode. Unlike Java, C
and C-+, in Python we can write a statement in the console and it will be
interpreted line by line. We do not have to compile the program and then run
it We can get the output immediately.
In the interactive mode, a single line or multiple lines of Python code can
be given and it will give a quick feedback for each statement, All the user has
to do is to write the code in python console and press Enter, and the output
will be shown in the next line
For example, we can perform a simple task of adding two numbers
>> 344
a
Or we can ask Python to display a messageProblem Solving with Python Programm! &
>>> print (“Hello world”)
Hello world
Advantages
* Beneficial as we can experiment and explore.
@ It is easy for beginners to use and understand the syntax. They can alsy
try variations on the syntax
# [¢ gives output immediately and hence it can be used to test how certain
codes work
# It is useful for implementing smaller codes
visadvantages
The code is lost when the console is closed.
# Difficult to write and edit huge programs
2.5.2 Script Mode
When a long piece of code has to be written, script mode is used. We cas
import files and multiple modules in this mode. In script mode, the result is
not displayed immediately. Once the code is written, we can save it with py
extension and execute the whole program together using the interpreter.
Let us write a sample program to add three numbers. Save the following
code snippet as sum. py.
a= 10
b=3
c=T
deatbec
print(d)
If you are on IDLE, then you can run the program via the Run option at meso
After execution, the output should be as below
209 Data Types
2.5.3 Differences
Interactive Mode Script Mode
The code is typed at the prompt. The code is executed from a script.
Useful for exploring the language. Useful for huge programs.
Supports a single line or block of code. Supports multiple blocks of code.
Does not save the code. Code can be saved.
Output is shown immediately. Output shown at execution only
2.6 Data Types
A value can be anything—a number, letter or a string. The clasification
of these values based on the operations that can be done on them is called
data type. The type of data, the memory space it takes and the type of
mathematical. logical or relational operations that can be done on each data
type differs,
Number Sequence Set__ Mapping _ Null
int str set dict None
float list
complex tuple
bool
2.6.1 Number
These data types hold any kind of numeric value.
ant
These are the positive or negative whole number values. They do not contai
a decimal point. For example, 25, -8, 2001 are integers
float
These are real numbers with floating point. It consists of a fractional part, For
example, 5.4, 83.0, 99.999 are floating point values.
complex
These values consist of a real part and an imaginary part. They are of the
form x + yj, where j is the square root of -1. x is the real part and y is the
imaginary part. For example, 2 + 8}, 7 - 5j are complex uumbersProblem Solving with Python Programming 10
bool
Boolean has two values, namely True and False, Note that the T in True ani
F in False are uppercase. We uso conditional and logical operators to work
on Boolean data. For example, 1 < 2 is True and 3 > 5 is Fals
Due to backwards compatibility, Python treats bool as a number such that
True equals 1 and False equals 0.
2.6.2 Sequence
This data types contains a collection of elements accessible by their indices
that is position but counted from 0.
str
A string is a collection or sequence of characters (letters, numbers or special
characters). In Python, a string can be enclosed in a single quote, double quotes
or triple quotes. Triple quotes are usually preferred for multiple sentences or
paragraphs
For example, the following are valid strings:
“Hello World’
"What a pleasant day!"
Let me sing a small
story, pay attention listen to me
Note that "334" is also a string even though it looks like an integer because
it is enclosed in double quotes.
list
It is an ordered collection of values belonging to the same or different dats
types. The list of items is separated by commas (,) and the entire list ®
enclosed in square brackets ((J)-
For example, (3, 6, 9, 12, 15], ("Hi", "Hello", "Vanakkam"), [1,
“Ananya”, 95.8) are lists
tuple
A tuple is an immutable list, that is, once a tuple is created, it cannot be
changed (you cannot add or delete items from the tuple). ‘The elements of &
tuple are also separated by commas but the tuple is enclosed within parenthess
(O)
For example, (4, 8, 12, 16, 20), ("A", "B", "C") are all tuples.101 Data Types
2.6.3 Set
A sot Is a collection of imordered values that is mutable (its values can be
changed after it is created), They are enclosed in curly brackets (2) and the
items aro separated by commas, The items of a set are not indexed and can
appear in any order. For example, ("blue" ,"black" ,"red" ,"orango"} is
anet.
2.6.4 Mapping
Python supports dict, that is, dictionnry for mapping. A dictionary consists
of key, value pains which is imtable, A key is separated front its value by a
colon (:) and the dictionary is enclosed in enrly brackets ({}).
Data types such as list, Luple, sets have only one value as an element but a
dictionary has a key and its value as a single element
For example, (1 "one", 2 "two", 3: hreo",
dictionary. 1 is the key and “one" is its value, A few more examples of
dictionary are {"CSK": "MS Dhoni", "MI": "Rohit Sharma", "RCB"
*Virat Kohli"} and = {"fruit" "apple", "vegetable": "potato",
"colour": "black"}.
“four"} isa
2.6.5 Null
Null denotes the absence of data, Python has None data type to indicate
noullness
2.7 Type Determination
Python is not a typed language. It means, if you assign an integer to a variable,
you can later assign a string to it. To get the type of a value we can use type
or isinstance function.
2.7.1 type(obj)
This function returns the class the value obj belongs to, Many often use this
funetion to check if a variable belongs to a type. But, type is not meant for
that It is useful in advanced usecases where you have the value but do not
know which class was used to create it
>>> x = 10
>>> cls = type(x)
>>> str(cls)
“cclass ‘ant '>">>> y = €18(20)
>>> y
20
>>> atr(type(y))
""
2.7.2 isinstance(obj, class_or_tuple)
This function returns whether the given obj belongs to the class or tuple gf
classes provided. To determine if a value belongs to a type, this function shoulg
be used.
>>> isinstance(10, int)
True
>>> isinstance(10, float)
False
>>> isinstance(“hello”, (int, float, str))
True
2.8 Mutability
A data type is said to be mutable if its value can be changed after it has beea
created. If it cannot be, then it is known as immutable.
Mutable _ Immutable
list Numbers —
dict str
set tuple
Note that None is a singleton. Only one instance of it exists hence there is uo
purpose in discussing its mutability.
2.9 Basic Input Output
Every program does some form of input and output during its execution. The
input can come from a variety of sources like GUI (mouse, keyboard events).
files, network, etc. Similarly, the output can be stored on files or shown iu GUI
(dialog windows).
The basic input and output is reading the data from user's keyboard ani
printing messages back. Python provides input and print functions for tho’
Purposes.Ww Dato
2.9.1 input (prompt)
To read input from user use input function. It takes an optional argument
prospt that is displayed while reading the input. After typing the input, the
user should press the Return (Enter) key. The typed input is returned in the
form of string.
>>> name = input( "Enter your name “)
John
>>> name
‘John’
.2 print (obj)
To display a message to user use print function. It has a lot of arguments and
nich operators as we will learn in later chapters. For now, assume that it takes
a value and prints it to the user. The value can be of any type and print will
automatically convert it to string for output
>>> print(10) -
10
>>> print( "Hello")
Hello
2.10 Integers
Numbers without any fractional part are known as integers, They ean be
positive or negative or zero. There are two ways to specify an integer in Python
The first is to use integer literals and then int constructor
2.10.1 Integer Literals
To create an integer, simply type the number itself, However, the number
should not have any spaces or commas. If you need to create a big number and
wish to separate its digits, use underscore (_) to separate the mmbers.
>>> 11234
11234
>>> 1000_124_567
1000124567
>>> -32Probl
-32
>>> a7
a7
By de
Prefix, Oo
hase 10. To create a number iy
radecimal tee
55> opi10 Tee
6
>>> -0p01
ot
>>> 00123
83
>>> -0035
-29
gil Floating Points
fractional part is knowns fontiog pointy
i be created using literals and float con eet Sst
at constructor
>>> Oxf
63
>>> -Oxabed
~43981
rn? cial (.), we get a
NE OF nepite of sere
>>> Oxabca
49981
However, care must be taken nt to volte che allowed digs. For ea
sing any other dit other than 2 oF 0 for a binary number results nan ett
Sox oot
File estden>*, Line 1
ob12
SyotaxError: invalid digit ’2’ in binary Literal |
2.10.2 int(x, base=10)
‘The other way to create an integer is to use int constructor. It takes the ake
X and its base. The base is useful only when x i a string. x can be
‘which the function returns the integral part. By default, the base is 10,
>>> int GO)
10
>>> int(3.14)
3
211.2 float (x)
‘To create a floating point number out of other data type lik string or integer,
we float constructor.