Skip to content
Understanding Python Print Function & Data Types
#pythonBeginner

Understanding Python Print Function & Data Types

Apr 23, 2026
Updated May 13, 2026
120 min read

AI Insights

Powered by GPT-4o-mini

Verified Context: python-basics-print-syntax-your-first-program

Discover Python basics through simple examples using the print function. Learn how case sensitivity affects output and explore straightforward syntax.

Quick Summary

Solve these questions own your own and try to test yourself what you have learned in the session.

1 - Python Output

Demonstrating case sensitivity in Python string literals and print function usage

Explanation

  • Python treats uppercase and lowercase letters as distinct characters, meaning 'Hello' and 'hello' are considered different identifiers
  • The print() function outputs the string literal 'Hello World' to the console, displaying it as plain text
  • String literals in Python must be enclosed in quotes (single or double) to be recognized as text data
  • The code illustrates fundamental Python syntax where function names and string content maintain their exact casing requirements
python
1# Python is a case-sensitive language2print('Hello World')

Output

text
1Hello World

Python print statement outputs text to console

Explanation

  • The code uses Python's built-in print() function to display text data
  • It outputs the string 'Madhu Dadi' to the standard output stream (console)
  • The print function automatically adds a newline character at the end of output
  • This is a fundamental way to display information or debug program state in Python
  • The statement executes immediately when the script runs, showing the literal text content
python
1print('Madhu Dadi')

Output

text
1Madhu Dadi

Python print statement displaying a name variable

Explanation

  • The code attempts to print a variable named Madhu Dadi using the print() function
  • This will result in a NameError because Madhu Dadi is not defined as a variable or string literal
  • The variable name should either be quoted as a string "Madhu Dadi" or properly defined before printing
  • In Python, unquoted text in print statements is treated as a variable reference, not a string
  • To fix this, the code should be written as print("Madhu Dadi") or define Madhu Dadi as a variable first
python
1print(Madhu Dadi)

Output

text
1  Cell In[3], line 12    print(Madhu Dadi)3          ^4SyntaxError: invalid syntax. Perhaps you forgot a comma?

Displaying the integer value seven using Python's print function

Explanation

  • The code executes the print() function which outputs the integer literal 7 to the console
  • This is a basic output statement that demonstrates fundamental printing functionality in Python
  • The number 7 is passed as an argument to the print function without any additional formatting
  • When executed, this code will display the digit 7 on the screen followed by a newline character
  • This represents one of the simplest ways to produce visible output in a Python program
python
1print(7)

Output

text
17

Displaying floating-point number output in Python console

Explanation

  • The code snippet uses the print() function to output the floating-point number 7.7 to the console
  • Python automatically formats and displays the numeric value with its decimal point intact
  • This demonstrates basic output functionality for numeric data types in Python programming
  • The statement executes immediately when run, showing the literal value 7.7 as the program's result
  • No additional processing or formatting is applied to the number before display
python
1print(7.7)

Output

text
17.7

This code snippet outputs a boolean value to the console.

Explanation

  • The print() function is used to display the specified message or value to the console.
  • In this case, the value True, which is a boolean literal in Python, is passed to the print() function.
  • The output will be the string representation of the boolean value, which is True.
  • This code demonstrates the basic functionality of printing values in Python.
python
1print(True)

Output

text
1True

This code snippet demonstrates how to print multiple data types in Python.

Explanation

  • The print() function is used to output data to the console.
  • It can accept multiple arguments, which are separated by commas.
  • Each argument can be of different data types, such as strings, integers, floats, and booleans.
  • The output will display all the provided arguments in a single line, separated by spaces.
python
1print('Hello', 1, 4.5, True)

Output

text
1Hello 1 4.5 True

This code prints multiple values with a custom separator in Python.

Explanation

  • The print function is used to output data to the console.
  • It takes multiple arguments: a string, an integer, a float, and a boolean.
  • The sep parameter specifies the string to be inserted between the values, which is set to a comma (,).
  • As a result, the output will be: Hello,1,4.5,True.
  • This allows for formatted output of different data types in a single line.
python
1print('Hello', 1, 4.5, True, sep=',')

Output

text
1Hello,1,4.5,True

This code prints multiple values separated by a custom delimiter.

Explanation

  • The print function is used to output data to the console.
  • It takes multiple arguments: a string, an integer, a float, and a boolean.
  • The sep parameter specifies the string that separates the printed values, which is set to '/'.
  • As a result, the output will display Hello/1/4.5/True.
python
1print('Hello', 1, 4.5, True, sep='/')

Output

text
1Hello/1/4.5/True

This code snippet outputs two strings to the console sequentially.

Explanation

  • The print function is used to display text output in Python.
  • The first print statement outputs the string 'Madhu' to the console.
  • The second print statement follows and outputs the string 'Dadi'.
  • Each string is printed on a new line by default.
