Python Comment and Variables

 

Python Comments

Comments can be used to explain Python code.

Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.


Creating a Comment

Comments starts with a #, and Python will ignore them:

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


Comments can be placed at the end of a line, and Python will ignore the rest of the line:

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


A comment does not have to be text that explains the code, it can also be used to prevent Python from executing code:


#print("Hello, World!")
print("Cheers, Mate!")



Multiline Comments

Python does not really have a syntax for multiline comments.

To add a multiline comment you could insert a # for each line:

#This is a comment
#written in
#more than just one line
print("Hello, World!")




Multiple Assignment

Python allows you to assign a single value to several variables simultaneously which means you can create multiple variables at a time. For example −

a = b = c = 100 print (a) print (b) print (c)

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example −

a,b,c = 1,2,"Zara Ali" print (a) print (b) print (c)

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "Zara Ali" is assigned to the variable c.



Variables

Variables are containers for storing data values.


Creating Variables

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

x = 5
y = "John"
print(x)
print(y)


Variables do not need to be declared with any particular type, and can even change type after they have been set.

x = 4       # x is of type int
x = "Sally" # x is now of type str
print(x)


Casting

If you want to specify the data type of a variable, this can be done with casting.

x = str(3)

y = int(3)

z = float(3)


print(x)

print(y)

print(z)






Get the Type

You can get the data type of a variable with the type() function.

x = 5
y = "John"
print(type(x))
print(type(y))




Single or Double Quotes?

String variables can be declared either by using single or double quotes:

x = "John"

print(x)

#double quotes are the same as single quotes:

x = 'John'

print(x)




Case-Sensitive

Variable names are case-sensitive.

Example

This will create two variables:

a = 4
A = "Sally"

print(a)

print(A)

#A will not overwrite a

Post a Comment

[blogger]

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget