Linux (28) Python (13) Raspberry Pi (5) Bugs (3) Install (3) C (2) Brainf**k (1) HTML (1) Maths (1) Sorts (1)

Sunday, 26 June 2016

Python 3: Lesson 2 Basics

This lesson will include:
  • Input
  • Output
  • Storing values in variables
  • A combination of the above.
Variables are used to hold data within the program. In python you do not need to assign it to a certain data type as this is done automatically.
Example Use:
a = 5                 #This would be defined as an integer
b = "Hello, World"    #This would be defined as a string
c = 5.000             #This would be defined as a float

To allow the users to input data into the program we use the input() function. Most of the time this will be paired up with assigning it to a variable to store the data.
Example Use:

name = input("Please enter your name: ")

The "Please enter your name: " is the prompt that tells the user what the program is asking for.

To allow the program to output data from the program.
Example Use:

print("Hello, World!")
print(name) In this case the contents of the variable "name" will be printed to the screen

Combination of all three
We will now create a program that uses variables input and output.
First off we will get the user to input some data.

name = input("Please enter your name: ")
age = input("How old are you?: ")

We have now got two things from them, their name(stored in the variable "name") and their age(stored in the variable "age").

We can now print this variables out with a print statement.
print("Hello",name,"you are",age, "years old")

You now have a program that will ask the user their name and age and print out the output of both of these in a sentence.

No comments:

Post a comment