Skip to content

Learning Python: Day 2

Chapter 2:

What happens when running Hello_World.py

print(“Hello Python world!”) –> input

Hello Python world! –> output

  • .py = Python program, the editor runs the file through Python Interpreter which determines what each word means
  • for example, print() prints whatever is inside the parentheses(not Python code), print is the name of the function
  • syntax highlighting – displays different parts in different colors

Variables

  • variable in Hello_World.py

message = “Hello Python world!” –> variable = value

print(message)

Hello Python world!

  • can change the value of a variable at any time

Naming and using variables

  • variable names can only contain letters, numbers, and underscores and can’t start with a number
  • avoid using Python keywords and function names as variable names, for example, don’t use print
  • lowercase “l” and uppercase “O” can be confused with 1 and 0
  • at this stage, variables should be lowercase

Avoiding name errors when using variables

  • Every programmer makes mistakes… print(mesage) –> name error
  • traceback – a record of where the interpreter ran into trouble

Variables are labels

  • labels you can assign to values or variable references a certain value
  • Strings
  • string – series of characters, anything inside single or double quotes

Changing case in a string with methods

Name.py

name = “ada lovelcae”

print(name.title())

Ada Lovelace

  • Method – an action Python performs on a piece of data, followed by ()
  • Dot(.) after name in name.title() tells Python to make the title() method act on the variable name
  • title() method – title case
  • upper() method – uppercase
  • lower() method – lowercase, useful for storing data

Using variables in strings

  • sometimes you’ll want to use a variable’s value inside a string
  • for example, you might want to use two variables to represent a first name and a last name and then combine those values to display the full name

Full_Name.py

first_name = “ada”

last_name = “lovelace”

full_name = f”{first_name}{last_name}”

print(full_name)

ada lovelace

  • place f before opening the quotation mark to insert a variable’s value into a string
  • f-string – f is format, Python formats string by replacing the name of any variable in braces with its value
  • use f-strings to compose complete messages like a sentence to greet users

first_name = “ada”

last_name = “lovelace”

full_name = f”{first_name}{last_name}”

print(f”Hello, {full_name.title()}!”)

Hello, Ada Lovelace!

  • or

first_name = “ada”

last_name = “lovelace”

full_name = f”{first_name}{last_name}”

message = f”Hello, {full_name.title()}!”

print(message) –> cleaner print line

Hello, Ada Lovelace!

End of study session.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *