Sunday, April 20, 2025

Python Variables, Contexts

Sure, while practicing you can use abstract/short variable names like, x, y, z, a, b, c, and so on:


x = "Actual Data"

print(x)

But, better option is to use variable names that describe what they contain:


name = "John"
lastname = "Snow"

print(name)
print(lastname)

We can use (print in this case) variables one after another - on single line. Make sure to have a comma to separate them:


name = "John"
lastname = "Snow"

print(name, lastname)

Underscores will work as part of variable names, but having a lot of them connected is silly.

Variables can hold numbers, too:


name = "John"
last____name = "Snow"

number = 5
pi = 3.14

print(name, last____name)
print(number, pi)

Mathematical operations can be done directly:


x = 5
y = 10

print(x + y)

We can use one variable multiple times:


x = 5
y = 10

print(x + y + x + y)

For complicated formulas enclose parts in a dedicated parenthesis:


x = 5
y = 10

print((x + x) + (y + y))

We can have numbers treated as letters - if we enclose them in quotes.

In this context, result will be a concatenation of numbers, because they are treated as characters, and not numbers:


x = "5"
y = "10"

print(x + y)

Result when numbers are used as letters:


510
>>> 

Don't worry about contexts, over time they will become intuitive.

In next tutorial we will talk about concatenation and how to detect data types in variables.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...