python
1print('Madhu')2print('Dadi')

Output

text
1Madhu2Dadi

This code demonstrates how to customize the end character of a print statement in Python.

Explanation

  • The first print function outputs the string 'Hello' followed by a custom end character, which is a hyphen (-), instead of the default newline.
  • The end parameter in the print function allows for modification of what is printed at the end of the output.
  • The second print function outputs the string 'Madhu' on the same line immediately after 'Hello-', resulting in 'Hello-Madhu'.
  • This technique is useful for formatting output in a more controlled manner, allowing for inline text display.
python
1print('Hello', end='-')2print('Madhu')

Output

text
1Hello-Madhu

This code snippet demonstrates how to customize the end character of a print statement in Python.

Explanation

  • The first print function outputs the string 'Hello' followed by a custom end character, which is ' | ' instead of the default newline.
  • The end parameter in the print function allows for modification of what is printed at the end of the output.
  • The second print function outputs 'Madhu' on the same line, immediately following the custom end character from the first print.
  • As a result, the final output appears as "Hello | Madhu" on a single line.
python
1print('Hello', end=' | ')2print('Madhu')

Output

text
1Hello | Madhu

2 - Data Types

This code snippet demonstrates how to print an integer value in Python.

Explanation

  • The print() function is used to output data to the console.
  • The argument 8 is an integer that will be displayed when the code is executed.
  • This simple operation showcases the basic functionality of printing values in Python.
python
1# Integer2print(8)

Output

text
18

Demonstrating the behavior of large floating-point numbers in Python

Explanation

  • The code prints the value of 1 multiplied by 10 raised to the power of 308, which is a very large floating-point number.
  • The first print statement outputs 1e308, which is the scientific notation for 1 followed by 308 zeros.
  • The second print statement attempts to output 1e309, which exceeds the maximum limit for floating-point numbers in Python, resulting in an overflow.
  • Due to this overflow, Python returns inf, indicating that the value is infinite.
  • This behavior illustrates Python's handling of floating-point arithmetic and the limitations of numerical representation.
python
1# 1*10^3082print(1e308)3print(1e309)

Output

text
11e+3082inf

This code snippet demonstrates how to print a floating-point number in Python.

Explanation

  • The print() function is used to output data to the console.
  • The argument 8.55 is a floating-point number, which represents a decimal value.
  • When executed, the code will display 8.55 as the output in the terminal or console.
  • This showcases Python's ability to handle and display decimal numbers directly.
python
1# Float2print(8.55)

Output

text
18.55

Understanding the behavior of floating-point numbers in Python with large exponent values

Explanation

  • The first print statement outputs 1.7e308, which is a valid floating-point number in Python representing 1.7 multiplied by 10 raised to the power of 308.
  • The second print statement attempts to output 1.7e309, which exceeds the maximum limit for floating-point numbers in Python, resulting in an overflow.
  • Due to this overflow, Python returns inf (infinity) for the second print statement, indicating that the value is too large to be represented.
  • This behavior highlights the limitations of floating-point representation and the concept of infinity in numerical computations.
python
1print(1.7e308)2print(1.7e309)

Output

text
11.7e+3082inf

This code snippet demonstrates the basic usage of Boolean values in Python.

Explanation

  • The code uses the built-in print() function to output values to the console.
  • It prints the Boolean value True, which represents a truthy condition.
  • It then prints the Boolean value False, representing a falsy condition.
  • This snippet illustrates how Boolean values can be directly displayed in Python.
python
1# Boolean2print(True)3print(False)

Output

text
1True2False

Displaying a greeting message using Python's print function with string literals

Explanation

  • The code uses Python's built-in print() function to output text to the console
  • The text 'Hello World' is enclosed in single quotes, making it a string literal
  • This is the traditional first program many programmers write when learning a new language
  • The print function automatically adds a newline character at the end of the output
  • String literals in Python can use either single or double quotes for definition
python
1# Text/String2print('Hello World')

Output

text
1Hello World

Displaying a complex number in Python using the print function

Explanation

  • The code utilizes the print function to output a complex number.
  • The complex number is represented as 5 + 6j, where 5 is the real part and 6j is the imaginary part.
  • In Python, complex numbers are defined using the j suffix for the imaginary component.
  • This snippet demonstrates how Python handles and displays complex numbers directly in the console.
python
1# complex2print(5 + 6j)

Output

text
1(5+6j)

This code snippet demonstrates how to print a list of integers in Python.

Explanation

  • The code uses the print() function to output data to the console.
  • It creates a list containing the integers 1 through 5.
  • Lists in Python are similar to arrays in C, allowing for ordered collections of items.
  • The output will display the entire list as a single line in the console.
python
1# List (in C -> Array)2print([1,2,3,4,5])

Output

text
1[1, 2, 3, 4, 5]

This code snippet demonstrates how to create and print a tuple in Python.

