Learning Python - Part 2 - Declaring Variables and understanding strings

in #programming7 years ago (edited)

Untitled-1-Recovered.jpg
In this post you wil learn how to declare a variable and understand strings(numbers will be covered in the next post)

Variables


First, let's understand the meaning of it in Computer Science, think of it like a box, we will give that box a name for example "message", then we will store in it a word "Hello!", this is a variable, a box where you store in it words, numbers...

Now open the IDLE, File > New File and write the following:

message = "Hello!"
print(message)
Then save it and give it a name... Run(f5) this program to see what happens.
Hello!
We've added a Variable named message, it holds the value "Hello!", wich is the information associated with that variable, and when we tried to print it with the Function"print" it showed us its value.
Now let's make our program a little bigger...
Write this please:
message = "Hello!"
print(message)

message = "Hello Mr James!"
print(message)
Please Run it(f5) and you should see two lines of output:
Hello!
Hello Mr James!
You can change the value of your variables in your program at any time.

Naming Variables


-> Variable names contain only letters, numbers and underscores but can't start with numbers.
-> Spaces aren't allowed in variables, but underscores can seperate words.
-> Avoid using Python Keywords as variable names

Strings


Strings are text that might be numbers or letters that are between quotes"".

"Here is a string"
'Here is another'

Changing Case

name = "james something"
print(name.title())

James Something
The "title()" method displays each word in titlecase.
name = "James Something"
print(name.upper())
print(name.lower())

JAMES SOMETHING
james something

Combining Strings

first_name = "james"
last_name = "something"
full_name = first_name + " " + last_name
print(full_name)
Run it and it will print the following
james something
We wrote " " so that the first_name and last_name can be seperated.

Adding whitespace or tabs to strings

>>> print("Pizza")
Pizza
>>> print("/tPizza")
Pizza
But for newlines we add "/n".
>>> print("Pizza")
Pizza
>>> print("/nPizza")

Pizza

Stripping whitespace


To strip white space you declare your variable and add to it .strip().

favorite_language = ' python'
favorite_language.strip()

'python'


That is all for today's post see you in the next one!

Coin Marketplace

STEEM 0.23
TRX 0.26
JST 0.040
BTC 98004.63
ETH 3487.60
USDT 1.00
SBD 3.26