Python Introduction
Python was created by Guido van Rossum in 1991 and further developed
by the Python Software Foundation. It was designed with focus on code
readability and its syntax allows us to express concepts in fewer lines of
code.
Key Features of Python
Python’s simple and readable syntax makes it beginner-friendly.
Python runs seamlessly on Windows, macOS and Linux.
Includes libraries for tasks like web development, data analysis and
machine learning.
Variable types are determined automatically at runtime, simplifying code
writing.
Supports multiple programming paradigms, including object-oriented,
functional and procedural programming.
Python is free to use, distribute and modify.
Understanding Hello World Program in Python
Hello, World! in python is the first python program which we learn when we
start learning any program. It’s a simple program that displays the message
“Hello, World!” on the screen.
Hello World Program
Here’s the “Hello World” program:
# This is a comment. It will not be executed.
print("Hello, World!")
Output
Hello, World!
How does this work:
print() is a built-in Python function that tells the computer to show
something on the screen.
The message "Hello, World!" is a string, which means it's just text. In
Python, strings are always written inside quotes (either single ' or double
").
Anything after # in a line is a comment. Python ignores comments when
running the code, but they help people understand what the code is
doing.
Comments are helpful for explaining code, making notes or skipping
lines while testing.
We can also write multi-line comments using triple quotes:
"""
This is a multi-line comment.
It can be used to describe larger sections of code.
"""
.
Indentation in Python
In Python, Indentation is used to define blocks of code. It tells the Python
interpreter that a group of statements belongs to a specific block. All
statements with the same level of indentation are considered part of the
same block. Indentation is achieved using whitespace (spaces or tabs) at
the beginning of each line. The most common convention is to use 4
spaces or a tab, per level of indentation.
Example:
print("I have no indentation")
print("I have tab indentaion")
Output:
Hangup (SIGHUP)
File "/home/guest/sandbox/[Link]", line 3
print("I have tab indentaion")
IndentationError: unexpected indent
Explanation:
first print statement has no indentation, so it is correctly executed.
second print statement has tab indentation, but it doesn't belong to a
new block of code. Python expects the indentation level to be consistent
within the same block. This inconsistency causes an IndentationError.
.
Famous Application Built using Python
YouTube: World’s largest video-sharing platform uses Python for
features like video streaming and backend services.
Instagram: This popular social media app relies on Python’s simplicity
for scaling and handling millions of users.
Spotify: Python is used for backend services and machine learning to
personalize music recommendations.
Dropbox: The file hosting service uses Python for both its desktop client
and server-side operations.
Netflix: Python powers key components of Netflix’s recommendation
engine and content delivery systems (CDN).
Google: Python is one of the key languages used in Google for web
crawling, testing and data analysis.
Uber: Python helps Uber handle dynamic pricing and route optimization
using machine learning.
Pinterest: Python is used to process and store huge amounts of image
data efficiently.
What can we do with Python?
Python is used for:
Web Development: Frameworks like Django, Flask.
Data Science and Analysis: Libraries like Pandas, NumPy, Matplotlib.
Machine Learning and AI: TensorFlow, PyTorch, Scikit-learn.
Automation and Scripting: Automate repetitive tasks.
Game Development: Libraries like Pygame.
Web Scraping: Tools like BeautifulSoup, Scrapy.
Desktop Applications: GUI frameworks like Tkinter, PyQt.
Scientific Computing: SciPy, SymPy.
Internet of Things (IoT): MicroPython, Raspberry Pi.
DevOps and Cloud: Automation scripts and APIs.
Cybersecurity: Penetration testing and ethical hacking tools.
The Programming Cycle for
Python With Example
The programming cycle, also known as the software development
life cycle (SDLC), refers to the various stages involved in creating,
testing, and maintaining software applications.
While there are different models for the SDLC, a commonly used
one is the waterfall model, which consists of the following phases:
requirements gathering, design, implementation, testing,
deployment, and maintenance.
Let’s go through each phase using Python as an example:
1. Requirements Gathering: In this phase, you gather and
analyze the requirements for your Python application. This
involves understanding the problem you’re trying to solve,
identifying user needs, and documenting the software
specifications.
Example: Let’s say you’re building a simple calculator
program. Your requirements might include basic arithmetic
operations such as addition, subtraction, multiplication, and
division.
2. Design: In the design phase, you create a high-level design for
your Python program based on the requirements. This includes
designing the architecture, data structures, algorithms, and user
interface (if applicable).
Example: For the calculator program, you might design a
user interface with input fields for two numbers and buttons
for different operations. You would also outline the structure
of your code, such as defining functions for each arithmetic
operation.
3. Implementation: In this phase, you start coding your Python
program based on the design. You write the actual source code,
following best practices, coding standards, and using appropriate
libraries or frameworks.
Example: You would write Python code to handle user input,
perform the desired arithmetic operation based on the user’s
choice, and display the result.
4. Testing: In the testing phase, you verify that your Python
program functions correctly and meets the specified
requirements. This involves writing test cases, executing them,
and fixing any issues that arise.
Example: You would write test cases to cover different
scenarios, such as testing addition, subtraction,
multiplication, and division with various inputs. You would
then run the tests and fix any bugs or errors discovered
during testing.
5. Deployment: Once you have thoroughly tested your Python
program, you are ready to deploy it to a production environment
or distribute it to users. This may involve packaging your
program, creating an installer, or making it available for
download.
Example: You might create an executable file or a Python
package that users can install on their systems to use the
calculator program.
6. Maintenance: After deployment, your Python program may
require updates, bug fixes, or enhancements based on user
feedback or changing requirements. Maintenance involves
making these changes, and ensuring the program remains
functional and up-to-date.
Example: You might release updates to the calculator
program to add new features like square root calculation or
to fix any reported issues.
Input and Output in Python
Understanding input and output operations is fundamental to Python
programming. With the print() function, we can display output in various
formats, while the input() function enables interaction with users by
gathering input during program execution.
Taking input in Python
Python's input() function is used to take user input. By default, it returns
the user input in form of a string.
Example:
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
Output
Enter your name: Navya
Hello, Navya ! Welcome!
The code prompts the user to input their name, stores it in the variable
"name" and then prints a greeting message addressing the user by their
entered name.
Printing Output using print() in Python
At its core, printing output in Python is straightforward, thanks to the print()
function. This function allows us to display text, variables and expressions
on the console. Let's begin with the basic usage of the print() function:
In this example, "Hello, World!" is a string literal enclosed within double
quotes. When executed, this statement will output the text to the console.
print("Hello, World!")
Output
Hello, World!
Printing Variables
We can use the print() function to print single and multiple variables. We
can print multiple variables by separating them with commas. Example:
# Single variable
s = "Bob"
print(s)
# Multiple Variables
s = "Alice"
age = 25
city = "New York"
print(s, age, city)
Output
Bob
Alice 25 New York
Take Multiple Input in Python
We are taking multiple input from the user in a single line, splitting the
values entered by the user into separate variables for each value using
the split() method. Then, it prints the values with corresponding labels,
either two or three, based on the number of inputs provided by the user.
# taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
# taking three inputs at a time
x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)
Output
Enter two values: 5 10
Number of boys: 5
Number of girls: 10
Enter three values: 5 10 15
Total number of students: 5
Number of boys is : 10
Number of girls is : 15
How to Change the Type of Input in Python
By default input() function helps in taking user input as string. If any user
wants to take input as int or float, we just need to typecast it.
Print Names in Python
The code prompts the user to input a string (the color of a rose), assigns it
to the variable color and then prints the inputted color.
# Taking input as string
color = input("What color is rose?: ")
print(color)
Output
What color is rose?: Red
Red
Print Numbers in Python
The code prompts the user to input an integer representing the number of
roses, converts the input to an integer using typecasting and then prints the
integer value.
# Taking input as int
# Typecasting to int
n = int(input("How many roses?: "))
print(n)
Output
How many roses?: 88
Print Float/Decimal Number in Python
The code prompts the user to input the price of each rose as a floating-
point number, converts the input to a float using typecasting and then prints
the price.
# Taking input as float
# Typecasting to float
price = float(input("Price of each rose?: "))
print(price)
Output
Price of each rose?: 50.3050.3
Find DataType of Input in Python
In the given example, we are printing the type of variable x. We will
determine the type of an object in Python.
a = "Hello World"
b = 10
c = 11.22
d = ("Geeks", "for", "Geeks")
e = ["Geeks", "for", "Geeks"]
f = {"Geeks": 1, "for":2, "Geeks":3}
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
Output
<class 'str'>
<class 'int'>
<class 'float'>
<class 'tuple'>
<class 'list'>
<class 'dict'>
Output Formatting
Output formatting in Python with various techniques including the format()
method, manipulation of the sep and end parameters, f-strings and the
versatile % operator. These methods enable precise control over how data
is displayed, enhancing the readability and effectiveness of your Python
programs.
Example 1: Using Format()
amount = 150.75
print("Amount: ${:.2f}".format(amount))
Output
Amount: $150.75
Example 2: Using sep and end parameter
# end Parameter with '@'
print("Python", end='@')
print("GeeksforGeeks")
# Seprating with Comma
print('G', 'F', 'G', sep='')
# for formatting a date
print('09', '12', '2016', sep='-')
# another example
print('pratik', 'geeksforgeeks', sep='@')
Output
Python@GeeksforGeeks
GFG
09-12-2016
pratik@geeksforgeeks
Example 3: Using f-string
name = 'navya'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")
Hello, My name is navya and I'm 23 years old.
Output
Hello, My name is Tushar and I'm 23 years old.
Example 4: Using % Operator
We can use '%' operator. % values are replaced with zero or more value
of elements. The formatting using % is similar to that of ‘printf’ in the C
programming language.
%d –integer
%f – float
%s – string
%x –hexadecimal
%o – octal
# Taking input from the user
num = int(input("Enter a value: "))
add = num + 5
# Output
print("The sum is %d" %add)
Output
Enter a value: 50The sum is 55
Taking Conditional User Input in Python
In Python, taking conditional user input means getting input from the user
and making decisions based on that input. You usually use the input()
function to get the value and then use if-else statements to check
conditions.
input() is used to take user input as a string.
You can use int() or float() to convert it if needed.
Use if, elif, and else to apply conditions to the input.
Python - Print Output using print() function
Python print() function prints the message to the screen or any other
standard output device. In this article, we will cover about print() function in
Python as well as it's various operations.
# print() function example
print("GeeksforGeeks")
a = [1, 2, 'gfg']
print(a)
print() Function Syntax
Syntax : print(value(s), sep= ' ', end = '\n', file=file, flush=flush)
Parameters:
value(s): Any value, and as many as you like. Will be converted to a
string before printed
sep='separator' : (Optional) Specify how to separate the objects, if
there is more than [Link] :' '
end='end': (Optional) Specify what to print at the [Link] : '\n'
file : (Optional) An object with a write method. Default :[Link]
flush : (Optional) A Boolean, specifying if the output is flushed (True) or
buffered (False). Default: False
Return Type: It returns output to the screen.
Though it is not necessary to pass arguments in print() function, it requires
an empty parenthesis at the end that tells Python to execute the function
rather than calling it by name. Now, let's explore the optional arguments
that can be used with the print() function.
In this example, we have 2 variables integer and string. We are printing all
variables with print() function.
name = "John"
age = 30
print("Name:", name)
print("Age:", age)
Output
Name: John
Age: 30
How print() works in Python?
You can pass variables, strings, numbers, or other data types as one or
more parameters when using the print() function. Then, these parameters
are represented as strings by their respective str() functions. To create a
single output string, the transformed strings are concatenated with spaces
between them.
If you want to master Python from start to finish, check out [Link]'s
Complete Python course here, we highly recommend it if you enjoy
hands-on learning. The course stands out for its structured approach,
interactive coding challenges, and focus on essential programming
concepts. The best part is that you don't require any prior programming
experience to complete the course.
In this code, we are passing two parameters name and age to the print
function.
name = "Alice"
age = 25
print("Hello, my name is", name, "and I am", age, "years old.")
Output
Hello, my name is Alice and I am 25 years old.
Python String Literals
String literals in Python's print statement are primarily used to format or
design how a specific string appears when printed using the print() function.
\n: This string literal is used to add a new blank line while printing a
statement.
"": An empty quote ("") is used to print an empty line.
This code uses \n to print the data to the new line.
print("GeeksforGeeks \n is best for DSA Content.")
Output
GeeksforGeeks
is best for DSA Content.
Print Concatenated Strings with +
In this example, we are concatenating strings inside print() function.
print('GeeksforGeeks is a Wonderful ' + 'Website.')
"end" parameter in print()
The end keyword is used to specify the content that is to be printed at the
end of the execution of the print() function. By default, it is set to "\n", which
leads to the change of line after the execution of print() statement.
# without end parameter
print ("GeeksForGeeks is the best platform to learn Python")
# print() function ends with "**" as set in end parameter.
print ("GeeksForGeeks is the best platform to Learn Python", end= "**")
print("Welcome to GFG")
"sep" parameter in print()
The print() function can accept any number of positional arguments. To
separate these positional arguments, the keyword argument "sep" is used.
This code is showing that how can we use sep argument for multiple
variables.
a = 12
b = 12
c = 2022
print(a, b, c, sep="-")
Output
12-12-2022
Note: As sep, end, flush, and file are keyword arguments their position
does not change the result of the code.
print() Function with file parameter
This code is writing the data in the print() function to the text file.
print('Welcome to GeeksforGeeks Python world.!!', file=open('[Link]',
'w'))
Output
Python