Sei sulla pagina 1di 15

1

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM


2

What is Python?
 Welcome to Python!
Python is a high-level programming language, with applications in numerous
areas, including web programming, scripting, scientific computing, and artificial
intelligence.

It is very popular and used by organizations such as Google, NASA, the CIA and
Disney.

Python is processed at runtime by the interpreter. There is no need to compile


your program before executing it.
Interpreter: A program that runs scripts written in an interpreted language such as Python.

The three major version of Python are 1.x, 2.x and 3.x. These are subdivided
into minor versions, such as 2.7 and 3.3.

Backwards compatible changes are only made between major versions; code
written in Python 3.x is guaranteed to work in all future versions. Both Python
Versions 2.x and 3.x are used currently.

Python has several different implementations, written in various languages.


The version CPython is used further.

Python source files have an extension of .py

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM


3

The Python Console


 First Program:
On IDLE (Python GUI)

>>> print("Hello Universe")


Hello Universe

 The Python Console


Python console is a program that allows you to enter one line of python code,
repeatedly executes that line, and displays the output. This is known as REPL –
a read-eval-print loop.
To close a console, type in “quit()” or “exit()”, and press enter.

>>> quit()

Ctrl-Z : sends an exit signal to the console program.


Ctrl-C : stops a running program, and is useful if you’ve accidentally created a
program that loops forever.

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM


4

Simple Operations
1. Simple Operations can be done on console directly.

>>> 2 + 2
4
>>> 5 + 4 – 3
6

* : Multiplication / : Division
2. Use of parentheses for determining which operations are performed
first.
>>> 2 * (3 + 4)
14

3. Minus indicates negative number


>>> (-7 + 2) * (-4)
20

4. Dividing by zero in Python produces an error, as no answer can be


calculated.

>>> 11/0
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
11/0
ZeroDivisionError: integer division or modulo by zero

In Python, the last line of an error message indicates the error’s type. In
further examples only last line of error is written.

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM


5

Floats
Floats are used in Python to represent numbers that aren’t integers. Extra
zeros at the number’s end are ignored.
A float can be added to an integer, because Python silently converts the
integer to float. This conversion is the exception rather the rule in Python –
usually you have to convert values manually if you want to operate on them.

Other Numerical Operations


 Exponentiation
The raising of one number to the power of another. This operation is
performed using two asterisks.

>>> 2**5
32
>>> 9** (1/2)
3.0

 Quotient & Remainder


