Variables in Python
Variables is a place placeholders used to contain a value, character number, etc. We use a name for our variable as a, b, number, etc. When we declare a variable, it will reserve a memory location we can use any name for our variable except reserve words.
Numeric type Variables
Integers (int
) and floats (float
) are numeric types in Python, these type of variables holds numbers. You can perform mathematical operations with them. The Python interpreter can then evaluate these expressions to produce numeric values.
You can use the type()
function to return the type of a value of a variable.
Examples:
Code
Integer assignment
counter = 100
print(counter)
Python100 |
Floating Point Numbers
Code
Assign Float Value
des_value = 10.12
print(des_value)
Python10.12 |
Print Value of Variables in Python
Code
var1 = "Hello, Python"
print(var1)
PythonHello, Python |
We can also assign other type of values as:
Code
var2 = 4
var3 = 36.9
print(var2, var3)
Python4 36.9 |
Note: Commas in the print function will show a space in the output.
We can also assign multiple values to multiple variables at the same time as:
Code
a, b, c = 1, 2, 'John'
PythonWe can also check the type of a variable by using the type keyword:
Code
a = 5
print(type(a))
Python<class 'int'> |
Strings in Python
The string is a combination of characters we can use string literals surrounded by single or double quotes such as ‘Hello Python’ OR “Hello Python”.
For displaying literals by using the print () function.
Code
Assign String Value
name = "John"
print(name)
PythonJohn |
Code
# Example: Print 'Hello Python'
print('Hello Python')
print("Hello Python") # Corrected the casing of 'Print'
# Assign String to a Variable
a = "Hello" # Corrected the indentation and casing of 'Print'
print(a)
PythonOutput: Hello Python Hello Python Hello |
Multiline Strings
We can also print a multiline string to a variable by using three quotes:
Code
a = """Python is an open-source programming language created by Dutch programmer Guido van Rossum, named after the British sketch comedy group Monty. Python is a high-level programming language, with applications in numerous areas, including web programming, scripting, data analysis and artificial intelligence."""
print(a)
PythonOutput: Python is an open-source programming language created by Dutch programmer Guido van Rossum, named after the British sketch comedy group Monty. Python is a high-level programming language, with applications in numerous areas, including web programming, scripting, data analysis and artificial intelligence. |
We can also store a string in an array and get the input by using the index value of a single character as:
Code
a = "Hello, Python!"
print(a[1])
PythonOutput: e |
Note: This will print the character at index 1
of the string a
, which is e
. Remember that Python uses 0-based indexing, so the first character is at index 0
.
String Slicing
As we know string is a combination of characters. If you have a huge document of about 10000 words and you just want to pick some lines to write from this document then Python provides this facility which is called “string slicing”.
Print the characters from index 3 to index 11:
Code
b = "Hello, Python!"
print(b[3:11])
PythonOutput: lo, Pyt |
We can also print a string by skipping one character:
Code
b = "Hello, Python!"
print(b[3:11:2])
PythonOutput: l,pt |
Python String Negative Indexing
Code
b = "Hello, Python!"
print(b[-5:-2])
PythonOutput: tho |
String Methods
Python provides some built-in methods to use on strings these methods are also called string methods.
Length Method
We can get the length of a string by using the len () function.
Code
b = "Hello Python!"
print(len(b))
PythonOutput: 13 |
Type Method
Example:
Python strip () method is used to remove whitespaces from the beginning and the end.
Code
The strip()
method removes leading and trailing white-space characters (spaces, tabs, newlines) from the string b
. Since there are no leading or trailing white-space characters in the string "Hello Python!"
, the output remains unchanged.
b = "Hello Python!"
print(b.strip())
PythonHello Python! |
Upper Method
Python’s upper () method converts the whole string into upper-case letters.
Code
b = "Hello Python!"
print(b.upper())
PythonOutput: HELLO PYTHON! |
Explanation: The upper()
method converts all characters in the string b
to uppercase, resulting in the output "HELLO PYTHON!"
.
Lower Method
Python lower () method converts the whole string into lowercase letters.
Code
b = "Hello Python!"
print(b.lower())
PythonOutput: hello python! |
Explanation: The lower()
method converts all characters in the string b
to lowercase, resulting in the output "hello python!"
.
Replace Method
Python replace () method replaces a string with another string.
Code
b = "Hello Python!"
print(b.replace("H", "J"))
PythonOutput: Jello Python! |
Explanation: The replace()
method replaces all occurrences of the sub-string "H"
with the sub-string "J"
in the string b
, resulting in the output "Jello Python!"
.
Split Method
Python split () method converts the whole string into upper case letters.
Code
b = "Hello Python!"
print(b.split(" "))
PythonOutput: [‘Hello’, ‘Python!’] |
In or Not in Method (check string)
You can use in or not-in built-in methods to check if a phrase is present in a string or not. The output will be True or False.
Code
b = "A quick brown fox jumps over the lazy dog."
x = "jumps" in b
print(x)
PythonOutput: True |
String Concatenation
Strings can be concatenated in Python by using the + operator.
Concatenate variable a with variable b.
Code
a = "Hello"
b = "Python"
c = a + b
print(c)
PythonOutput: HelloPython |
Explanation: The variables a
and b
store the strings “Hello” and “Python” respectively. The expression a + b
concatenates these strings together, resulting in the string “HelloPython”, which is then printed.
Python Booleans
Boolean represent output in the form of True or False.
Boolean Values
In some cases, we need to know whether the expression is True or False.
Code
print(1 > 2)
print(1 == 2)
print(1 < 2)
PythonOutput: False False True |
Explanation: Each print statement evaluates a comparison expression:
1 > 2
isFalse
because 1 is not greater than 2.1 == 2
isFalse
because 1 is not equal to 2.1 < 2
isTrue
because 1 is less than 2.
Print a message based on whether the condition is True or False:
Code
print(1 > 2)
print(1 == 2)
print(1 < 2)
PythonOutput: False False True |
Evaluate Values and Variables
We can evaluate any value by using the bool () function, it will return True or False.
print (bool("Hello"))
print (bool (15))
PythonOutput: True True |
Explanation: The bool()
function returns True
if the argument is non-empty for strings and non-zero for numeric values. In this case:
"Hello"
is a non-empty string, sobool("Hello")
evaluates toTrue
.15
is a non-zero integer, sobool(15)
evaluates toTrue
.
Type Casting in Python
We can use the type casting technique to convert our value from one type to another type e.g we can convert a string value into an integer as we explain below:
If we want to add string values then in the output both values will be concatenated except for calculating the sum.
Without using Type Casting
Code
Var1 = "54"
Var2 = "30"
print(Var1 + Var2)
PythonOutput: 5430 |
Explanation: The variables Var1
and Var2
store strings "54"
and "30"
respectively. When you use the +
operator with strings, it performs concatenation rather than arithmetic addition. So, Var1 + Var2
concatenates the strings "54"
and "30"
, resulting in "5430"
.
By using Type Casting
Code
Var1 = "54"
Var2 = "30"
print(int(Var1) + int(Var2))
PythonOutput: 84 |
Explanation: In this corrected code, int(Var1)
and int(Var2)
convert the string variables Var1
and Var2
into integers, resulting in the numbers 54 and 30 respectively. Then, these integers are added together using the +
operator, resulting in the sum 84, which is printed.
User Input
We can interact with our users by asking the user for input.
We can take input from a user by using the input () method.
Python 3.6 provides a user input method as input ()
Python 2.7 provides the user input method as raw_input ()
Code
print("Enter a number")
num = input()
print("You entered:", num)
PythonOutput: Enter a number 5 You entered: 5 |
Explanation: The corrected code prompts the user to enter a number with the message “Enter a number”. The input()
function then waits for user input, which is stored in the variable num
. Finally, it prints the message “You entered:” followed by the value stored in num
.
Note: The input method stores each value as a string so if you want to add values for calculating sum then first you have to convert values into integers by using the type casting technique.
Example:
Code
print("Enter a number")
num = input()
print("You entered:", int(num) + 10)
PythonInput: 10 Output: Enter a number You entered: 20 |
Author: TCF Editorial
Copyright The Cloudflare.