INTRODUCTION TO PYTHON PROGRAMMING
IDLE is an integrated development environment (an application like a word processor which
helps developers to write programs) for Python. IDLE is the Python IDE which comes with
Python, built with the tkinter GUI toolkit. It has two modes Interactive and Development.
IDLE features:
Cross Platform : Works on Unix and Windows.
Multi-window text editor with syntax highlighting and smart indent and other.
Python shell window with syntax highlighting.
Integrated debugger.
Coded in Python, using the tkinter GUI toolkit
Python IDLE: Interactive Mode
Let us assume that we've already installed Python (here we installed Python 3.2 on a standard pc
with windows 7 OS). Click on start button and find Python 3.2 tab in installed programs.
To start IDLE click on IDLE (Python GUI) icon, you will see a new window opens up and the
cursor is waiting beside '>>>' sign which is called command prompt.
This mode is called interactive mode as you can interact with IDLE directly, you type something
(single unit in a programming language) and press enter key Python will execute it, but you can
not execute your entire program here. At the command prompt type copyright and press enter
key Python executes the copyright information.
Now Python is ready to read new command. Let's execute the following commands one by one.
Command -1 : print("Hello World")
Command -2 : primt("Hello World")
Python command line interface
There are some users who prefer command line intersection, rather than a GUI interface. To go
Python command line, click on Python 3.2 tab then click on Python(command line).
Here is the screen shot of Python command line interface. To return type exit() or Ctrl+Z plus
Enter key.
PYTHON BASICS:
Covers Python syntax, print statements, variables, data types, and operators, along with control
flow structures like if-else, loops, and the use of break and continue.
Python Syntax
Python is designed to be a highly readable language with a straightforward syntax. The syntax
defines the rules for writing a Python program. A Python parser reads the program and translates
it into executable code.
Python Line Structure:
A Python program consists of logical lines. Every logical line is terminated by a NEWLINE
token. A logical line may span one or more physical lines.
Comments in Python:
A comment starts with the # symbol and continues until the end of the line.
Comments are ignored by the Python interpreter and are not part of the program's output.
Python does not have multi-line comment syntax like some other languages. If multiple lines are
required for comments, each line should start with #.
Joining two lines:
To write a long statement across multiple physical lines, use the backslash (\) at the end of the
first line. This allows you to break the code logically without causing syntax errors.
Example:
Python Reserve words:
The following are Python's reserved words. These cannot be used as variable names or identifiers
in your program:
DATA TYPES
Data types: The data stored in memory can be of many types. For example, a student roll number
is stored as a numeric value and his or her address is stored as alphanumeric characters. Python
has various standard data types that are used to define the operations possible on them and the
storage method for each of them.
1. Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value. A numeric value
can be an integer, a floating number, or even a complex number. These values are defined
as Python int, Python float and Python complex classes in Python.
Integers - This value is represented by int class. It contains positive or negative whole numbers
(without fractions or decimals of unlimited length). In Python, there is no limit to how long an
integer value can be.
>>> print (20)
20
>>> x=10
>>> print x
>>> print (int(x))
10
Float - This value is represented by the float class. It is a real number with a floating-point
representation (positive or negative). It is specified by a decimal point. Optionally, the character
e or E followed by a positive or negative integer may be appended to specify scientific notation.
Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8
Complex Numbers - A complex number is represented by a complex class. It is specified
as (real part) + (imaginary part)j . For example - 2+3j
2. Sequence Data Types in Python
The sequence Data Type in Python is the ordered collection of similar or different Python data
types. Sequences allow storing of multiple values in an organized and efficient fashion. There are
several sequence data types of Python:
Python String
Python List
Python Tuple
String Data Type
Python Strings are arrays of bytes representing Unicode characters. In Python, there is no
character data type Python, a character is a string of length one. It is represented by str class.
Strings in Python can be created using single quotes, double quotes or even triple quotes. We can
access individual characters of a String using index.
s = 'Welcome to the Geeks World'
print(s)
List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data. It is
very flexible as the items in a list do not need to be of the same type.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square brackets[].
# Empty list
a = []
# list with int values
a = [1, 2, 3]
print(a)
# list with mixed int and string
b = ["Geeks", "For", "Geeks", 4, 5]
print(b)
Access List Items
In order to access the list items refer to the index number. In Python, negative sequence indexes
represent positions from the end of the array. Instead of having to compute the offset as in
List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the
end, -1 refers to the last item, -2 refers to the second-last item, etc.
a = ["Geeks", "For", "Geeks"]
print("Accessing element from the list")
print(a[0])
print(a[2])
print("Accessing element using negative indexing")
print(a[-1])
print(a[-3])
Boolean:
Python Data type with one of the two built-in values, True or False. Boolean objects that are
equal to True are truthy (true), and those equal to False are falsy (false).
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
>>> type(False)
print() function
The print() function is a fundamental part of Python that allows for easy console output
output formatting refers to the way data is presented when printed or logged. Proper formatting
makes information more understandable and actionable. Python provides several ways to format
strings effectively, ranging from old-style formatting to the newer f-string approach.
The simplest way to use the print() function is by passing a string or variable as an argument:
print("Good Morning")
print("Good", <Variable Containing the String>)
print("Good" + <Variable Containing the String>)
print("Good %s" % <variable containing the string>)
Syntax and Parameters
The general syntax for print() is:
print(<el_1>, ..., sep=' ', end='\n', file=[Link], flush=False)
Parameters:
sep: Specifies the separator between values. Default is a single space.
end: Specifies the string to be appended at the end of the output. Default is a newline.
file: Defines the output destination. Default is [Link]. Use [Link] for errors.
flush: If True, forcibly flushes the output buffer.
Examples with sep and end:
print("Python", "is", "fun", sep="-") # Output: Python-is-fun
print("Hello", end=", ")
print("world!") # Output: Hello, world!
1. Advanced String Formatting
Python provides multiple ways to format strings in print().
Using F-Strings (Python 3.6+):
F-strings provide an efficient way to embed expressions within string literals.
name = "Tom"
age = 25
print(f"Hello, {name}. You are {age} years old.")
Output:
Hello, Tom. You are 25 years old.
2. Using .format()
The .format() method is versatile and allows you to format strings with placeholders.
name = "Tom"
age = 25
print("Hello, {}. You are {} years old.".format(name, age))
Output:
Hello, Tom. You are 25 years old.
3. Using % Operator
The % operator is an older method that remains useful for specific formatting needs.
name = "Tom"
age = 25
print("Hello, %s. You are %d years old." % (name, age))
Output:
Hello, Tom. You are 25 years old.
Working with Quotes in Strings
Single Quotes: For simple strings: print('Hello')
Double Quotes: Useful for strings with single quotes inside: print("Python's simplicity")
Triple Quotes: Allow multi-line strings and embedded quotes
print("""Python is versatile.
It's also popular!""")
Variable Use:
Strings can be assigned to variable say string1 and string2 which can called when using the print
statement.
Example-1:
str1 = 'Wel'
print(str1,'come')
Output:
Wel come
Example-2:
str1 = 'Welcome'
str2 = 'Python'
print(str1, str2)
Output:
Welcome Python
String Concatenation:
String concatenation is the "addition" of two strings. Observe that while concatenating there will
be no space between the strings.
Example:
str1 = 'Python'
str2 = ':'
print('Welcome' + str1 + str2)
Output:
WelcomePython:
Using as String:
%s is used to refer to a variable which contains a string.
Example:
str1 = 'Python'
print("Welcome %s" % str1)
Output:
Welcome Python
Using other data types:
Similarly, when using other data types
%d -> Integer
%e -> exponential
%f -> Float
%o -> Octal
%x -> Hexadecimal
This can be used for conversions inside the print statement itself.
Using as Integer:
Example:
print("Actual Number = %d" %15)
Output:
Actual Number = 15
Using as Exponential:
Example:
print("Exponential equivalent of the number = %e" %15)
Output:
Exponential equivalent of the number = 1.500000e+01
Using as Float:
Example:
print("Float of the number = %f" %15)
Output:
Float of the number = 15.000000
Using as Octal:
Example:
print("Octal equivalent of the number = %o" %15)
Output:
Octal equivalent of the number = 17
Using as Hexadecimal:
Example:
print("Hexadecimal equivalent of the number = %x" %15)
Output:
Hexadecimal equivalent of the number = f
Using multiple variables:
When referring to multiple variables parenthesis is used.
Example:
str1 = 'World'
str2 = ':'
print("Python %s %s" %(str1,str2))
Output:
Python World :
Repeating Characters
Use multiplication with strings to repeat characters:
print('#' * 10) # Output: ##########
Other Examples of Print Statement:
The following are other different ways the print statement can be put to use.
Example - % is used for %d type
% is used for %d type word
print("Welcome to %%Python %s" %'language')
Output:
Welcome to %Python language
Example - Line Break
\n is used for Line Break.
print("Sunday\nMonday\nTuesday\nWednesday\nThursday\nFriday\nSaturday")
Output:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Example - multiple times
Any word print multiple times.
print('-w3r'*5)
Output:
-w3r-w3r-w3r-w3r-w3r
Example - using tab
\t is used for tab.
print("""
Language:
\t1 Python
\t2 Java\n\t3 JavaScript
""")
Output:
Language:
1 Python
2 Java
3 JavaScript
Precision width and field width:
Field width is the width of the entire number and precision is the width towards the right. One
can alter these widths based on the requirements.
The default Precision Width is set to 6.
Example - decimal points
Notice upto 6 decimal points are returned. To specify the number of decimal points, '%
(fieldwidth).(precisionwidth)f' is used.
print("%f" % 5.1234567890)
Output:
5.123457
Example - decimal points
Notice upto 5 decimal points are returned
print("%.5f" % 5.1234567890)
Output:
5.12346
Example - field width is set more than the necessary
f the field width is set more than the necessary than the data right aligns itself to adjust to the
specified values.
print("%9.5f" % 5.1234567890)
Output:
5.12346
Example - Zero padding
Zero padding is done by adding a 0 at the start of fieldwidth.
print("%015.5f" % 5.1234567890)
Output:
000000005.12346
Example - proper alignment
For proper alignment, a space can be left blank in the field width so that when a negative number
is used, proper alignment is maintained.
print("% 9f" % 5.1234567890)
print("% 9f" % -5.1234567890)
Output:
5.123457
-5.123457
Example - adding a + sign
'+' sign can be returned at the beginning of a positive number by adding a + sign at the beginning
of the field width.
print("%+9f" % 5.1234567890)
print("% 9f" % -5.1234567890)
Output:
+5.123457
-5.123457
Example - specifying a negative symbol
As mentioned above, the data right aligns itself when the field width mentioned is larger than the
actually field width. But left alignment can be done by specifying a negative symbol in the field
width.
print("%-9.4f" % 5.1234567890)
Output:
5.1235
Pretty Printing with pprint
For structured data, such as dictionaries, use the pprint module to print data in a readable format.
from pprint import pprint
data = {"Python": 3, "Java": 8, "C++": 11}
pprint(data)
Output:
{'C++': 11, 'Java': 8, 'Python': 3}