Floor division is done using two forward slashes. ( // )
The modulo operator is carried out with a percent symbol. ( % )

>>> 20 // 6
3
>>> 1.25 % 0.5
0.25

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM


6

Strings
A String is created by entering text between two single or double quotation
marks.
Some characters can’t be included in string, they must be escaped by placing
backslash before them.
Manually writing “\n” can be avoided with writing the whole string between
three sets of quotes.

>>> """System: Please Enter Input


User: Enters Input
System: Gives Output."""

'System: Please Enter Input\nUser: Enters


Input\nSystem: Gives Output.'

Simple Input & Output


In Python, we can use print function can be used to process output.

>>> print(1 + 1)
2

To get input from user, we can use input function. Which prompts user for i/p.
Returns what user enters as a string (with contents automatically escaped).

>>> input("Enter here:")


Enter here:222
222

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM


7

String Operations
Strings in python can be added using Concatenation using “+” operator.

>>> “Hello ” + ‘Python’ (works with both types of


quotes)
Hello Python
>>> “2” + “2”
22
>>> "2" + 3
TypeError: cannot concatenate 'str' and 'int' objects

Strings also can be multiplied.

>>> "Sumit" * 3
'SumitSumitSumit'
>>> 4 * '2'
'2222'

Strings can’t be multiplied by other strings.


Strings also can’t be multiplied by floats, even if the floats are whole numbers.

>>> '27' * '54'


TypeError: can't multiply sequence by non-int of type 'str'

>>>"PythonIsFun" * 7.0
TypeError: can't multiply sequence by non-int of type 'float'

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM


8

Type Conversion
You can’t add two strings containing numbers together to produce the integer
result. The solution is type conversion.

>>> int("2")+int("3")
5

>>> float(input("Enter a number:"))+float(


input("Enter Another Number:"))
Enter a number : 42
Enter Another Number : 55
97.0

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM


9

Variables
A variable allows you to store a value by assigning it to a name, which can be
used to refer to the value later in the program.
To assign a variable, “=” is used.

>>> x=9
>>> print(2*x)
18

Variables can be used to perform operations as we did with numbers and


strings as they store value throughout the program.
In Python, variables can be assigned multiple times with different data types as
per need.

>>> x=123
>>> print(x)
123
>>> x='String'
>>> print(x+'!')
String!

For Variable names only characters that are allowed are letters, numbers and
underscores. Numbers are not allowed at the start. Spaces are not allowed in
variable name.
Invalid variable name generates error.
>>> 2ndNo = 22
SyntaxError: invalid syntax

Python is case sensitive programming language. Thus, Number and number


are two different variable names in Python.

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM


10

Trying to reference a variable you haven’t assigned, causes error.


You can use the del statement to remove a variable, which means the
reference from the name to the value is deleted & trying to use the variable
causes an error.
Deleted variables can be reassigned to later as normal.

>>> foo = 'string'


>>> foo
'string'
>>> bar
NameError: name 'bar' is not defined
>>> del foo
>>> foo
NameError: name 'foo' is not defined

You can also take the value of the variable from user input.

>>> foo=input("Enter a number: ")


Enter a number: 24
>>> print foo
24

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM


11

In-Place Operators
In-place operators allow you to write code like ’x = x + 3’ more concisely,
as ‘x +=3’. The same thing is possible with other operators such as - , * , / and
% as well.

>>> x=25
>>> x+=30
>>> print(x)
55

These operators can be used on types other than number such as


strings.

>>> x = "Learn"
>>> print(x)
Learn
>>> x+= "Python"
>>> print(x)
LearnPython

Many languages have special operators such as ‘++’ as a shortcut for ‘x+=1’.
Python does not have these.

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM


12

Dissecting Programs
 Comments
Single Line Comments
#This Single Line Comment
Multi-line Comments

'''
This is another type of comment
This is multi-line comment.
'''

 The print() Function


Displays the string value inside the parentheses written in the program on the
screen.

print(‘Hello World!’)

You can also use this function to put a blank line on the screen; just call
print() with nothing in between the parentheses.

 The input() Function


Waits for the user to type some text on the keyboard and press ENTER.

myName = input()

This function call evaluates to a string equal to the user’s text, and the previous
line of code assigns the myName variable to this string value.
You can think of the input() function call as an expression that evaluates to
whatever string the user typed in.

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM


13

 The len() Function


You can pass the len() function a string value (or a variable containing a string),
and the function evaluates to the integer value of the number of characters in
that string.
Example:

>>> len('hello')
5

 The str(), int() and float() Functions


If you want to concatenate an integer such as 21 with a string to pass to
print(), you’ll need to get the value '21', which is the string form of 21. The str()
function can be passed an integer value and will evaluate to a string value
version of it, as follows:

>>> str(21)
'21'
>>> print('I am ' + str(21) + ' years old.')
I am 21 years old

The str(), int(), and float() functions will evaluate to the string, integer, and
floating-point forms of the value you pass, respectively.

>>> str(0)
'0'
>>> str(-3.14)
'-3.14'

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM


14

>>> int('42')
42
>>> int('-99')
-99
>>> int(1.25)
1
>>> int(1.99)
1

>>> float('3.14')
3.14
>>> float(10)
10.0

TEXT AND NUMBER EQUIVALENCE


Although the string value of a number is considered a completely different
value from the integer or floating-point version, an integer can be equal to
a floating point .
>>> 42 == '42'
False
>>> 42 == 42.0
True
>>> 42.0 == 0042.000
True
Python makes this distinction because strings are text, while integers and
floats are both numbers .

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM


15

You were reading:


1. Basic Concepts In Python
 What is Python?
 The Python Console
 Simple Operations
 Floats
 Other Numerical Operations
 Strings
 Simple Input & Output
 String Operations
 Type conversions
 Variables
 In-Place Operators
 Dissecting Programs
2. Control Structures In Python
3. Functions & Modules In Python
4. Exceptions & Files In Python
5. More Types In Python
6. Functional Programming with Python
7. Object-Oriented Programming with Python
8. Regular Expressions In Python
9. Pythonicness & Packaging

BASIC CONCEPTS IN PYTHON SUMIT S. SATAM

Potrebbero piacerti anche