Python Syntax and Input Output

← Back to Home

Execute Python Syntax

In previous chapter, we learned that Python syntax can be executed by writing directly in command line: you can get more on this in Python Interactive mode.

>>> print("Hello, World!")
Hello, World!
Or by creating a python file, using the .py file extension, and running it in the Command Line:

C:\Users\Your Name>python myfile.py

Python Indentation

Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is part of the syntax and is very important.
Python uses indentation to indicate a block 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.


if 5 > 2:
  print("Five is greater than two!")
Python will give you an error if you skip the indentation:

if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least one. Example:

if 10 > 5:
    print("Indented!")
    print("Tab indentation")

print("No indentation")

Explanation:
  • The first two print statements are indented by 4 spaces, so they belong to the if block.
  • The third print statement is not indented, so it is outside the if block.

Python Variables

In Python, variables are created when you assign a value to it:

Example

Variables in Python:

x = 5
y = "Hello, World!"

Python has no command for declaring a variable. You will learn more about variables in the Python Variables chapter.

Comments

Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment: Example Comments in Python:

#This is a comment.
print("Hello, World!")

Input and Output in Python

Input and output operations are basic fundamentals in Python Programming. print(): function is used to display output. input(): function is used for input from users during program execution.

Taking User Input

Python 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!,", " Welcome!", name)

Output:
Enter your name: Geek4Code
Hello!, Welcome! Geek4Code
The code prompts the user to input their name, stores it in the variable "name" and then prints a greeting message to the user by the name he/she entered.

Output using print() in Python

Output in Python is printed directly by using print() function. It allows to display text, variables and expressions on our console. Below are examples of using print() function:
Printing Text
Printing text within double quotes("")

  print("Hello, World!")
  
Output:
Hello, World!

Printing Variables
We can use print() function to print single and multiple variables. We can print multiple variables by separating them with commas.

  	# Single variable
	s = "Allen"
	print(s)

	# Multiple Variables
	s = "John"
	age = 25
	city = "New York"
	print(s, age, city)
  
Output:
Allen
John 25 New York

Taking Multiple Inputs 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

Taking Conditional Input from user in Python
In this example, the program prompts the user to enter their age. The input is converted to an integer using the int() function. Then, the program uses conditional statements to check the age range and prints a message based on whether the user is a minor, an adult, or a senior citizen.

# Prompting the user for input
age_input = input("Enter your age: ")

# Converting the input to an integer
age = int(age_input)

# Checking conditions based on user input

if age < 0:
    print("Please enter a valid age.")
elif age < 18:
    print("You are a minor.")
elif age >= 18 and age < 65:
    print("You are an adult.")
else:
    print("You are a senior citizen.")


Output:
Enter your age: 25
You are an adult.

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?: 77

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.30
50.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 = ("Geek", "4", "Code")
e = ["Geek", "4", "Code"]
f = {"Geek": 1, "4":2, "Code":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.55
print("Amount: ${:.2f}".format(amount))
  
Output:
Amount: $150.55

Example 2: Using sep and end parameter

# end Parameter with '@'
print("Python", end='@')
print("Geek4Code")


# Seprating with Comma
print('G', '4', 'C', sep='')

# for formatting a date
print('09', '07', '2025', sep='-')

# another example
print('Neeraj', 'geek4code', sep='@')
  
Output:
Python@Geek4Code
G4C
09-07-2025
Neeraj@geek4code

Example 3: Using f-string

name = 'Rajesh'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")
  
Output:
Hello, My name is Rajesh 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: 50
The sum is 55


Some Global Applications Built using Python

  • YouTube
  • Instagram
  • Netflix
  • Google
  • Uber
  • Dropbox
  • Spotify
  • Pinterest

What can we do with Python?

Python is used for:
  • Web Development: Frameworks like Django, Flask.
  • Game Development: Libraries like Pygame.
  • Desktop Applications: GUI frameworks like Tkinter, PyQt.
  • Data Science and Analysis: Libraries like Pandas, NumPy, Matplotlib.
  • Machine Learning and AI: TensorFlow, PyTorch, Scikit-learn.
  • Automation and Scripting: Automate repetitive tasks.
  • Scientific Computing: SciPy, SymPy.
  • Web Scraping: Tools like BeautifulSoup, Scrapy.
  • Internet of Things (IoT): MicroPython, Raspberry Pi.
  • DevOps and Cloud: Automation scripts and APIs.
  • Cybersecurity: Penetration testing and ethical hacking tools.