Explanation

  • The code uses the print() function to output the contents of a tuple.
  • A tuple is defined by enclosing a sequence of values in parentheses, in this case, the numbers 1 through 5.
  • Tuples are immutable, meaning their contents cannot be changed after creation.
  • This snippet showcases the basic syntax for creating and displaying a tuple in Python.
python
1# Tuple2print((1,2,3,4,5))

Output

text
1(1, 2, 3, 4, 5)

Displaying a set of unique integers in Python.

Explanation

  • The code uses the print() function to output a set.
  • A set is defined using curly braces {} and contains unique elements.
  • In this case, the set includes the integers 1, 2, 3, 4, and 5.
  • Sets automatically remove any duplicate values, ensuring all elements are distinct.
  • The output will be a representation of the set, showcasing its unordered nature.
python
1# Sets2print({1,2,3,4,5})

Output

text
1{1, 2, 3, 4, 5}

This code snippet demonstrates how to create and print a dictionary in Python.

Explanation

  • The code defines a dictionary with three key-value pairs: 'name', 'gender', and 'age'.
  • The keys are strings representing attributes of a person, while the values are the corresponding data.
  • The print function outputs the entire dictionary to the console in a readable format.
python
1# Dictionary2print({'name': 'Madhu', 'gender': 'Male', 'age': 30})

Output

text
1{'name': 'Madhu', 'gender': 'Male', 'age': 30}

Determine the data type of a given value in Python using the type function

Explanation

  • The type() function is a built-in Python function that returns the type of an object.
  • In this snippet, type(3) is called to check the type of the integer 3.
  • The output will be <class 'int'>, indicating that 3 is of type integer.
  • This function is useful for debugging and understanding the data types of variables in your code.
python
1# type2type(3)

Output

text
1int

Determine the data type of a floating-point number in Python

Explanation

  • The type() function is used to identify the type of a given object in Python.
  • In this case, the argument 3.5 is a floating-point number.
  • When executed, type(3.5) will return <class 'float'>, indicating that the input is of type float.
  • This function is useful for debugging and understanding data types in Python programming.
python
1type(3.5)

Output

text
1float

Determine the data type of a given string in Python

Explanation

  • The type() function is a built-in Python function that returns the type of an object.
  • In this snippet, the argument passed to type() is the string 'Hello'.
  • The output will indicate that the type of the object is <class 'str'>, confirming it is a string.
  • This function is useful for debugging and understanding the data types of variables in Python.
python
1type('Hello')

Output

text
1str

Determine the data type of a complex number in Python

Explanation

  • The code uses the type() function to identify the data type of the expression 6 + 6j.
  • 6 + 6j is a complex number in Python, where 6 is the real part and 6j is the imaginary part.
  • The output of the code will be <class 'complex'>, indicating that the result is of the complex type.
  • This is useful for understanding how Python handles different numerical types, especially in mathematical computations.
python
1type(6+6j)

Output

text
1complex

Determining the data type of a list object in Python

Explanation

  • The code uses Python's built-in type() function to identify the class or type of the provided argument
  • The argument [1,2,3,4,5] is a list containing five integer elements
  • The type() function returns the type object representing the list class
  • This operation is commonly used for debugging, validation, or understanding data structures in Python programs
  • The output will be "<class 'list'>" indicating that the object is indeed a list data type
python
1type([1,2,3,4,5])

Output

text
1list

3 - Variables

Static vs Dynamic Typing

Static vs Dynamic Binding

Stylish declaration techniques

Assigning a string value to a variable in Python programming

Explanation

  • This code declares a variable named 'name' and assigns it the string value 'Madhu'
  • The variable can be used later in the program to reference the stored name value
  • In Python, strings are immutable objects that can contain letters, numbers, and special characters
  • The assignment creates a reference to the string object in memory that can be accessed throughout the program
  • This is a basic variable declaration pattern commonly used for storing user data or identifiers
python
1name = 'Madhu'

Displaying variable content using Python's print function

Explanation

  • The code outputs the value stored in the variable named "name" to the console
  • It uses Python's built-in print() function to display the variable's contents
  • The variable name must be defined earlier in the code for this to execute successfully
  • This is a fundamental operation for debugging and showing program output to users
  • The print statement will display whatever string, number, or object is assigned to the name variable
python
1print(name)

Output

text
1Madhu

Python script demonstrating basic arithmetic addition and output printing

Explanation

  • Two integer variables 'a' and 'b' are initialized with values 5 and 6 respectively
  • The code performs simple addition operation by adding the two variables together
  • The result of the addition (11) is displayed using the print function
  • This demonstrates fundamental variable assignment and arithmetic operations in Python programming
  • The output shows the sum of two predefined integers on the console
python
1a = 52b = 63 4print(a + b)

Output

text
111

Understanding Dynamic Typing in Python Compared to Static Typing in Other Languages

Explanation

  • The code illustrates Python's dynamic typing feature, where the variable a is assigned an integer value without explicitly declaring its type.
  • Unlike languages such as C, Java, or C++, Python does not require type declarations, simplifying variable assignments.
  • The comment highlights the contrast with static typing, where the data type must be specified at the time of variable declaration.
  • This flexibility allows for easier and faster coding but may lead to runtime errors if types are not managed properly.
python
1# Dynamic Typing - No need to tell the datatype. Python interpreter will take based on the value2a = 53# Static Typing - Not supported in Python unlike in C, Jave, C++4# int a = 5

Demonstrating dynamic typing and variable reassignment in Python

Explanation

  • The variable a is initially assigned an integer value of 5.
  • The first print(a) outputs the integer value 5 to the console.
  • The variable a is then reassigned to a string value 'Madhu'.
  • The second print(a) outputs the string 'Madhu', showcasing Python's dynamic typing feature.
  • This code illustrates how a variable can change its type during runtime without any explicit type declaration.
python
1# Dynamic Binding2a = 53print(a)4a = 'Madhu'5print(a)

Output

text
152Madhu

Understanding Static Binding Limitations in Python Programming

Explanation

  • The code snippet illustrates the concept of static binding, which is not supported in Python.
  • It attempts to declare a variable a as an integer with the value 5, but later reassigns it to a string 'Madhu'.
  • This behavior highlights Python's dynamic typing, allowing variables to change types at runtime.
  • The commented lines indicate that static type declarations, like in languages such as Java or C++, are not applicable in Python.
  • The snippet serves as a reminder of Python's flexibility and the absence of strict type enforcement.
python
1# Static Binding - Doesn't support in Python2# int a = 53# a = 'Madhu'

Demonstrating variable assignment and printing in Python using different techniques

Explanation

  • The first part of the code initializes three variables a, b, and c with values 1, 2, and 3 respectively and prints them in a single line.
  • The second part showcases a more compact way to assign values to multiple variables in one line using tuple unpacking.
  • Both print statements output the values of a, b, and c, demonstrating that both assignment methods yield the same result.
  • This snippet illustrates Python's flexibility in variable declaration and assignment styles.
python
1# Stylish declaration techniques2a = 13b = 24c = 35print(a,b,c)6 7a,b,c = 1,2,38print(a,b,c)

Output

text
11 2 321 2 3

This code snippet demonstrates variable assignment and printing multiple variables in Python.

Explanation

  • The variables a, b, and c are all assigned the same value of 5 in a single line using chained assignment.
  • The print function outputs the values of a, b, and c to the console, separated by spaces.
  • This approach allows for efficient assignment of the same value to multiple variables simultaneously.
  • The output of the print statement will be 5 5 5, showing that all three variables hold the same value.
python
1a=b=c = 52print(a,b,c)

Output

text
15 5 5

Comments

This Python code snippet demonstrates basic variable assignment and arithmetic operations.

Explanation

  • The code initializes two variables, a and b, with integer values 4 and 6, respectively.
  • It includes comments that provide context for each line, which are ignored during execution.
  • The print function outputs the sum of a and b, which is 10, to the console.
  • The use of comments enhances code readability and helps explain the purpose of each line.
python
1# This is a comment2# Second line3a = 4 # another comment4b = 65print(a+b)

Output

text
110

4 - Keywords & Identifiers

Keywords

Understanding Python Identifiers and Their Naming Rules

Explanation

  • Identifiers in Python are names used for variables, functions, and classes, and they must follow specific naming conventions.
  • Identifiers cannot start with a digit; for example, 1name is invalid, while name1 is valid.
  • Special characters are limited to the underscore _, making names like first_name valid, but names like first-name are not allowed.
  • Identifiers cannot be Python keywords; for instance, using class as an identifier is not permitted.
  • The code demonstrates valid identifier usage by defining and printing variables with different naming conventions.
python
1# Identifiers - Variable, function, class is an identifier2# You cannot start with a digit3# 1name = 'Madhu'4name1 = 'Madhu'5print(name1)6# You can use special chars -> _ only7# first-name = 'Madhu'8first_name = 'Madhu'9print(first_name)10_ = 'Madhu'11print(_)12# Identifiers can not be Keyword13# class = 'ABC'

Output

text
1Madhu2Madhu3Madhu

5 - User Input

This code snippet captures user input from the console in Python.

Explanation

  • The input() function prompts the user to enter data via the console.
  • It waits for the user to type something and press Enter before proceeding.
  • The input is returned as a string, which can be stored in a variable for further processing.
  • If no prompt message is provided, it defaults to an empty prompt.
python
1input()

Output

text
1'Madhu'

This code prompts the user to enter their name via standard input.

