Posts

Showing posts from March, 2023

Inputs and Outputs Basics

  Cheat Sheet Inputs and Outputs Basics Take Input From User input() allows flexibility to take the input from the user. Reads a line of input as a string. Code: username = input() print(username) Input Ajay Output Ajay Working with Strings String Concatenation Joining strings together is called string concatenation. Code a = "Hello" + " " + "World" print(a) Output: Hello World Concatenation Errors String Concatenation is possible only with strings. Code: a = "*" + 10 print(a) Output: File "main.py", line 1 a = "*" + 10 ^ TypeError: can only concatenate str (not "int") to str String Repetition * operator is used for repeating strings any number of times as required. Code: a = "*" * 10 print(a) Output: ********** Code: s = "Python" s = ("* " * 3) + s + (" *" * 3) print(s) Output: * * * Python * * * Length of String len() returns the number of characters in a given string. Code: ...

Sequence of Instructions

  Cheat Sheet Sequence of Instructions Program A program is a sequence of instructions given to a computer. Defining a Variable A variable gets created when you assign a value to it for the first time. Code age = 10 Printing Value in a Variable Code age = 10 print(age) Output 10 Code age = 10 print("age") Output age Variable name enclosed in quotes will print variable rather than the value in it. If you intend to print value, do not enclose the variable in quotes. Order of Instructions Python executes the code line-by-line. Code print(age) age = 10 Output NameError: name 'age' is not defined Variable 'age' is not created by the time we tried to print. Spacing in Python Having spaces at the beginning of line causes errors. Code a = 10 * 5 b = 5 * 0.5 b = a + b Output File "main.py", line 3 b = a + b ^ IndentationError: unexpected indent Variable Assignment Values in the variables can be changed. Code a = 1 print(a) a = 2 print(a) Output 1 2 Examples ...