Sunday, June 7, 2020

Assigning values to Variables in Python

As you can see from the above example, you can use the assignment operator = to assign a value to a variable.

Example 1: Declaring and assigning value to a variable

website = "apple.com"
print(website)
Output
apple.com
In the above program, we assigned a value apple.com to the variable website. Then, we printed out the value assigned to website i.e. apple.com
Note: Python is a type-inferred language, so you don't have to explicitly define the variable type. It automatically knows that apple.com is a string and declares the website variable as a string.

Example 2: Changing the value of a variable

website = "apple.com"
print(website)

# assigning a new variable to website
website = "programiz.com"

print(website)
Output
apple.com
programiz.com
In the above program, we have assigned apple.com to the website variable initially. Then, the value is changed to programiz.com.

Example 3: Assigning multiple values to multiple variables

a, b, c = 5, 3.2, "Hello"

print (a)
print (b)
print (c)
If we want to assign the same value to multiple variables at once, we can do this as:
x = y = z = "same"

print (x)
print (y)
print (z)
The second program assigns the same string to all the three variables xy and z

No comments:

Post a Comment