Explanation

  • The input() function is used to take input from the user in a console or terminal.
  • The string 'Type your name:' is displayed as a prompt to guide the user on what to enter.
  • The function waits for the user to type their name and press Enter before proceeding.
  • The entered name is not stored or processed further in this snippet.
python
1input('Type your name:')

Output

text
1'Madhu'

This code captures user input and concatenates two numbers as strings.

Explanation

  • The code prompts the user to input two numbers, storing them in the variables fnum and snum.
  • It prints both inputs and their data types, which will be <class 'str'> since input() returns strings.
  • The two string variables are concatenated using the + operator, resulting in a combined string rather than a numerical sum.
  • Finally, it prints the concatenated result, which may not be the expected arithmetic addition of the two numbers.
python
1# Take input from users and store them in a variable2fnum = input('Enter first number:')3snum = input('Enter second number:')4print(fnum,snum)5print(type(fnum),type(snum))6# Add the 2 variables7result = fnum + snum8# Print the result9print(result)

Output

text
13 52<class 'str'> <class 'str'>335

6 - Type Conversion

Understanding Implicit Type Conversion in Python Arithmetic Operations

Explanation

  • The code demonstrates how Python performs implicit type conversion when adding an integer and a float.
  • The expression 5 + 5.6 results in a float, showcasing Python's ability to handle mixed types seamlessly.
  • The print(type(5), type(5.6)) statement outputs the types of the operands, confirming that one is an integer and the other is a float.
  • This behavior allows for more flexible arithmetic operations without requiring explicit type casting by the programmer.
python
1# Implicit vs Explicit2 3# Implicit - Python knows and do the conversion if compatible4print(5+5.6)5print(type(5),type(5.6))

Output

text
110.62<class 'int'> <class 'float'>

This code attempts to add an integer and a string, resulting in a TypeError.

Explanation

  • The code uses the print function to output the result of an addition operation.
  • It tries to add the integer 4 and the string '4', which are of different data types.
  • In Python, adding an integer to a string directly is not allowed, leading to a TypeError.
  • This snippet highlights the importance of type compatibility in arithmetic operations.
  • To fix the error, one could convert the integer to a string or the string to an integer before performing the addition.
python
1print(4 + '4')

Output

text
1---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)Cell In[56], line 12----> 1 print(4 + '4')3TypeError: unsupported operand type(s) for +: 'int' and 'str'

Converting a string representation of a number to an integer in Python

Explanation

  • The code uses the built-in int() function to convert a string '4' into its integer equivalent 4.
  • This conversion is explicit, meaning the programmer clearly indicates the intention to change the data type from string to integer.
  • If the string contains non-numeric characters, a ValueError will be raised during the conversion process.
  • This technique is commonly used when processing user input or data read from files that are in string format.
python
1# Explicit2# str -> int3int('4')

Output

text
14

This code snippet demonstrates how to convert a floating-point number to an integer in Python.

Explanation

  • The int() function is used to convert a value to an integer type.
  • In this case, the floating-point number 4.5 is passed as an argument.
  • The conversion truncates the decimal part, resulting in the integer 4.
  • This operation does not round the number; it simply removes the fractional component.
  • The output of this code will be the integer 4.
python
1int(4.5)

Output

text
14

Converting a complex number to an integer in Python results in a TypeError.

Explanation

  • The code attempts to convert a complex number 4+5j into an integer using the int() function.
  • In Python, complex numbers cannot be directly converted to integers, as they contain both real and imaginary parts.
  • Executing this code will raise a TypeError, indicating that the conversion is not valid.
  • To handle complex numbers, one must extract the real part (using .real) or the imaginary part (using .imag) before conversion.
python
1int(4+5j)

Output

text
1---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)Cell In[61], line 12----> 1 int(4+5j)3TypeError: int() argument must be a string, a bytes-like object or a real number, not 'complex'

Converting an integer to a string in Python

Explanation

  • The str() function is used to convert the provided argument into its string representation.
  • In this case, the integer 5 is passed to the str() function.
  • The output will be the string '5', allowing for string operations to be performed on it.
  • This conversion is useful when concatenating numbers with strings or when formatting output.
python
1str(5)

Output

text
1'5'

Converting a string representation of a number to a float in Python

Explanation

  • The float() function is used to convert a string or a number into a floating-point number.
  • In this case, the string '4' is passed to the float() function.
  • The output of this operation will be the floating-point number 4.0.
  • This conversion is useful for performing arithmetic operations that require decimal precision.
  • If the string cannot be converted to a float, a ValueError will be raised.
python
1float('4')

Output

text
14.0

This code snippet captures user input and performs addition on two numbers.

Explanation

  • The code prompts the user to enter two numbers, storing them as strings in the variables fnum and snum.
  • It prints the values of both input variables along with their data types, which will be <class 'str'> since inputs are taken as strings.
  • The inputs are then converted to integers using int() and added together, with the result stored in the variable result.
  • Finally, the code prints the sum of the two numbers.
