Knowledge in Python

Python Variables

Python VariablesCreating VariablesVariables are containers for storing data values.Unlike other programming languages, Python has no command for declaring a variable.A variable is created the moment you first assign a value to it.Example 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.Example x = 4 # x is of type int x = "Sally" # x is now of type str print(x) String variables can be declared either by using single or double quotes:Example x = "John"# is the same asx = 'John'

Assign Value to Multiple Variables

Assign Value to Multiple VariablesPython allows you to assign values to multiple variables in one line:Example x, y, z = "Orange", "Banana", "Cherry"print(x)print(y)print(z) And you can assign the same value to multiple variables in one line:Example x = y = z = "Orange"print(x)print(y)print(z) Output VariablesThe Python print statement is often used to output variables.To combine both text and a variable, Python uses the + character:Example x = "awesome"print("Python is " + x) You can also use the + character to add a variable to another variable:Example x = "Python is "y = "awesome"z = x + y print(z) For numbers, the + character works as a mathematical operator:Example x = 5y = 10print(x + y) If you try to combine a string and a number, Python will give you an error:Example x = 5y = "John"print(x + y)

Global Variables

Global VariablesVariables that are created outside of a function (as in all of the examples above) are known as global variables.Global variables can be used by everyone, both inside of functions and outside.ExampleCreate a variable outside of a function, and use it inside the function x = "awesome" def myfunc(): print("Python is " + x)myfunc() If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.ExampleCreate a variable inside a function, with the same name as the global variable x = "awesome" def myfunc(): x = "fantastic" print("Python is " + x)myfunc() print("Python is " + x)

The global Keyword

The global KeywordNormally, when you create a variable inside a function, that variable is local, and can only be used inside that function.To create a global variable inside a function, you can use the global keyword.ExampleIf you use the global keyword, the variable belongs to the global scope: def myfunc(): global x x = "fantastic"myfunc() print("Python is " + x) Also, use the global keyword if you want to change a global variable inside a function.ExampleTo change the value of a global variable inside a function, refer to the variable by using the global keyword: x = "awesome"def myfunc(): global x x = "fantastic"myfunc() print("Python is " + x)

Python Data Types

Python Data TypesBuilt-in Data TypesIn programming, data type is an important concept.Variables can store data of different types, and different types can do different things.Python has the following data types built-in by default, in these categories: Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview Getting the Data TypeYou can get the data type of any object by using the type() function:ExamplePrint the data type of the variable x: x = 5 print(type(x))

Python Numbers

Python NumbersPython NumbersThere are three numeric types in Python:intfloatcomplexVariables of numeric types are created when you assign a value to them:Example x = 1    # inty = 2.8 # floatz = 1j  # complex To verify the type of any object in Python, use the type() function:Example print(type(x))print(type(y))print(type(z))

python numbers

IntInt, or integer, is a whole number, positive or negative, without decimals, of unlimited length.ExampleIntegers: x = 1y = 35656222554887711z = -3255522print(type(x))print(type(y))print(type(z)) FloatFloat, or "floating point number" is a number, positive or negative, containing one or more decimals.ExampleFloats: x = 1.10y = 1.0z = -35.59print(type(x))print(type(y))print(type(z)) Float can also be scientific numbers with an "e" to indicate the power of 10.ExampleFloats: x = 35e3y = 12E4z = -87.7e100print(type(x))print(type(y)) print(type(z))

Complex

ComplexComplex numbers are written with a "j" as the imaginary part:ExampleComplex: x = 3+5jy = 5jz = -5jprint(type(x))print(type(y)) print(type(z)) Type ConversionYou can convert from one type to another with the int(), float(), and complex() methods:ExampleConvert from one type to another: x = 1 # inty = 2.8 # floatz = 1j # complex#convert from int to float: a = float(x)#convert from float to int: b = int(y)#convert from int to complex:c = complex(x)print(a)print(b) print(c)print(type(a))print(type(b)) print(type(c))

Random Number

Random Numberython does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers:ExampleImport the random module, and display a random number between 1 and 9: import randomprint(random.randrange(1,10))

Python Casting

Python CastingSpecify a Variable TypeThere may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.Casting in python is therefore done using constructor functions:int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)str() - constructs a string from a wide variety of data types, including strings, integer literals and float literalsExampleIntegers: x = int(1)  # x will be 1 y = int(2.8) # y will be 2 z = int("3") # z will be 3 ExampleFloats: x = float(1)    # x will be 1.0 y = float(2.8)  # y will be 2.8 z = float("3")  # z will be 3.0 w = float("4.2") # w will be 4.2 ExampleStrings: x = str("s1") # x will be 's1' y = str(2)   # y will be '2' z = str(3.0) # z will be '3.0'

Python Strings

Python StringsString LiteralsString literals in python are surrounded by either single quotation marks, or double quotation marks.'hello' is the same as "hello".You can display a string literal with the print() function:Example print("Hello") print('Hello') Assign String to a VariableAssigning a string to a variable is done with the variable name followed by an equal sign and the string:Example a = "Hello"print(a) Multiline StringsYou can assign a multiline string to a variable by using three quotes:ExampleYou can use three double quotes: a = """Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididuntut labore et dolore magna aliqua."""print(a) Or three single quotes:Example a = '''Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididuntut labore et dolore magna aliqua.'''print(a)

Strings are Arrays

Strings are ArraysLike many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.However, Python does not have a character data type, a single character is simply a string with a length of 1.Square brackets can be used to access elements of the string.ExampleGet the character at position 1 (remember that the first character has the position 0): a = "Hello, World!" print(a[1]) SlicingYou can return a range of characters by using the slice syntax.Specify the start index and the end index, separated by a colon, to return a part of the string.ExampleGet the characters from position 2 to position 5 (not included): b = "Hello, World!" print(b[2:5]) Negative IndexingUse negative indexes to start the slice from the end of the string:ExampleGet the characters from position 5 to position 1, starting the count from the end of the string: b = "Hello, World!" print(b[-5:-2]) String LengthTo get the length of a string, use the len() function.ExampleThe len() function returns the length of a string: a = "Hello, World!" print(len(a))