String Issue in Python - python

I would like to understand why one program of mine is giving error and one not where as I am applying same concept for both of them.
The program that is giving error:
greeting = "test"
age = 24
print( greeting + age)
Which is true and it should give error because of incompatible variable types being concatenated. But this same behavior I was expecting from the below code as well where as it is giving proper result. Why is it so?
print("Please enter your name: ")
myname = input()
print("Your name is " + myname)
print("Please enter your age: ")
myage = input()
print("Your age is: " + myage)
print("Final Outcome is:")
print(myage + " " + myname)

By default the input function in Python returns a string type. So when you enter the age, it is not being returned to your program as an int but rather a string. So:
print("Your age is: " + myage)
Actually looks like:
print("Your age is: " + "24")

input() returns a string, even if the user enters a number.

Related

what is wrong with python my python code in while loop?

I don't know what is the error of my code can anyone help me to fix this code.
age = ""
while int(len(age)) == 0:
age = int(input("Enter your age: "))
print("Your age is " + age)
You wanted a string for age but you transformed this age into an integer inside your loop :)
You can write :
age = ""
while age == "":
age = input("Enter your age: ")
print("Your age is " + age)
In Python, "" and 0 (and values like None and empty containers) are considered "falsey". Not necessarily the same thing as False but logically treated like False.
So you can simplify your while loop:
age = ""
while not age:
age = input("Enter your age: ")
print("Your age is " + age)
You cast age to be an int inside of your while loop, while using the len(age) as the comparison.
int does not have a length.
You want to wait to cast age until you are outside of the loop, or in this situation, don't cast it at all.
age = ""
while len(age) == 0:
age = input("Enter your age: ")
print("Your age is " + age)

How can I clear this error message 'expected intended block' in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a problem with my program:(python program)
A = input("What is ur name?") print("Your name is %s" %A)
print("Lets make a little calculations here")
Value1 = input('Lets enter our first value: ') print("Your value is %s" %Value1)
Value2 = input('Now enter the second value: ' ) print("The value you gave was %s" %Value2)
print("Now lets add or multiply this two values together, are yoy ready?")
Sign = input("Please select add(for addition) or multi(for multiplication): ")
print("You have selected %s " %Sign)
print("Loading result values...")
if Sign == '+':
print(Value1 + Value2)
elif Sign == '*':
print(Value1 * Value2)
It gives me the same syntax error any time. please help me.
Your code after a few fixes:
A = input("What is ur name?")
print("Your name is " + A)
print("Lets make a little calculations here")
Value1 = int(input('Lets enter our first value: '))
print("Your value is " + str(Value1))
Value2 = int(input('Now enter the second value: '))
print("The value you gave was " + str(Value2))
print("Now lets add or multiply this two values together, are yoy ready?")
Sign = input("Please select add(for addition) or multi(for multiplication): ")
print("You have selected " + Sign)
print("Loading result values...")
if Sign == '+':
print(Value1 + Value2)
elif Sign == '*':
print(Value1 * Value2)
As I understand from your code, you are new in Python, and you used C before.
In python the input method always return a String.
Also in Python instead of use "%s" in the print you can add your output like that:
print("some text" + variable_name)
The only thing you need to check that that your variables Value1 and Value2 are integers. you can cast your variable to other type in this way:
x = 1
# cast variable into string
y = str(x) # y is a string "1"
# cast variable into int
z = int(y) # z is a integer 1
Also after a if statment you need use tabs, example:
x = 1
if x == 1:
# we are inside the if
print("in if")
print("after if")
Here is the corrected Program
A = input("What is ur name?")
print("Hello %s" %A)
print("Lets make a little calculations here")
Value1 = int(input('Lets enter our first value: '))
print("Your value is %s" %Value1)
Value2 = int(input('Now enter the second value: ' ))
print("The value you gave was %s" %Value2)
print("Now lets add or multiply this two values together,\n are yoy ready?")
Sign = input("Please select addition(+) or\n multiplication(*): ")
print("You have selected %s " %Sign)
print("Loading result values...")
if Sign == '+':
Result = Value1 + Value2
print("Your result = " + str(Result))
elif Sign == '*':
Result = Value1 * Value2
print("Your result = " + str(Result))
Python uses indentation to understand your code and distinguish blocks of codes.
So, indentation is at the beginning of a code line and must be at least one space.
It's is very important in Python (it also make your code readable)
And as you said Python will give you always an error if you skip it.
A = input("What is ur name?") print("Your name is %s" %A)
print("Lets make a little calculations here")
Value1 = input('Lets enter our first value: ') print("Your value is %s" %Value1)
Value2 = input('Now enter the second value: ' ) print("The value you gave was %s" %Value2)
print("Now lets add or multiply this two values together, are yoy ready?")
Sign = input("Please select add(for addition) or multi(for multiplication): ")
print("You have selected %s " %Sign)
print("Loading result values...")
if Sign == '+':
print(Value1 + Value2)
elif Sign == '*':
print(Value1 * Value2)`
One more thing may be helpful for you is that you can write comments in your code, by putting a #write whatever you want here
Comments are words that won't be readed by Python, we use them to keep a notes, or as explanation for people who will read your code in the future.
And also it dosen't matter how many space you keep between lines of codes, Python will skip empty lines

How to remove the parenthesis and a comma in the output

I am writing a program in python for a banking application using arrays and functions. Here's my code:
NamesArray=[]
AccountNumbersArray=[]
BalanceArray=[]
def PopulateAccounts():
for position in range(5):
name = input("Please enter a name: ")
account = input("Please enter an account number: ")
balance = input("Please enter a balance: ")
NamesArray.append(name)
AccountNumbersArray.append(account)
BalanceArray.append(balance)
def SearchAccounts():
accounttosearch = input("Please enter the account number to search: ")
for position in range(5):
if (accounttosearch==AccountNumbersArray[position]):
print("Name is: " +NamesArray[position])
print(NamesArray[position],"account has the balance of: ",(BalanceArray[position]))
break
if position>4:
print("The account number not found!")
while True:
print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choice = input("Please enter your choice: ")
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
break
else:
print("Invalid choice. Please try again!")
Everything is fine now, but when I run the program and search for an account. For example, when I search an account the output shows ('name', 'account has the balance of: ', 312) instead of name account has the balance of: 312 How do I fix this?
In the line
print(NamesArray[position],"account has the balance of: ",(BalanceArray[position]))
you should use string concatenation to add the different strings. One way to do this would be like this:
print(NamesArray[position] + " account has the balance of: " + str(BalanceArray[position]))
u are using old python version,
replace your line with this :
print(NamesArray[position] + "account has the balance of: " + (BalanceArray[position]))
use ' + ' instead of comma

python random numbers and comparison

I'm a new programmer and just starting off with Python. I have the following 2 questions, however, I decided to put them in one post.
When asking to input age, how do I force the program to only accept numbers?
The concept is that after the user has entered their age, the program would pick a random number between 1 and 100 and compare it to the user input, returning either "I'm older than you", "I'm younger than you" or "we are the same age".
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
age = input("How old are you? ")
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
random.randint(1, 100)
Try the following
import random
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
while True: # only numbers
try:
age = int(input("How old are you? "))
except:
pass
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
t=random.randint(1, 100)
if t==age:
print("we are the same age") #compare ages
if t<age:
print("I'm younger than you")
if t>age:
print("I'm older than you")
Hi you can try this simply.
import random
name = input("What is your name? ")
print("Hello " + str(name))
while True :
try :
age = int(input("How old are you? "))
break
except :
print("Your entered age is not integer. Please try again.")
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
randNumber=random.randint(1, 100)
if randNumber > age :
print("I am older than you")
if randNumber < age :
print("I am younger than you")
else :
print("we are the same age")
Only made few changes to existing code with modifications asked.
import random
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
while True:
try:
age = int(input("How old are you? "))
except ValueError:
pass
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
my_random = random.randint(1, 100)
if my_random > age:
print("Im older than you")
elif my_random < age:
print("I'm younger than you")
else:
print("We are the same age")
Includ a try block around the age part. If the user inputs an non-int answer then it will just pass. I then saved the random int that you generated it and compared it to the age to find if the random int was greater than the age.
To answer your first question, use int() as such:
age = int(input("How old are you? "))
This will raise an exception (error) if the value is not an integer.
To answer your second question, you may store the random number in a variable and use it in comparison to the user's age, using conditional statements (if, elif, else). So for instance:
random.seed() # you need to seed the random number generator
n = random.randint(1, 100)
if n < age:
print("I am younger than you.")
elif n > age:
print("I am older than you.")
else:
print("We are the same age.")
I hope this answers your question. You can refer to the official Python docs for more info on conditional statements.
My guess is that you should convert the variable age into integer. For example:
age = input("How old are you?")
age = int(age)
This should work.
The answer to the 1st question.
x = int(input("Enter any number: "))
To force the program to enter number add int in your input statement as above.

Simple raw_input and conditions

I created the simple code:
name = raw_input("Hi. What's your name? \nType name: ")
age = raw_input("How old are you " + name + "? \nType age: ")
if age >= 21
print "Margaritas for everyone!!!"
else:
print "NO alcohol for you, young one!!!"
raw_input("\nPress enter to exit.")
It works great until I get to the 'if' statement... it tells me that I am using invalid syntax.
I am trying to learn how to use Python, and have messed around with the code quite a bit, but I can't figure out what I did wrong (probably something very basic).
It should be something like this:
name = raw_input("Hi. What's your name? \nType name: ")
age = raw_input("How old are you " + name + "? \nType age: ")
age = int(age)
if age >= 21:
print "Margaritas for everyone!!!"
else:
print "NO alcohol for you, young one!!!"
raw_input("\nPress enter to exit.")
You were missing the colon. Also, you should cast age from string to int.
Hope this helps!
With python, indentation is very important. You have to use the correct indentation or it won't work. Also, you need a : after the if and else
try:
if age >= 21:
print #string
else:
print #other string
Firstly raw_input returns a string not integer, so use int(). Otherwise the if-condition if age >= 21 is always going to be False.:
>>> 21 > ''
False
>>> 21 > '1'
False
Code:
name = raw_input("Hi. What's your name? \nType name: ")
age = int(raw_input("How old are you " + name + "? \nType age: "))
The syntax error is there because you forgot a : on the if line.
if age >= 21
^
|
colon missing

Categories

Resources