python
1# Take input from users and store them in a variable2fnum = input('Enter first number:')3snum = input('Enter second number:')4print(fnum,snum)5print(type(fnum),type(snum))6# Add the 2 variables7result = int(fnum) + int(snum)8# Print the result9print(result)

Output

text
15 62<class 'str'> <class 'str'>311

7 - Literals

Demonstrating various numeric literals in Python including binary, decimal, octal, hexadecimal, float, and complex numbers

Explanation

  • The code initializes variables using different numeric literals: binary (0b), decimal, octal (0o), and hexadecimal (0x).
  • It also demonstrates the use of float literals, including standard decimal notation and scientific notation (e.g., 1.5e2 for 150).
  • A complex number is created using the imaginary unit j, showcasing Python's support for complex number types.
  • The print statements output the values of all initialized variables, including the real and imaginary parts of the complex number.
python
1a = 0b1010 # Binary Literals2b = 100 # Decimal Literal3c = 0o310 # Octal Literal4d = 0x12c # Hexadecimal Literal5 6# Float Literal7float_1 = 10.58float_2 = 1.5e29float_3 = 1.5e-310 11# Complex Literal12x = 3.14j13 14print(a, b, c, d)15print(float_1, float_2, float_3)16print(x, x.real, x.imag)

Output

text
110 100 200 300210.5 150.0 0.001533.14j 0.0 3.14

Demonstrating various string types and printing in Python

Explanation

  • The code initializes different types of strings, including single-line, multi-line, Unicode, and raw strings.
  • string and strings are standard strings, while multiline_str showcases a multi-line string using triple quotes.
  • The char variable holds a single character string.
  • The unicode variable is defined but commented out, representing Unicode characters using their code points.
  • The raw_string variable demonstrates a raw string, which ignores escape sequences, and all initialized strings are printed to the console.
python
1string = 'This is Python'2strings = "This is Python"3char = "C"4multiline_str = """This is a multiline string with more than one line code."""5unicode = u"\U0001f600\U0001F606\U0001F923"6raw_string = r"raw \n string"7 8print(string)9print(strings)10print(char)11print(multiline_str)12#print(unicode)13print(raw_string)

Output

text
1This is Python2This is Python3C4This is a multiline string with more than one line code.5raw \n string

Understanding Boolean Arithmetic in Python with Integer Addition

Explanation

  • The code demonstrates how Python treats Boolean values as integers, where True is equivalent to 1 and False is equivalent to 0.
  • The variable a is calculated by adding True (1) to 4, resulting in a being 5.
  • The variable b is calculated by adding False (0) to 10, resulting in b being 10.
  • The print statements output the values of a and b, showing the results of the arithmetic operations.
  • This snippet highlights the implicit type conversion that occurs when performing arithmetic with Boolean values in Python.
python
1a = True + 42b = False + 103 4print('a:', a)5print('b:', b)

Output

text
1a: 52b: 10

Python code demonstrating None type assignment and type checking

Explanation

  • Variable 'a' is assigned the special Python value None, which represents the absence of a value or a null value
  • The first print statement outputs 'None' to the console, displaying the string representation of the None value
  • The second print statement shows '<class 'NoneType'>' indicating that None is an instance of the NoneType class
  • This demonstrates how None serves as Python's equivalent to null or nil in other programming languages
  • The code illustrates fundamental concepts of variable assignment and type introspection in Python
python
1a = None2print(a)3print(type(a))

Output

text
1None2<class 'NoneType'>

Variable assignment and print statement execution in Python

Explanation

  • The variable k is declared without initialization, which will result in a NameError when the code tries to execute
  • Variables a and b are assigned integer values 2 and 3 respectively, demonstrating basic variable assignment syntax
  • The print function outputs the string 'Something' to the console, showing simple text output functionality
  • This code illustrates fundamental Python operations including variable declaration, assignment, and output statements
  • The unassigned variable k creates a runtime error that prevents the subsequent code from executing properly
python
1k2a = 23b = 34print('Something')

Output

text
1---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)Cell In[72], line 12----> 1 k 3      2 a = 24      3 b = 35NameError: name 'k' is not defined

Python variable initialization and print statement execution

Explanation

  • Variable k is initialized to None, representing the absence of a value or a null state
  • Variables a and b are assigned integer values 2 and 3 respectively, demonstrating basic variable assignment
  • The print function outputs the string 'Something' to the console, showing simple text display functionality
  • This code illustrates fundamental Python operations including variable declaration, assignment, and output formatting
python
1k = None2a = 23b = 34print('Something')

Output

text
1Something

Task : Session 1

Solve these questions own your own and try to test yourself what you have learned in the session.

Happy Learning!

Q1 :- Print the given strings as per stated format.

Given strings:

text
1"Data" "Science" "Learning" "Program"2"By" "Madhu"

Output

:

text
1Data-Science-Learning-Program-started-By-Madhu

Concept- [Seperator and End]

Python print function with custom separator and end parameters for string formatting

Explanation

  • The code uses the print() function with multiple arguments to output text with custom formatting
  • The sep='-' parameter replaces the default space separator between arguments with hyphens
  • The end='-started-' parameter adds a hyphen-separated suffix after the first print statement instead of a newline
  • The second print statement continues on the same line from where the first left off due to the custom end parameter
  • Both print statements together demonstrate how to control output formatting and line continuation in Python
python
1# Write your code here2 3print("Data","Science","Learning","Program", sep='-',end='-started-')4print("By","Madhu", sep='-')

Output

text
1Data-Science-Learning-Program-started-By-Madhu

Q2:- Write a program that will convert celsius value to fahrenheit.

Convert Celsius temperature to Fahrenheit using user input in Python

Explanation

  • The code prompts the user to input a temperature in Celsius and converts it to a float for accurate calculations.
  • It applies the formula for conversion from Celsius to Fahrenheit: F = C * (9/5) + 32.
  • The converted Fahrenheit temperature is then printed in a formatted string that includes both the original Celsius value and the calculated Fahrenheit value.
python
1# Write your code here2 3celcius = float(input("Enter a temperature in celcius:"))4 5faren = celcius * (9/5) + 326 7print('Celcius {} to Fahrenheit is {}'.format(celcius,faren))

Output

text
1Celcius 36.9 to Fahrenheit is98.42

Q3:- Take 2 numbers as input from the user.Write a program to swap the numbers without using any special python syntax.

This code snippet demonstrates how to swap two variables in Python without using tuple unpacking.

Explanation

  • The variables a and b are initialized with the values 3 and 5, respectively.
  • A temporary variable temp is used to hold the value of a during the swap process.
  • The value of b is then assigned to a, effectively replacing a's original value.
  • Finally, the value stored in temp (original a) is assigned to b, completing the swap.
  • The swapped values of a and b are printed, resulting in the output "5 3".
python
1# Write your code here2a = 33b = 54 5#a,b = b,a6#print(a,b)7 8temp = a9a = b10b = temp11 12print(a,b)

Output

text
15 3

Q4:- Write a program to find the euclidean distance between two coordinates.Take both the coordinates from the user as input.

Calculate the Euclidean distance between two points in a 2D space using Python

Explanation

  • Prompts the user to input the x and y coordinates for two points in a 2D plane.
  • Computes the distance between the two points using the Euclidean distance formula: √((x2 - x1)² + (y2 - y1)²).
  • Utilizes the int() function to convert user input from strings to integers for accurate calculations.
  • Outputs the calculated distance to the console.
python
1# Write your code here2 3p1x = int(input("Enter first point x coordinate:"))4p2x = int(input("Enter second point x coordinate:"))5p1y = int(input("Enter first point y coordinate:"))6p2y = int(input("Enter second point y coordinate:"))7 8distance = ((p2x - p1x)**2 + (p2y - p1y)**2)**0.59 10print(distance)

Output

text
13.605551275463989

Q5:- Write a program to find the simple interest when the value of principle,rate of interest and time period is provided by the user.

Calculate simple interest based on user input for principal, time, and rate.

Explanation

  • Prompts the user to input the principal amount, time period, and interest rate.
  • Converts the input values into appropriate data types: integer for principal and time, and float for the rate.
  • Computes the simple interest using the formula: (principal * time * rate) / 100.
  • Outputs the calculated interest to the user in a formatted message.
python
1# Write your code here2 3p = int(input("Enter amount"))4t = int(input("Enter time period"))5r = float(input("Enter rate"))6 7interest = (p*t*r)/1008 9print('The interest is', interest)

Output

text
1The interest is 10000.0

Q6:- Write a program that will tell the number of dogs and chicken are there when the user will provide the value of total heads and legs.

For example: Input: heads -> 4 legs -> 12 Output: dogs -> 2 chicken -> 2

Calculate the number of dogs and chickens based on heads and legs input

Explanation

  • The code prompts the user to input the total number of heads and legs, which represent the combined count of dogs and chickens.
  • It calculates the number of dogs using the formula: (total legs - 2 * total heads) / 2, accounting for the fact that each dog has 4 legs and each chicken has 2 legs.
  • The number of chickens is derived by subtracting the number of dogs from the total number of heads.
  • Finally, it prints the calculated number of dogs and chickens to the console.
python
1# Write your code here2 3heads = int(input("Enter number of heads:"))4legs = int(input("Enter number of legs:"))5 6dogs = (legs-(2*heads))/27chicken = heads - dogs8 9print('dogs:', dogs)10print('chicken:', chicken)

Output

text
1dogs: 0.02chicken: 4.0

Q7:- Write a program to find the sum of squares of first n natural numbers where n will be provided by the user.

Calculate the sum of squares of the first n natural numbers using Python

Explanation

  • The code prompts the user to input a number, which is converted to an integer and stored in the variable n.
  • It calculates the sum of squares of the first n natural numbers using the formula ( \frac{n(n+1)(2n+1)}{6} ).
  • The result of the calculation is stored in the variable result.
  • Finally, the code prints the computed sum of squares to the console.
python
1# Write your code here2 3n = int(input("Enter a number:"))4 5result = (n*(n+1)*(2*n+1))/66print(result)

Output

text
155.0

Q8:- Given the first 2 terms of an Arithmetic Series.Find the Nth term of the series. Assume all inputs are provided by the user.

Calculate the nth term of an arithmetic sequence using user input

Explanation

  • The code prompts the user to input the first term, second term, and the desired term position (n) of an arithmetic sequence.
  • It calculates the common difference (d) by subtracting the first term from the second term.
  • The nth term (an) is computed using the formula for the nth term of an arithmetic sequence: an = first_term + (n-1) * d.
  • Finally, the calculated nth term is printed to the console.
python
1# Write your code here2first_term = int(input("Enter first term:"))3second_term = int(input("Enter second term:"))4n = int(input("Enter the value of n"))5 6d = second_term - first_term7 8an = first_term + (n-1)*d9 10print(an)

Output

text
115

Q9:- Given 2 fractions, find the sum of those 2 fractions.Take the numerator and denominator values of the fractions from the user.

This code snippet performs the addition of two fractions and outputs the result in fractional form.

Explanation

  • The code prompts the user to input the numerators and denominators of two fractions.
  • It calculates the resultant numerator by cross-multiplying and adding the two fractions: rn = n1*d2 + n2*d1.
  • The resultant denominator is computed by multiplying the two denominators: rd = d1*d2.
  • Finally, it prints the resulting fraction in the format numerator/denominator.
python
1# Write your code here2n1 = int(input("Enter a num1:"))3d1 = int(input("Enter a den1:"))4n2 = int(input("Enter a num2:"))5d2 = int(input("Enter a den2:"))6 7rn = n1*d2 + n2*d18rd = d1*d29 10print('{}/{}'.format(rn, rd))

Output

text
122/15

Q10:- Given the height, width and breadth of a milk tank, you have to find out how many glasses of milk can be obtained? Assume all the inputs are provided by the user.

Input: Dimensions of the milk tank H = 20cm, L = 20cm, B = 20cm Dimensions of the glass h = 3cm, r = 1cm

Calculate the number of glasses that can fit in a tank based on dimensions and glass size

Explanation

  • The code prompts the user to input the height, breadth, and length of a tank, as well as the height and radius of a glass.
  • It calculates the volume of the tank using the formula: volume = height * breadth * length.
  • The volume of the glass is computed using the formula for the volume of a cylinder: volume = π * radius² * height.
  • The program then determines how many glasses can fit in the tank by dividing the tank's volume by the glass's volume and using math.floor() to round down to the nearest whole number.
  • Finally, it prints the total number of glasses that can be filled with the tank's volume.
python
1# Write your code here2import math3 4h_t = float(input("Enter a height:"))5b_t = float(input("Enter a breadth:"))6l_t = float(input("Enter a length:"))7 8h_g = float(input("Enter glass height:"))9r_g = float(input("Enter glass radius:"))10 11vol_tank = h_t*b_t*l_t12vol_glass = 3.14*r_g*r_g*h_g13 14print('no of glasses', math.floor(vol_tank/vol_glass))

Output

text
1no of glasses 6

Convert Jupyter Notebook to PDF using LaTeX command customization

Explanation

  • The command utilizes jupyter nbconvert to convert a Jupyter Notebook file into a PDF format.
  • The --to pdf flag specifies that the output format should be PDF.
  • The --PDFExporter.latex_command option allows customization of the LaTeX command used for the conversion process.
  • The command provided in the brackets specifies the use of pdflatex along with the filename of the notebook to generate the PDF.
  • This command is executed in a terminal or command line interface, not within a Python script.
python
1#jupyter nbconvert --to pdf --PDFExporter.latex_command="['pdflatex', '{filename}']" "1 - Python Basics.ipynb"

Next in this series: Python Operators & Control Flow: A Complete Beginner's Guide →

Frequently Asked Questions

Python treats uppercase and lowercase letters as distinct characters, meaning 'Hello' and 'hello' are considered different identifiers.
If you try to print a variable that is not defined, it will result in a NameError because the variable is not recognized as a defined entity or string literal.
The Python print function automatically adds a newline character at the end of its output.
String literals in Python must be enclosed in quotes, either single or double, to be recognized as text data.
Executing the code 'print7' will display the digit 7 on the screen followed by a newline character.

How was this tutorial?